]> granicus.if.org Git - esp-idf/blob - components/nvs_flash/README.rst
heap: test: don’t warn about oversized mallocs
[esp-idf] / components / nvs_flash / README.rst
1 Non-volatile storage library
2 ============================
3
4 Introduction
5 ------------
6
7 Non-volatile storage (NVS) library is designed to store key-value pairs in flash. This sections introduces some concepts used by NVS.
8
9 Underlying storage
10 ^^^^^^^^^^^^^^^^^^
11
12 Currently NVS uses a portion of main flash memory through ``spi_flash_{read|write|erase}`` APIs. The library uses the all the partitions with ``data`` type and ``nvs`` subtype. The application can choose to use the partition with label ``nvs`` through ``nvs_open`` API or any of the other partition by specifying its name through ``nvs_open_from_part`` API.
13
14 Future versions of this library may add other storage backends to keep data in another flash chip (SPI or I2C), RTC, FRAM, etc.
15
16 .. 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 ``make erase_flash`` target to erase all contents of the flash chip.
17
18 .. note:: NVS works best for storing many small values, rather than a few large values of type 'string' and 'blob'. If storing large blobs or strings is required, consider using the facilities provided by the FAT filesystem on top of the wear levelling library.
19
20 Keys and values
21 ^^^^^^^^^^^^^^^
22
23 NVS operates on key-value pairs. Keys are ASCII strings, maximum key length is currently 15 characters. Values can have one of the following types:
24
25 -  integer types: ``uint8_t``, ``int8_t``, ``uint16_t``, ``int16_t``, ``uint32_t``, ``int32_t``, ``uint64_t``, ``int64_t``
26 -  zero-terminated string
27 -  variable length binary data (blob)
28
29 .. note::
30    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.
31
32 Additional types, such as ``float`` and ``double`` may be added later.
33
34 Keys are required to be unique. Writing a value for a key which already exists behaves as follows:
35
36 -  if the new value is of the same type as old one, value is updated
37 -  if the new value has different data type, an error is returned
38
39 Data type check is also performed when reading a value. An error is returned if data type of read operation doesn’t match the data type of the value.
40
41 Namespaces
42 ^^^^^^^^^^
43
44 To 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. 15 character maximum length. 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 ``nvs_read_*``, ``nvs_write_*``, and ``nvs_commit`` functions. This way, handle is associated with a namespace, and key names will not collide with same names in other namespaces.
45 Please note that the namespaces with same name in different NVS partitions are considered as separate namespaces.
46
47 Security, tampering, and robustness
48 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
49
50 NVS library doesn't implement tamper prevention measures. It is possible for anyone with physical access to the flash chip to alter, erase, or add key-value pairs.
51
52 NVS is not currently compatible with the ESP32 flash encryption system.
53
54 The 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, expect for the new key-value pair if it was being written at the moment of power off. The library should also be able to initialize properly with any random data present in flash memory.
55
56 Internals
57 ---------
58
59 Log of key-value pairs
60 ^^^^^^^^^^^^^^^^^^^^^^
61
62 NVS 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, new key-value pair is added at the end of the log and old key-value pair is marked as erased.
63
64 Pages and entries
65 ^^^^^^^^^^^^^^^^^
66
67 NVS 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:
68
69 Empty/uninitialized
70     Flash storage for the page is empty (all bytes are ``0xff``). Page isn't used to store any data at this point and doesn’t have a sequence number.
71
72 Active
73     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. At most one page can be in this state at any given moment.
74
75 Full
76     Flash storage is in a consistent state and is filled with key-value pairs.
77     Writing new key-value pairs into this page is not possible. It is still possible to mark some key-value pairs as erased.
78
79 Erasing
80     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 when any API call returns. In case of a sudden power off, move-and-erase process will be completed upon next power on.
81
82 Corrupted
83     Page header contains invalid data, and further parsing of page data was canceled. Any items previously written into this page will not be accessible. 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.
84
85 Mapping from flash sectors to logical pages doesn't have any particular order. Library will inspect sequence numbers of pages found in each flash sector and organize pages in a list based on these numbers.
86
87 ::
88
89     +--------+     +--------+     +--------+     +--------+
90     | Page 1 |     | Page 2 |     | Page 3 |     | Page 4 |
91     | Full   +---> | Full   +---> | Active |     | Empty  |   <- states
92     | #11    |     | #12    |     | #14    |     |        |   <- sequence numbers
93     +---+----+     +----+---+     +----+---+     +---+----+
94         |               |              |             |
95         |               |              |             |
96         |               |              |             |
97     +---v------+  +-----v----+  +------v---+  +------v---+
98     | Sector 3 |  | Sector 0 |  | Sector 2 |  | Sector 1 |    <- physical sectors
99     +----------+  +----------+  +----------+  +----------+
100
101 Structure of a page
102 ^^^^^^^^^^^^^^^^^^^
103
104 For 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).
105
106 Page 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).
107
108 The following diagram illustrates page structure. Numbers in parentheses indicate size of each part in bytes. ::
109
110     +-----------+--------------+-------------+-----------+
111     | State (4) | Seq. no. (4) | Unused (20) | CRC32 (4) | Header (32)
112     +-----------+--------------+-------------+-----------+
113     |                Entry state bitmap (32)             |
114     +----------------------------------------------------+
115     |                       Entry 0 (32)                 |
116     +----------------------------------------------------+
117     |                       Entry 1 (32)                 |
118     +----------------------------------------------------+
119     /                                                    /
120     /                                                    /
121     +----------------------------------------------------+
122     |                       Entry 125 (32)               |
123     +----------------------------------------------------+
124
125 Page header and entry state bitmap are always written to flash unencrypted. Entries are encrypted if flash encryption feature of the ESP32 is used.
126
127 Page state values are defined in such a way that changing state is possible by writing 0 into some of the bits. Therefore it not necessary to erase the page to change page state, unless that is a change to *erased* state.
128
129 CRC32 value in header is calculated over the part which doesn't include state value (bytes 4 to 28). Unused part is currently filled with ``0xff`` bytes. Future versions of the library may store format version there.
130
131 The following sections describe structure of entry state bitmap and entry itself.
132
133 Entry and entry state bitmap
134 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
135
136 Each entry can be in one of the following three states. Each state is represented with two bits in the entry state bitmap. Final four bits in the bitmap (256 - 2 * 126) are unused.
137
138 Empty (2'b11)
139     Nothing is written into the specific entry yet. It is in an uninitialized state (all bytes ``0xff``). 
140
141 Written (2'b10)
142     A key-value pair (or part of key-value pair which spans multiple entries) has been written into the entry.
143
144 Erased (2'b00)
145     A key-value pair in this entry has been discarded. Contents of this entry will not be parsed anymore.
146
147
148 Structure of entry
149 ^^^^^^^^^^^^^^^^^^
150
151 For 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 the purpose tracking these chunks, an additional fixed length metadata entry is stored called "blob index" entry. Earlier format of blobs are still supported (can be read and modified). However, once the blobs are modified, they are stored using the new format.
152
153 ::
154
155     +--------+----------+----------+----------------+-----------+---------------+----------+
156     | NS (1) | Type (1) | Span (1) | ChunkIndex (1) | CRC32 (4) |    Key (16)   | Data (8) |
157     +--------+----------+----------+----------------+-----------+---------------+----------+
158
159                                              Primitive  +--------------------------------+                        
160                                             +-------->  |     Data (8)                   |                        
161                                             | Types     +--------------------------------+
162                        +-> Fixed length --                                                                 
163                        |                    |           +---------+--------------+---------------+-------+
164                        |                    +-------->  | Size(4) | ChunkCount(1)| ChunkStart(1) | Rsv(2)|
165         Data format ---+                    Blob Index  +---------+--------------+---------------+-------+
166                        |
167                        |                             +----------+---------+-----------+ 
168                        +->   Variable length   -->   | Size (2) | Rsv (2) | CRC32 (4) |
169                             (Strings, Blob Data)     +----------+---------+-----------+
170
171
172 Individual fields in entry structure have the following meanings:
173
174 NS
175     Namespace index for this entry. See section on namespaces implementation for explanation of this value.
176
177 Type
178     One byte indicating data type of value. See ``ItemType`` enumeration in ``nvs_types.h`` for possible values.
179
180 Span
181     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.
182
183 ChunkIndex
184     Used to store index of the blob-data chunk for blob types. For other types, this should be ``0xff``.
185
186 CRC32
187     Checksum calculated over all the bytes in this entry, except for the CRC32 field itself.
188
189 Key
190     Zero-terminated ASCII string containing key name. Maximum string length is 15 bytes, excluding zero terminator.
191
192 Data
193     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``. 
194
195     For "blob index" entry, these 8 bytes hold the following information about data-chunks:
196
197     - Size
198         (Only for blob index.) Size, in bytes, of complete blob data.
199
200     - ChunkCount 
201         (Only for blob index.) Total number of blob-data chunks into which the blob was divided during storage. 
202      
203     - ChunkStart 
204         (Only for blob index.) ChunkIndex of the first blob-data chunk of this blob. Subsequent chunks have chunkIndex incrementely allocated (step of 1). 
205
206     For string and blob data chunks, these 8 bytes hold additional data about the value, described next:
207   
208     - Size
209         (Only for strings and blobs.) Size, in bytes, of actual data. For strings, this includes zero terminator.
210
211     - CRC32
212         (Only for strings and blobs.) Checksum calculated over all bytes of data.
213
214 Variable length values (strings and blobs) are written into subsequent entries, 32 bytes per entry. `Span` field of the first entry indicates how many entries are used.
215
216
217 Namespaces
218 ^^^^^^^^^^
219
220 As mentioned above, each key-value pair belongs to one of the namespaces. Namespaces 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. 
221
222 ::
223
224     +-------------------------------------------+
225     | NS=0 Type=uint8_t Key="wifi" Value=1      |   Entry describing namespace "wifi"
226     +-------------------------------------------+
227     | NS=1 Type=uint32_t Key="channel" Value=6  |   Key "channel" in namespace "wifi"
228     +-------------------------------------------+
229     | NS=0 Type=uint8_t Key="pwm" Value=2       |   Entry describing namespace "pwm"
230     +-------------------------------------------+
231     | NS=2 Type=uint16_t Key="channel" Value=20 |   Key "channel" in namespace "pwm"
232     +-------------------------------------------+
233
234
235 Item hash list
236 ^^^^^^^^^^^^^^
237
238 To reduce the number of reads performed from flash memory, each member of 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 search for 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.
239
240 Each node in 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, result is truncated to 24 bits. To reduce overhead of storing 32-bit entries in a linked list, list is implemented as a doubly-linked list of arrays. Each array holds 29 entries, for the total size of 128 bytes, together with linked list pointers and 32-bit count field. Minimal amount of extra RAM useage per page is therefore 128 bytes, maximum is 640 bytes.
241