• Home
  • History
  • Annotate
Name Date Size #Lines LOC

..--

host_test/11-Mar-2024-1,432994

include/11-Mar-2024-1,088210

mock/int/11-Mar-2024-9956

nvs_partition_generator/11-Mar-2024-1,7251,281

src/11-Mar-2024-5,5423,902

test/11-Mar-2024-559412

test_nvs_host/11-Mar-2024-5,4084,139

.gitignoreD11-Mar-2024118 87

CMakeLists.txtD11-Mar-20242 KiB5244

KconfigD11-Mar-2024481 1311

README.rstD11-Mar-202423.6 KiB341218

README_CN.rstD11-Mar-202418.8 KiB304197

component.mkD11-Mar-2024164 125

README.rst

1Non-volatile storage library
2============================
3
4:link_to_translation:`zh_CN:[中文]`
5
6Introduction
7------------
8
9Non-volatile storage (NVS) library is designed to store key-value pairs in flash. This section introduces some concepts used by NVS.
10
11
12Underlying storage
13^^^^^^^^^^^^^^^^^^
14
15Currently, NVS uses a portion of main flash memory through ``spi_flash_{read|write|erase}`` APIs. The library uses all the partitions with ``data`` type and ``nvs`` subtype. The application can choose to use the partition with the label ``nvs`` through the ``nvs_open`` API function or any other partition by specifying its name using the ``nvs_open_from_part`` API function.
16
17Future versions of this library may have other storage backends to keep data in another flash chip (SPI or I2C), RTC, FRAM, etc.
18
19.. note:: if an NVS partition is truncated (for example, when the partition table layout is changed), its contents should be erased. ESP-IDF build system provides a ``idf.py erase_flash`` target to erase all contents of the flash chip.
20
21.. note:: NVS works best for storing many small values, rather than a few large values of the type 'string' and 'blob'. If you need to store large blobs or strings, consider using the facilities provided by the FAT filesystem on top of the wear levelling library.
22
23
24Keys and values
25^^^^^^^^^^^^^^^
26
27NVS operates on key-value pairs. Keys are ASCII strings; the maximum key length is currently 15 characters. Values can have one of the following types:
28
29-  integer types: ``uint8_t``, ``int8_t``, ``uint16_t``, ``int16_t``, ``uint32_t``, ``int32_t``, ``uint64_t``, ``int64_t``
30-  zero-terminated string
31-  variable length binary data (blob)
32
33.. note::
34
35    String values are currently limited to 4000 bytes. This includes the null terminator. Blob values are limited to 508000 bytes or 97.6% of the partition size - 4000 bytes, whichever is lower.
36
37Additional types, such as ``float`` and ``double`` might be added later.
38
39Keys are required to be unique. Assigning a new value to an existing key works as follows:
40
41-  if the new value is of the same type as the old one, value is updated
42-  if the new value has a different data type, an error is returned
43
44Data type check is also performed when reading a value. An error is returned if the data type of the read operation does not match the data type of the value.
45
46
47Namespaces
48^^^^^^^^^^
49
50To mitigate potential conflicts in key names between different components, NVS assigns each key-value pair to one of namespaces. Namespace names follow the same rules as key names, i.e., the maximum length is 15 characters. Namespace name is specified in the ``nvs_open`` or ``nvs_open_from_part`` call. This call returns an opaque handle, which is used in subsequent calls to the ``nvs_get_*``, ``nvs_set_*``, and ``nvs_commit`` functions. This way, a handle is associated with a namespace, and key names will not collide with same names in other namespaces.
51Please note that the namespaces with the same name in different NVS partitions are considered as separate namespaces.
52
53
54Security, tampering, and robustness
55^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
56
57NVS is not directly compatible with the ESP32 flash encryption system. However, data can still be stored in encrypted form if NVS encryption is used together with ESP32 flash encryption. Please refer to :ref:`nvs_encryption` for more details.
58
59If NVS encryption is not used, it is possible for anyone with physical access to the flash chip to alter, erase, or add key-value pairs. With NVS encryption enabled, it is not possible to alter or add a key-value pair and get recognized as a valid pair without knowing corresponding NVS encryption keys. However, there is no tamper-resistance against the erase operation.
60
61The library does try to recover from conditions when flash memory is in an inconsistent state. In particular, one should be able to power off the device at any point and time and then power it back on. This should not result in loss of data, except for the new key-value pair if it was being written at the moment of powering off. The library should also be able to initialize properly with any random data present in flash memory.
62
63
64Internals
65---------
66
67Log of key-value pairs
68^^^^^^^^^^^^^^^^^^^^^^
69
70NVS stores key-value pairs sequentially, with new key-value pairs being added at the end. When a value of any given key has to be updated, a new key-value pair is added at the end of the log and the old key-value pair is marked as erased.
71
72Pages and entries
73^^^^^^^^^^^^^^^^^
74
75NVS library uses two main entities in its operation: pages and entries. Page is a logical structure which stores a portion of the overall log. Logical page corresponds to one physical sector of flash memory. Pages which are in use have a *sequence number* associated with them. Sequence numbers impose an ordering on pages. Higher sequence numbers correspond to pages which were created later. Each page can be in one of the following states:
76
77Empty/uninitialized
78    Flash storage for the page is empty (all bytes are ``0xff``). Page is not used to store any data at this point and does not have a sequence number.
79
80Active
81    Flash storage is initialized, page header has been written to flash, page has a valid sequence number. Page has some empty entries and data can be written there. No more than one page can be in this state at any given moment.
82
83Full
84    Flash storage is in a consistent state and is filled with key-value pairs.
85    Writing new key-value pairs into this page is not possible. It is still possible to mark some key-value pairs as erased.
86
87Erasing
88    Non-erased key-value pairs are being moved into another page so that the current page can be erased. This is a transient state, i.e., page should never stay in this state at the time when any API call returns. In case of a sudden power off, the move-and-erase process will be completed upon the next power-on.
89
90Corrupted
91    Page header contains invalid data, and further parsing of page data was canceled. Any items previously written into this page will not be accessible. The corresponding flash sector will not be erased immediately and will be kept along with sectors in *uninitialized* state for later use. This may be useful for debugging.
92
93Mapping from flash sectors to logical pages does not have any particular order. The library will inspect sequence numbers of pages found in each flash sector and organize pages in a list based on these numbers.
94
95::
96
97    +--------+     +--------+     +--------+     +--------+
98    | Page 1 |     | Page 2 |     | Page 3 |     | Page 4 |
99    | Full   +---> | Full   +---> | Active |     | Empty  |   <- states
100    | #11    |     | #12    |     | #14    |     |        |   <- sequence numbers
101    +---+----+     +----+---+     +----+---+     +---+----+
102        |               |              |             |
103        |               |              |             |
104        |               |              |             |
105    +---v------+  +-----v----+  +------v---+  +------v---+
106    | Sector 3 |  | Sector 0 |  | Sector 2 |  | Sector 1 |    <- physical sectors
107    +----------+  +----------+  +----------+  +----------+
108
109Structure of a page
110^^^^^^^^^^^^^^^^^^^
111
112For now, we assume that flash sector size is 4096 bytes and that ESP32 flash encryption hardware operates on 32-byte blocks. It is possible to introduce some settings configurable at compile-time (e.g., via menuconfig) to accommodate flash chips with different sector sizes (although it is not clear if other components in the system, e.g., SPI flash driver and SPI flash cache can support these other sizes).
113
114Page consists of three parts: header, entry state bitmap, and entries themselves. To be compatible with ESP32 flash encryption, entry size is 32 bytes. For integer types, entry holds one key-value pair. For strings and blobs, an entry holds part of key-value pair (more on that in the entry structure description).
115
116The following diagram illustrates the page structure. Numbers in parentheses indicate the size of each part in bytes. ::
117
118    +-----------+--------------+-------------+-------------------------+
119    | State (4) | Seq. no. (4) | version (1) | Unused (19) | CRC32 (4) |   Header (32)
120    +-----------+--------------+-------------+-------------------------+
121    |                Entry state bitmap (32)                           |
122    +------------------------------------------------------------------+
123    |                       Entry 0 (32)                               |
124    +------------------------------------------------------------------+
125    |                       Entry 1 (32)                               |
126    +------------------------------------------------------------------+
127    /                                                                  /
128    /                                                                  /
129    +------------------------------------------------------------------+
130    |                       Entry 125 (32)                             |
131    +------------------------------------------------------------------+
132
133Page header and entry state bitmap are always written to flash unencrypted. Entries are encrypted if flash encryption feature of ESP32 is used.
134
135Page state values are defined in such a way that changing state is possible by writing 0 into some of the bits. Therefore it is not necessary to erase the page to change its state unless that is a change to the *erased* state.
136
137The version field in the header reflects the NVS format version used. For backward compatibility reasons, it is decremented for every version upgrade starting at 0xff (i.e., 0xff for version-1, 0xfe for version-2 and so on).
138
139CRC32 value in the header is calculated over the part which does not include a state value (bytes 4 to 28). The unused part is currently filled with ``0xff`` bytes.
140
141The following sections describe the structure of entry state bitmap and entry itself.
142
143Entry and entry state bitmap
144^^^^^^^^^^^^^^^^^^^^^^^^^^^^
145
146Each entry can be in one of the following three states represented with two bits in the entry state bitmap. The final four bits in the bitmap (256 - 2 * 126) are not used.
147
148Empty (2'b11)
149    Nothing is written into the specific entry yet. It is in an uninitialized state (all bytes are ``0xff``).
150
151Written (2'b10)
152    A key-value pair (or part of key-value pair which spans multiple entries) has been written into the entry.
153
154Erased (2'b00)
155    A key-value pair in this entry has been discarded. Contents of this entry will not be parsed anymore.
156
157
158.. _structure_of_entry:
159
160Structure of entry
161^^^^^^^^^^^^^^^^^^
162
163For values of primitive types (currently integers from 1 to 8 bytes long), entry holds one key-value pair. For string and blob types, entry holds part of the whole key-value pair. For strings, in case when a key-value pair spans multiple entries, all entries are stored in the same page. Blobs are allowed to span over multiple pages by dividing them into smaller chunks. For tracking these chunks, an additional fixed length metadata entry is stored called "blob index". Earlier formats of blobs are still supported (can be read and modified). However, once the blobs are modified, they are stored using the new format.
164
165::
166
167    +--------+----------+----------+----------------+-----------+---------------+----------+
168    | NS (1) | Type (1) | Span (1) | ChunkIndex (1) | CRC32 (4) |    Key (16)   | Data (8) |
169    +--------+----------+----------+----------------+-----------+---------------+----------+
170
171                                             Primitive  +--------------------------------+
172                                            +-------->  |     Data (8)                   |
173                                            | Types     +--------------------------------+
174                       +-> Fixed length --
175                       |                    |           +---------+--------------+---------------+-------+
176                       |                    +-------->  | Size(4) | ChunkCount(1)| ChunkStart(1) | Rsv(2)|
177        Data format ---+                    Blob Index  +---------+--------------+---------------+-------+
178                       |
179                       |                             +----------+---------+-----------+
180                       +->   Variable length   -->   | Size (2) | Rsv (2) | CRC32 (4) |
181                            (Strings, Blob Data)     +----------+---------+-----------+
182
183
184Individual fields in entry structure have the following meanings:
185
186NS
187    Namespace index for this entry. For more information on this value, see the section on namespaces implementation.
188
189Type
190    One byte indicating the value data type. See the ``ItemType`` enumeration in ``nvs_types.h`` for possible values.
191
192Span
193    Number of entries used by this key-value pair. For integer types, this is equal to 1. For strings and blobs, this depends on value length.
194
195ChunkIndex
196    Used to store the index of a blob-data chunk for blob types. For other types, this should be ``0xff``.
197
198CRC32
199    Checksum calculated over all the bytes in this entry, except for the CRC32 field itself.
200
201Key
202    Zero-terminated ASCII string containing a key name. Maximum string length is 15 bytes, excluding a zero terminator.
203
204Data
205    For integer types, this field contains the value itself. If the value itself is shorter than 8 bytes, it is padded to the right, with unused bytes filled with ``0xff``.
206
207    For "blob index" entry, these 8 bytes hold the following information about data-chunks:
208
209    - Size
210        (Only for blob index.) Size, in bytes, of complete blob data.
211
212    - ChunkCount
213        (Only for blob index.) Total number of blob-data chunks into which the blob was divided during storage.
214
215    - ChunkStart
216        (Only for blob index.) ChunkIndex of the first blob-data chunk of this blob. Subsequent chunks have chunkIndex incrementally allocated (step of 1).
217
218    For string and blob data chunks, these 8 bytes hold additional data about the value, which are described below:
219
220    - Size
221        (Only for strings and blobs.) Size, in bytes, of actual data. For strings, this includes zero terminators.
222
223    - CRC32
224        (Only for strings and blobs.) Checksum calculated over all bytes of data.
225
226Variable length values (strings and blobs) are written into subsequent entries, 32 bytes per entry. The `Span` field of the first entry indicates how many entries are used.
227
228
229Namespaces
230^^^^^^^^^^
231
232As mentioned above, each key-value pair belongs to one of the namespaces. Namespace identifiers (strings) are stored as keys of key-value pairs in namespace with index 0. Values corresponding to these keys are indexes of these namespaces.
233
234::
235
236    +-------------------------------------------+
237    | NS=0 Type=uint8_t Key="wifi" Value=1      |   Entry describing namespace "wifi"
238    +-------------------------------------------+
239    | NS=1 Type=uint32_t Key="channel" Value=6  |   Key "channel" in namespace "wifi"
240    +-------------------------------------------+
241    | NS=0 Type=uint8_t Key="pwm" Value=2       |   Entry describing namespace "pwm"
242    +-------------------------------------------+
243    | NS=2 Type=uint16_t Key="channel" Value=20 |   Key "channel" in namespace "pwm"
244    +-------------------------------------------+
245
246
247Item hash list
248^^^^^^^^^^^^^^
249
250To reduce the number of reads from flash memory, each member of the Page class maintains a list of pairs: item index; item hash. This list makes searches much quicker. Instead of iterating over all entries, reading them from flash one at a time, ``Page::findItem`` first performs a search for the item hash in the hash list. This gives the item index within the page if such an item exists. Due to a hash collision, it is possible that a different item will be found. This is handled by falling back to iteration over items in flash.
251
252Each node in the hash list contains a 24-bit hash and 8-bit item index. Hash is calculated based on item namespace, key name, and ChunkIndex. CRC32 is used for calculation; the result is truncated to 24 bits. To reduce the overhead for storing 32-bit entries in a linked list, the list is implemented as a double-linked list of arrays. Each array holds 29 entries, for the total size of 128 bytes, together with linked list pointers and a 32-bit count field. The minimum amount of extra RAM usage per page is therefore 128 bytes; maximum is 640 bytes.
253
254.. _nvs_encryption:
255
256NVS Encryption
257--------------
258
259Data stored in NVS partitions can be encrypted using AES-XTS in the manner similar to the one mentioned in disk encryption standard IEEE P1619. For the purpose of encryption, each entry is treated as one `sector` and relative address of the entry (w.r.t. partition-start) is fed to the encryption algorithm as `sector-number`. The NVS Encryption can be enabled by enabling :ref:`CONFIG_NVS_ENCRYPTION`. The keys required for NVS encryption are stored in yet another partition, which is protected using :doc:`Flash Encryption <../../security/flash-encryption>`. Therefore, enabling :doc:`Flash Encryption <../../security/flash-encryption>` is a prerequisite for NVS encryption.
260
261The NVS Encryption is enabled by default when :doc:`Flash Encryption <../../security/flash-encryption>` is enabled. This is done because WiFi driver stores credentials (like SSID and passphrase) in the default NVS partition. It is important to encrypt them as default choice if platform level encryption is already enabled.
262
263For using NVS encryption, the partition table must contain the :ref:`nvs_key_partition`. Two partition tables containing the :ref:`nvs_key_partition` are provided for NVS encryption under the partition table option (menuconfig->Partition Table). They can be selected with the project configuration menu (``idf.py menuconfig``). Please refer to the example :example:`security/flash_encryption` for how to configure and use NVS encryption feature.
264
265.. _nvs_key_partition:
266
267NVS key partition
268^^^^^^^^^^^^^^^^^
269
270    An application requiring NVS encryption support needs to be compiled with a key-partition of the type `data` and subtype `key`. This partition should be marked as `encrypted`. Refer to :doc:`Partition Tables <../../api-guides/partition-tables>` for more details. Two additional partition tables which contain the :ref:`nvs_key_partition` are provided under the partition table option (menuconfig->Partition Table). They can be directly used for :ref:`nvs_encryption`. The structure of these partitions is depicted below.
271
272::
273
274    +-----------+--------------+-------------+----+
275    |              XTS encryption key(32)         |
276    +---------------------------------------------+
277    |              XTS tweak key (32)             |
278    +---------------------------------------------+
279    |                  CRC32(4)                   |
280    +---------------------------------------------+
281
282The XTS encryption keys in the :ref:`nvs_key_partition` can be generated with one of the following two ways.
283
2841. Generate the keys on the ESP chip:
285
286    When NVS encryption is enabled the :cpp:func:`nvs_flash_init` API function can be used to initialize the encrypted default NVS partition. The API function internally generates the XTS encryption keys on the ESP chip. The API function finds the first :ref:`nvs_key_partition`.
287    Then the API function automatically generates and stores the nvs keys in that partition by making use of the :cpp:func:`nvs_flash_generate_keys` API function provided by ``nvs_flash.h``. New keys are generated and stored only when the respective key partiton is empty. The same key partition can then be used to read the security configurations for initializing a custom encrypted NVS partition with help of :cpp:func:`nvs_flash_secure_init_partition`.
288
289    The API functions :cpp:func:`nvs_flash_secure_init` and :cpp:func:`nvs_flash_secure_init_partition` do not generate the keys internally. When these API functions are used for initializing encrypted NVS partitions, the keys can be generated after startup using the :cpp:func:`nvs_flash_generate_keys` API function provided by ``nvs_flash.h``. The API function will then write those keys onto the key-partition in encrypted form.
290
2912. Use pre-generated key partition:
292
293    This option will be required by the user when keys in the :ref:`nvs_key_partition` are not generated by the application. The :ref:`nvs_key_partition` containing the XTS encryption keys can be generated with the help of :doc:`NVS Partition Generator Utility</api-reference/storage/nvs_partition_gen>`. Then the user can store the pre generated key partition on the flash with help of the following two commands:
294
295    i) Build and flash the partition table
296    ::
297
298        idf.py partition_table partition_table-flash
299
300    ii) Store the keys in the :ref:`nvs_key_partition` (on the flash) with the help of :component_file:`parttool.py<partition_table/parttool.py>` (see Partition Tool section in :doc:`partition-tables </api-guides/partition-tables>` for more details)
301    ::
302
303        parttool.py --port /dev/ttyUSB0 --partition-table-offset "nvs_key partition offset" write_partition --partition-name="name of nvs_key partition" --input "nvs_key partition"
304
305Since the key partition is marked as `encrypted` and :doc:`Flash Encryption <../../security/flash-encryption>` is enabled, the bootloader will encrypt this partition using flash encryption key on the first boot.
306
307It is possible for an application to use different keys for different NVS partitions and thereby have multiple key-partitions. However, it is a responsibility of the application to provide correct key-partition/keys for the purpose of encryption/decryption.
308
309Encrypted Read/Write
310^^^^^^^^^^^^^^^^^^^^
311
312The same NVS API functions ``nvs_get_*`` or ``nvs_set_*`` can be used for reading of, and writing to an encrypted nvs partition as well.
313
314**Encrypt the default NVS partition:**
315To enable encryption for the default NVS partition no additional steps are necessary. When :ref:`CONFIG_NVS_ENCRYPTION` is enabled, the :cpp:func:`nvs_flash_init` API function internally performs some additional steps using the first :ref:`nvs_key_partition` found to enable encryption for the default NVS partition (refer to the API documentation for more details). Alternatively, :cpp:func:`nvs_flash_secure_init` API function can also be used to enable encryption for the default NVS partition.
316
317**Encrypt a custom NVS partition:**
318To enable encryption for a custom NVS partition, :cpp:func:`nvs_flash_secure_init_partition` API function is used instead of :cpp:func:`nvs_flash_init_partition`.
319
320When :cpp:func:`nvs_flash_secure_init` and :cpp:func:`nvs_flash_secure_init_partition` API functions are used, the applications are expected to follow the steps below in order to perform NVS read/write operations with encryption enabled.
321
322    1. Find key partition and NVS data partition using ``esp_partition_find*`` API functions.
323    2. Populate the ``nvs_sec_cfg_t`` struct using the ``nvs_flash_read_security_cfg`` or ``nvs_flash_generate_keys`` API functions.
324    3. Initialise NVS flash partition using the ``nvs_flash_secure_init`` or ``nvs_flash_secure_init_partition`` API functions.
325    4. Open a namespace using the ``nvs_open`` or ``nvs_open_from_part`` API functions.
326    5. Perform NVS read/write operations using ``nvs_get_*`` or ``nvs_set_*``.
327    6. Deinitialise an NVS partition using ``nvs_flash_deinit``.
328
329NVS iterators
330^^^^^^^^^^^^^
331
332Iterators allow to list key-value pairs stored in NVS, based on specified partition name, namespace, and data type.
333
334There are the following functions available:
335
336- ``nvs_entry_find`` returns an opaque handle, which is used in subsequent calls to the ``nvs_entry_next`` and ``nvs_entry_info`` functions.
337- ``nvs_entry_next`` returns iterator to the next key-value pair.
338- ``nvs_entry_info`` returns information about each key-value pair
339
340If none or no other key-value pair was found for given criteria, ``nvs_entry_find`` and ``nvs_entry_next`` return NULL. In that case, the iterator does not have to be released. If the iterator is no longer needed, you can release it by using the function ``nvs_release_iterator``.
341

README_CN.rst

1非易失性存储库
2============================
3
4:link_to_translation:`en:[English]`
5
6简介
7------------
8
9非易失性存储 (NVS) 库主要用于在 flash 中存储键值格式的数据。本文档将详细介绍 NVS 常用的一些概念。
10
11底层存储
12^^^^^^^^^^^^^^^^^^
13
14NVS 通过调用 ``spi_flash_{read|write|erase}`` API 对主 flash 的部分空间进行读、写、擦除操作,包括 ``data`` 类型和 ``nvs`` 子类型的所有分区。应用程序可调用 ``nvs_open`` API 选择使用带有 ``nvs`` 标签的分区,也可以通过调用 ``nvs_open_from_part`` API 选择使用指定名称的任意分区。
15
16NVS 库后续版本可能会增加其他存储器后端,实现将数据保存至其他 flash 芯片(SPI 或 I2C 接口)、RTC 或 FRAM 中。
17
18.. note:: 如果 NVS 分区被截断(例如,更改分区表布局时),则应擦除分区内容。可以使用 ESP-IDF 构建系统中的 ``idf.py erase_flash`` 命令擦除 flash 上的所有内容。
19
20.. note:: NVS 最适合存储一些较小的数据,而非字符串或二进制大对象 (BLOB) 等较大的数据。如需存储较大的 BLOB 或者字符串,请考虑使用基于磨损均衡库的 FAT 文件系统。
21
22
23键值对
24^^^^^^^^^^^^^^^
25
26NVS 的操作对象为键值对,其中键是 ASCII 字符串,当前支持最大键长为 15 个字符,值可以为以下几种类型:
27
28-  整数型:``uint8_t``、``int8_t``、``uint16_t``、``int16_t``、``uint32_t``、``int32_t``、``uint64_t`` 和 ``int64_t``;
29-  以 ``\0`` 结尾的字符串;
30-  可变长度的二进制数据 (BLOB)
31
32.. note::
33
34    字符串值当前上限为 4000 字节,其中包括空终止符。BLOB 值上限为 508,000 字节或分区大小减去 4000 字节的 97.6%,以较低值为准。
35
36后续可能会增加对 ``float`` 和 ``double`` 等其他类型数据的支持。
37
38键必须唯一。为现有的键写入新的值可能产生如下结果:
39
40-  如果新旧值数据类型相同,则更新值;
41-  如果新旧值数据类型不同,则返回错误。
42
43读取值时也会执行数据类型检查。如果读取操作的数据类型与该值的数据类型不匹配,则返回错误。
44
45
46命名空间
47^^^^^^^^^^
48
49为了减少不同组件之间键名的潜在冲突,NVS 将每个键值对分配给一个命名空间。命名空间的命名规则遵循键名的命名规则,即最多可占 15 个字符。命名空间的名称在调用 ``nvs_open`` 或 ``nvs_open_from_part`` 中指定,调用后将返回一个不透明句柄,用于后续调用 ``nvs_get_*``、``nvs_set_*`` 和 ``nvs_commit`` 函数。这样,一个句柄关联一个命名空间,键名便不会与其他命名空间中相同键名冲突。请注意,不同 NVS 分区中具有相同名称的命名空间将被视为不同的命名空间。
50
51
52安全性、篡改性及鲁棒性
53^^^^^^^^^^^^^^^^^^^^^^^^^^
54
55NVS 与 ESP32 flash 加密系统不直接兼容。但如果 NVS 加密与 ESP32 flash 加密一起使用时,数据仍可以加密形式存储。更多详情请参阅 :ref:`nvs_encryption`。
56
57如果未启用 NVS 加密,任何对 flash 芯片有物理访问权限的人都可以修改、擦除或添加键值对。NVS 加密启用后,如果不知道相应的 NVS 加密密钥,则无法修改或添加键值对并将其识别为有效键值。但是,针对擦除操作没有相应的防篡改功能。
58
59当 flash 处于不一致状态时,NVS 库会尝试恢复。在任何时间点关闭设备电源,然后重新打开电源,不会导致数据丢失;但如果关闭设备电源时正在写入新的键值对,这一键值对可能会丢失。该库还应当能对 flash 中的任意数据进行正确初始化。
60
61
62内部实现
63---------
64
65键值对日志
66^^^^^^^^^^^^^^^^^^^^^^
67
68NVS 按顺序存储键值对,新的键值对添加在最后。因此,如需更新某一键值对,实际是在日志最后增加一对新的键值对,同时将旧的键值对标记为已擦除。
69
70页面和条目
71^^^^^^^^^^^^^^^^^
72
73NVS 库在其操作中主要使用两个实体:页面和条目。页面是一个逻辑结构,用于存储部分的整体日志。逻辑页面对应 flash 的一个物理扇区,正在使用中的页面具有与之相关联的序列号。序列号赋予了页面顺序,较高的序列号对应较晚创建的页面。页面有以下几种状态:
74
75空或未初始化
76    页面对应的 flash 扇区为空白状态(所有字节均为 ``0xff``)。此时,页面未存储任何数据且没有关联的序列号。
77
78活跃状态
79    此时 flash 已完成初始化,页头部写入 flash,页面已具备有效序列号。页面中存在一些空条目,可写入数据。任意时刻,至多有一个页面处于活跃状态。
80
81写满状态
82    Flash 已写满键值对,状态不再改变。用户无法向写满状态下的页面写入新键值对,但仍可将一些键值对标记为已擦除。
83
84擦除状态
85    未擦除的键值对将移至其他页面,以便擦除当前页面。这一状态仅为暂时性状态,即 API 调用返回时,页面应脱离这一状态。如果设备突然断电,下次开机时,设备将继续把未擦除的键值对移至其他页面,并继续擦除当前页面。
86
87损坏状态
88    页头部包含无效数据,无法进一步解析该页面中的数据,因此之前写入该页面的所有条目均无法访问。相应的 flash 扇区并不会被立即擦除,而是与其他处于未初始化状态的扇区一起等待后续使用。这一状态可能对调试有用。
89
90Flash 扇区映射至逻辑页面并没有特定的顺序,NVS 库会检查存储在 flash 扇区的页面序列号,并根据序列号组织页面。
91
92::
93
94    +--------+     +--------+     +--------+     +--------+
95    | Page 1 |     | Page 2 |     | Page 3 |     | Page 4 |
96    | Full   +---> | Full   +---> | Active |     | Empty  |   <- 状态
97    | #11    |     | #12    |     | #14    |     |        |   <- 序列号
98    +---+----+     +----+---+     +----+---+     +---+----+
99        |               |              |             |
100        |               |              |             |
101        |               |              |             |
102    +---v------+  +-----v----+  +------v---+  +------v---+
103    | Sector 3 |  | Sector 0 |  | Sector 2 |  | Sector 1 |    <- 物理扇区
104    +----------+  +----------+  +----------+  +----------+
105
106页面结构
107^^^^^^^^^^^^^^^^^^^
108
109当前,我们假设 flash 扇区大小为 4096 字节,并且 ESP32 flash 加密硬件在 32 字节块上运行。未来有可能引入一些编译时可配置项(可通过 menuconfig 进行配置),以适配具有不同扇区大小的 flash 芯片。但目前尚不清楚 SPI flash 驱动和 SPI flash cache 之类的系统组件是否支持其他扇区大小。
110
111页面由头部、条目状态位图和条目三部分组成。为了实现与 ESP32 flash 加密功能兼容,条目大小设置为 32 字节。如果键值为整数型,条目则保存一个键值对;如果键值为字符串或 BLOB 类型,则条目仅保存一个键值对的部分内容(更多信息详见条目结构描述)。
112
113页面结构如下图所示,括号内数字表示该部分的大小(以字节为单位)::
114
115    +-----------+--------------+-------------+-------------------------+
116    | State (4) | Seq. no. (4) | version (1) | Unused (19) | CRC32 (4) |   页头部 (32)
117    +-----------+--------------+-------------+-------------------------+
118    |                Entry state bitmap (32)                           |
119    +------------------------------------------------------------------+
120    |                       Entry 0 (32)                               |
121    +------------------------------------------------------------------+
122    |                       Entry 1 (32)                               |
123    +------------------------------------------------------------------+
124    /                                                                  /
125    /                                                                  /
126    +------------------------------------------------------------------+
127    |                       Entry 125 (32)                             |
128    +------------------------------------------------------------------+
129
130头部和条目状态位图写入 flash 时不加密。如果启用了 ESP32 flash 加密功能,则条目写入 flash 时将会加密。
131
132通过将 0 写入某些位可以定义页面状态值,表示状态改变。因此,如果需要变更页面状态,并不一定要擦除页面,除非要将其变更为擦除状态。
133
134头部中的 ``version`` 字段反映了所用的 NVS 格式版本。为实现向后兼容,版本升级从 0xff 开始依次递减(例如,version-1 为 0xff,version-2 为 0xfe 等)。
135
136头部中 CRC32 值是由不包含状态值的条目计算所得(4 到 28 字节)。当前未使用的条目用 ``0xff`` 字节填充。
137
138条目结构和条目状态位图详细信息见下文描述。
139
140条目和条目状态位图
141^^^^^^^^^^^^^^^^^^^^^^^^^^^^
142
143每个条目可处于以下三种状态之一,每个状态在条目状态位图中用两位表示。位图中的最后四位 (256 - 2 * 126) 未使用。
144
145空 (2'b11)
146    条目还未写入任何内容,处于未初始化状态(全部字节为 ``0xff``)。
147
148写入(2'b10)
149    一个键值对(或跨多个条目的键值对的部分内容)已写入条目中。
150
151擦除(2'b00)
152    条目中的键值对已丢弃,条目内容不再解析。
153
154.. _structure_of_entry:
155
156条目结构
157^^^^^^^^^^^^^^^^^^
158
159如果键值类型为基础类型,即 1 - 8 个字节长度的整数型,条目将保存一个键值对;如果键值类型为字符串或 BLOB 类型,条目将保存整个键值对的部分内容。另外,如果键值为字符串类型且跨多个条目,则键值所跨的所有条目均保存在同一页面。BLOB 则可以切分为多个块,实现跨多个页面。BLOB 索引是一个附加的固定长度元数据条目,用于追踪 BLOB 块。目前条目仍支持早期 BLOB 格式(可读取可修改),但这些 BLOB 一经修改,即以新格式储存至条目。
160
161::
162
163    +--------+----------+----------+----------------+-----------+---------------+----------+
164    | NS (1) | Type (1) | Span (1) | ChunkIndex (1) | CRC32 (4) |    Key (16)   | Data (8) |
165    +--------+----------+----------+----------------+-----------+---------------+----------+
166
167                                             Primitive  +--------------------------------+
168                                            +-------->  |     Data (8)                   |
169                                            | Types     +--------------------------------+
170                       +-> Fixed length --
171                       |                    |           +---------+--------------+---------------+-------+
172                       |                    +-------->  | Size(4) | ChunkCount(1)| ChunkStart(1) | Rsv(2)|
173        Data format ---+                    BLOB Index  +---------+--------------+---------------+-------+
174                       |
175                       |                             +----------+---------+-----------+
176                       +->   Variable length   -->   | Size (2) | Rsv (2) | CRC32 (4) |
177                            (Strings, BLOB Data)     +----------+---------+-----------+
178
179
180条目结构中各个字段含义如下:
181
182命名空间 (NS, NameSpace)
183    该条目的命名空间索引,详细信息见命名空间实现章节。
184
185类型 (Type)
186    一个字节表示的值的数据类型,可能的类型见 ``nvs_types.h`` 中 ``ItemType`` 枚举。
187
188跨度 (Span)
189    该键值对所用的条目数量。如果键值为整数型,条目数量即为 1。如果键值为字符串或 BLOB,则条目数量取决于值的长度。
190
191块索引 (ChunkIndex)
192    用于存储 BLOB 类型数据块的索引。如果键值为其他数据类型,则此处索引应写入 ``0xff``。
193
194CRC32
195    对条目下所有字节进行校验,所得的校验和(CRC32 字段不计算在内)。
196
197键 (Key)
198    即以零结尾的 ASCII 字符串,字符串最长为 15 字节,不包含最后一个字节的 NULL (``\0``) 终止符。
199
200数据 (Data)
201    如果键值类型为整数型,则数据字段仅包含键值。如果键值小于八个字节,使用 ``0xff`` 填充未使用的部分(右侧)。
202
203    如果键值类型为 BLOB 索引条目,则该字段的八个字节将保存以下数据块信息:
204
205    - 块大小
206        整个 BLOB 数据的大小(以字节为单位)。该字段仅用于 BLOB 索引类型条目。
207
208    - ChunkCount
209        存储过程中 BLOB 分成的数据块数量。该字段仅用于 BLOB 索引类型条目。
210
211    - ChunkStart
212        BLOB 第一个数据块的块索引,后续数据块索引依次递增,步长为 1。该字段仅用于 BLOB 索引类型条目。
213
214    如果键值类型为字符串或 BLOB 数据块,数据字段的这八个字节将保存该键值的一些附加信息,如下所示:
215
216    - 数据大小
217        实际数据的大小(以字节为单位)。如果键值类型为字符串,此字段也应将零终止符包含在内。此字段仅用于字符串和 BLOB 类型条目。
218
219    - CRC32
220        数据所有字节的校验和,该字段仅用于字符串和 BLOB 类型条目。
221
222可变长度值(字符串和 BLOB)写入后续条目,每个条目 32 字节。第一个条目的 span 字段将指明使用了多少条目。
223
224命名空间
225^^^^^^^^^^
226
227如上所述,每个键值对属于一个命名空间。命名空间标识符(字符串)也作为键值对的键,存储在索引为 0 的命名空间中。与这些键对应的值就是这些命名空间的索引。
228
229::
230
231    +-------------------------------------------+
232    | NS=0 Type=uint8_t Key="wifi" Value=1      |   Entry describing namespace "wifi"
233    +-------------------------------------------+
234    | NS=1 Type=uint32_t Key="channel" Value=6  |   Key "channel" in namespace "wifi"
235    +-------------------------------------------+
236    | NS=0 Type=uint8_t Key="pwm" Value=2       |   Entry describing namespace "pwm"
237    +-------------------------------------------+
238    | NS=2 Type=uint16_t Key="channel" Value=20 |   Key "channel" in namespace "pwm"
239    +-------------------------------------------+
240
241
242条目哈希列表
243^^^^^^^^^^^^^^
244
245为了减少对 flash 执行的读操作次数,Page 类对象均设有一个列表,包含一对数据:条目索引和条目哈希值。该列表可大大提高检索速度,而无需迭代所有条目并逐个从 flash 中读取。``Page::findItem`` 首先从哈希列表中检索条目哈希值,如果条目存在,则在页面内给出条目索引。由于哈希冲突,在哈希列表中检索条目哈希值可能会得到不同的条目,对 flash 中条目再次迭代可解决这一冲突。
246
247哈希列表中每个节点均包含一个 24 位哈希值和 8 位条目索引。哈希值根据条目命名空间、键名和块索引由 CRC32 计算所得,计算结果保留 24 位。为减少将 32 位条目存储在链表中的开销,链表采用了数组的双向链表。每个数组占用 128 个字节,包含 29 个条目、两个链表指针和一个 32 位计数字段。因此,每页额外需要的 RAM 最少为 128 字节,最多为 640 字节。
248
249.. _nvs_encryption:
250
251NVS 加密
252--------------
253
254NVS 分区内存储的数据可使用 AES-XTS 进行加密,类似于 IEEE P1619 磁盘加密标准中提到的加密方式。为了实现加密,每个条目被均视为一个扇区,并将条目相对地址(相对于分区开头)传递给加密算法,用作扇区号。NVS 加密所需的密钥存储于其他分区,并进行了 :doc:`flash 加密 <../../security/flash-encryption>`。因此,在使用 NVS 加密前应先启用 :doc:`flash 加密 <../../security/flash-encryption>`。
255
256.. _nvs_key_partition:
257
258NVS 密钥分区
259^^^^^^^^^^^^^^^^^
260
261应用程序如果想使用 NVS 加密,则需要编译进一个类型为 ``data``,子类型为 ``key`` 的密钥分区。该分区应标记为已加密,且最小为 4096 字节,具体结构见下表。如需了解更多详细信息,请参考 :doc:`分区表 <../../api-guides/partition-tables>`。
262
263::
264
265    +-----------+--------------+-------------+----+
266    |              XTS encryption key(32)         |
267    +---------------------------------------------+
268    |              XTS tweak key (32)             |
269    +---------------------------------------------+
270    |                  CRC32(4)                   |
271    +---------------------------------------------+
272
273使用 NVS 分区生成程序生成上述分区表,并烧录至设备。由于分区已标记为已加密,而且启用了 :doc:`flash 加密 <../../security/flash-encryption>`,引导程序在首次启动时将使用 flash 加密对密钥分区进行加密。您也可以在设备启动后调用 ``nvs_flash.h`` 提供的 ``nvs_flash_generate_keys`` API 生成加密密钥,然后再将密钥以加密形式写入密钥分区。
274
275应用程序可以使用不同的密钥对不同的 NVS 分区进行加密,这样就会需要多个加密密钥分区。应用程序应为加解密操作提供正确的密钥或密钥分区。
276
277加密读取/写入
278^^^^^^^^^^^^^^^^^^^^
279
280``nvs_get_*`` 和 ``nvs_set_*`` 等 NVS API 函数同样可以对 NVS 加密分区执行读写操作。但用于初始化 NVS 非加密分区和加密分区的 API 则有所不同:初始化 NVS 非加密分区可以使用 ``nvs_flash_init`` 和 ``nvs_flash_init_partition``,但初始化 NVS 加密分区则需调用 ``nvs_flash_secure_init`` 和 ``nvs_flash_secure_init_partition``。上述 API 函数所需的 ``nvs_sec_cfg_t`` 结构可使用 ``nvs_flash_generate_keys`` 或者 ``nvs_flash_read_security_cfg`` 进行填充。
281
282应用程序如需在加密状态下执行 NVS 读写操作,应遵循以下步骤:
283
284    1. 使用 ``esp_partition_find*`` API 查找密钥分区和 NVS 数据分区;
285    2. 使用 ``nvs_flash_read_security_cfg`` 或 ``nvs_flash_generate_keys`` API 填充 ``nvs_sec_cfg_t`` 结构;
286    3. 使用 ``nvs_flash_secure_init`` 或 ``nvs_flash_secure_init_partition`` API 初始化 NVS flash 分区;
287    4. 使用 ``nvs_open`` 或 ``nvs_open_from_part`` API 打开命名空间;
288    5. 使用 ``nvs_get_*`` 或 ``nvs_set_*`` API 执行 NVS 读取/写入操作;
289    6. 使用 ``nvs_flash_deinit`` API 释放已初始化的 NVS 分区。
290
291NVS 迭代器
292^^^^^^^^^^^^^
293
294迭代器允许根据指定的分区名称、命名空间和数据类型轮询 NVS 中存储的键值对。
295
296您可以使用以下函数,执行相关操作:
297
298- ``nvs_entry_find``:返回一个不透明句柄,用于后续调用 ``nvs_entry_next`` 和 ``nvs_entry_info`` 函数;
299- ``nvs_entry_next``:返回指向下一个键值对的迭代器;
300- ``nvs_entry_info``:返回每个键值对的信息。
301
302如果未找到符合标准的键值对,``nvs_entry_find`` 和 ``nvs_entry_next`` 将返回 NULL,此时不必释放迭代器。若不再需要迭代器,可使用 ``nvs_release_iterator`` 释放迭代器。
303
304