1 // Copyright 2015-2016 Espressif Systems (Shanghai) PTE LTD
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
7 // http://www.apache.org/licenses/LICENSE-2.0
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14 #include "nvs_storage.hpp"
29 void Storage::clearNamespaces()
31 mNamespaces.clearAndFreeNodes();
34 void Storage::populateBlobIndices(TBlobIndexList& blobIdxList)
36 for (auto it = mPageManager.begin(); it != mPageManager.end(); ++it) {
41 /* If the power went off just after writing a blob index, the duplicate detection
42 * logic in pagemanager will remove the earlier index. So we should never find a
43 * duplicate index at this point */
45 while (p.findItem(Page::NS_ANY, ItemType::BLOB_IDX, nullptr, itemIndex, item) == ESP_OK) {
46 BlobIndexNode* entry = new BlobIndexNode;
48 item.getKey(entry->key, sizeof(entry->key) - 1);
49 entry->nsIndex = item.nsIndex;
50 entry->chunkStart = item.blobIndex.chunkStart;
51 entry->chunkCount = item.blobIndex.chunkCount;
53 blobIdxList.push_back(entry);
54 itemIndex += item.span;
59 void Storage::eraseOrphanDataBlobs(TBlobIndexList& blobIdxList)
61 for (auto it = mPageManager.begin(); it != mPageManager.end(); ++it) {
65 /* Chunks with same <ns,key> and with chunkIndex in the following ranges
66 * belong to same family.
67 * 1) VER_0_OFFSET <= chunkIndex < VER_1_OFFSET-1 => Version0 chunks
68 * 2) VER_1_OFFSET <= chunkIndex < VER_ANY => Version1 chunks
70 while (p.findItem(Page::NS_ANY, ItemType::BLOB_DATA, nullptr, itemIndex, item) == ESP_OK) {
72 auto iter = std::find_if(blobIdxList.begin(),
74 [=] (const BlobIndexNode& e) -> bool
75 {return (strncmp(item.key, e.key, sizeof(e.key) - 1) == 0)
76 && (item.nsIndex == e.nsIndex)
77 && (item.chunkIndex >= static_cast<uint8_t> (e.chunkStart))
78 && (item.chunkIndex < static_cast<uint8_t> (e.chunkStart) + e.chunkCount);});
79 if (iter == std::end(blobIdxList)) {
80 p.eraseItem(item.nsIndex, item.datatype, item.key, item.chunkIndex);
82 itemIndex += item.span;
87 esp_err_t Storage::init(uint32_t baseSector, uint32_t sectorCount)
89 auto err = mPageManager.load(baseSector, sectorCount);
91 mState = StorageState::INVALID;
95 // load namespaces list
97 std::fill_n(mNamespaceUsage.data(), mNamespaceUsage.byteSize() / 4, 0);
98 for (auto it = mPageManager.begin(); it != mPageManager.end(); ++it) {
100 size_t itemIndex = 0;
102 while (p.findItem(Page::NS_INDEX, ItemType::U8, nullptr, itemIndex, item) == ESP_OK) {
103 NamespaceEntry* entry = new NamespaceEntry;
104 item.getKey(entry->mName, sizeof(entry->mName) - 1);
105 item.getValue(entry->mIndex);
106 mNamespaces.push_back(entry);
107 mNamespaceUsage.set(entry->mIndex, true);
108 itemIndex += item.span;
111 mNamespaceUsage.set(0, true);
112 mNamespaceUsage.set(255, true);
113 mState = StorageState::ACTIVE;
115 // Populate list of multi-page index entries.
116 TBlobIndexList blobIdxList;
117 populateBlobIndices(blobIdxList);
119 // Remove the entries for which there is no parent multi-page index.
120 eraseOrphanDataBlobs(blobIdxList);
122 // Purge the blob index list
123 blobIdxList.clearAndFreeNodes();
131 bool Storage::isValid() const
133 return mState == StorageState::ACTIVE;
136 esp_err_t Storage::findItem(uint8_t nsIndex, ItemType datatype, const char* key, Page* &page, Item& item, uint8_t chunkIdx, VerOffset chunkStart)
138 for (auto it = std::begin(mPageManager); it != std::end(mPageManager); ++it) {
139 size_t itemIndex = 0;
140 auto err = it->findItem(nsIndex, datatype, key, itemIndex, item, chunkIdx, chunkStart);
146 return ESP_ERR_NVS_NOT_FOUND;
149 esp_err_t Storage::writeMultiPageBlob(uint8_t nsIndex, const char* key, const void* data, size_t dataSize, VerOffset chunkStart)
151 uint8_t chunkCount = 0;
152 TUsedPageList usedPages;
153 size_t remainingSize = dataSize;
155 esp_err_t err = ESP_OK;
157 /* Check how much maximum data can be accommodated**/
158 uint32_t max_pages = mPageManager.getPageCount() - 1;
160 if(max_pages > (Page::CHUNK_ANY-1)/2) {
161 max_pages = (Page::CHUNK_ANY-1)/2;
164 if (dataSize > max_pages * Page::CHUNK_MAX_SIZE) {
165 return ESP_ERR_NVS_VALUE_TOO_LONG;
169 Page& page = getCurrentPage();
170 size_t tailroom = page.getVarDataTailroom();
172 if (!chunkCount && tailroom < dataSize && tailroom < Page::CHUNK_MAX_SIZE/10) {
173 /** This is the first chunk and tailroom is too small ***/
174 if (page.state() != Page::PageState::FULL) {
175 err = page.markFull();
180 err = mPageManager.requestNewPage();
183 } else if(getCurrentPage().getVarDataTailroom() == tailroom) {
184 /* We got the same page or we are not improving.*/
185 return ESP_ERR_NVS_NOT_ENOUGH_SPACE;
189 } else if (!tailroom) {
190 err = ESP_ERR_NVS_NOT_ENOUGH_SPACE;
194 /* Split the blob into two and store the chunk of available size onto the current page */
196 chunkSize = (remainingSize > tailroom)? tailroom : remainingSize;
197 remainingSize -= chunkSize;
199 err = page.writeItem(nsIndex, ItemType::BLOB_DATA, key,
200 static_cast<const uint8_t*> (data) + offset, chunkSize, static_cast<uint8_t> (chunkStart) + chunkCount);
202 assert(err != ESP_ERR_NVS_PAGE_FULL);
206 UsedPageNode* node = new UsedPageNode();
208 usedPages.push_back(node);
209 if (remainingSize || (tailroom - chunkSize) < Page::ENTRY_SIZE) {
210 if (page.state() != Page::PageState::FULL) {
211 err = page.markFull();
216 err = mPageManager.requestNewPage();
223 if (!remainingSize) {
224 /* All pages are stored. Now store the index.*/
226 item.blobIndex.dataSize = dataSize;
227 item.blobIndex.chunkCount = chunkCount;
228 item.blobIndex.chunkStart = chunkStart;
230 err = getCurrentPage().writeItem(nsIndex, ItemType::BLOB_IDX, key, item.data, sizeof(item.data));
231 assert(err != ESP_ERR_NVS_PAGE_FULL);
237 /* Anything failed, then we should erase all the written chunks*/
239 for (auto it = std::begin(usedPages); it != std::end(usedPages); it++) {
240 it->mPage->eraseItem(nsIndex, ItemType::BLOB_DATA, key, ii++);
243 usedPages.clearAndFreeNodes();
247 esp_err_t Storage::writeItem(uint8_t nsIndex, ItemType datatype, const char* key, const void* data, size_t dataSize)
249 if (mState != StorageState::ACTIVE) {
250 return ESP_ERR_NVS_NOT_INITIALIZED;
253 Page* findPage = nullptr;
257 if (datatype == ItemType::BLOB) {
258 err = findItem(nsIndex, ItemType::BLOB_IDX, key, findPage, item);
260 err = findItem(nsIndex, datatype, key, findPage, item);
263 if (err != ESP_OK && err != ESP_ERR_NVS_NOT_FOUND) {
267 if (datatype == ItemType::BLOB) {
268 VerOffset prevStart, nextStart;
269 prevStart = nextStart = VerOffset::VER_0_OFFSET;
271 if (findPage->state() == Page::PageState::UNINITIALIZED ||
272 findPage->state() == Page::PageState::INVALID) {
273 ESP_ERROR_CHECK(findItem(nsIndex, datatype, key, findPage, item));
275 /* Get the version of the previous index with same <ns,key> */
276 prevStart = item.blobIndex.chunkStart;
277 assert(prevStart == VerOffset::VER_0_OFFSET || prevStart == VerOffset::VER_1_OFFSET);
279 /* Toggle the version by changing the offset */
281 = (prevStart == VerOffset::VER_1_OFFSET) ? VerOffset::VER_0_OFFSET : VerOffset::VER_1_OFFSET;
283 /* Write the blob with new version*/
284 err = writeMultiPageBlob(nsIndex, key, data, dataSize, nextStart);
286 if (err == ESP_ERR_NVS_PAGE_FULL) {
287 return ESP_ERR_NVS_NOT_ENOUGH_SPACE;
294 /* Erase the blob with earlier version*/
295 err = eraseMultiPageBlob(nsIndex, key, prevStart);
297 if (err == ESP_ERR_FLASH_OP_FAIL) {
298 return ESP_ERR_NVS_REMOVE_FAILED;
306 /* Support for earlier versions where BLOBS were stored without index */
307 err = findItem(nsIndex, datatype, key, findPage, item);
308 if (err != ESP_OK && err != ESP_ERR_NVS_NOT_FOUND) {
314 Page& page = getCurrentPage();
315 err = page.writeItem(nsIndex, datatype, key, data, dataSize);
316 if (err == ESP_ERR_NVS_PAGE_FULL) {
317 if (page.state() != Page::PageState::FULL) {
318 err = page.markFull();
323 err = mPageManager.requestNewPage();
328 err = getCurrentPage().writeItem(nsIndex, datatype, key, data, dataSize);
329 if (err == ESP_ERR_NVS_PAGE_FULL) {
330 return ESP_ERR_NVS_NOT_ENOUGH_SPACE;
335 } else if (err != ESP_OK) {
341 if (findPage->state() == Page::PageState::UNINITIALIZED ||
342 findPage->state() == Page::PageState::INVALID) {
343 ESP_ERROR_CHECK(findItem(nsIndex, datatype, key, findPage, item));
345 err = findPage->eraseItem(nsIndex, datatype, key);
346 if (err == ESP_ERR_FLASH_OP_FAIL) {
347 return ESP_ERR_NVS_REMOVE_FAILED;
359 esp_err_t Storage::createOrOpenNamespace(const char* nsName, bool canCreate, uint8_t& nsIndex)
361 if (mState != StorageState::ACTIVE) {
362 return ESP_ERR_NVS_NOT_INITIALIZED;
364 auto it = std::find_if(mNamespaces.begin(), mNamespaces.end(), [=] (const NamespaceEntry& e) -> bool {
365 return strncmp(nsName, e.mName, sizeof(e.mName) - 1) == 0;
367 if (it == std::end(mNamespaces)) {
369 return ESP_ERR_NVS_NOT_FOUND;
373 for (ns = 1; ns < 255; ++ns) {
374 if (mNamespaceUsage.get(ns) == false) {
380 return ESP_ERR_NVS_NOT_ENOUGH_SPACE;
383 auto err = writeItem(Page::NS_INDEX, ItemType::U8, nsName, &ns, sizeof(ns));
387 mNamespaceUsage.set(ns, true);
390 NamespaceEntry* entry = new NamespaceEntry;
392 strncpy(entry->mName, nsName, sizeof(entry->mName) - 1);
393 entry->mName[sizeof(entry->mName) - 1] = 0;
394 mNamespaces.push_back(entry);
397 nsIndex = it->mIndex;
402 esp_err_t Storage::readMultiPageBlob(uint8_t nsIndex, const char* key, void* data, size_t dataSize)
405 Page* findPage = nullptr;
407 /* First read the blob index */
408 auto err = findItem(nsIndex, ItemType::BLOB_IDX, key, findPage, item);
413 uint8_t chunkCount = item.blobIndex.chunkCount;
414 VerOffset chunkStart = item.blobIndex.chunkStart;
415 size_t readSize = item.blobIndex.dataSize;
418 assert(dataSize == readSize);
420 /* Now read corresponding chunks */
421 for (uint8_t chunkNum = 0; chunkNum < chunkCount; chunkNum++) {
422 err = findItem(nsIndex, ItemType::BLOB_DATA, key, findPage, item, static_cast<uint8_t> (chunkStart) + chunkNum);
424 if (err == ESP_ERR_NVS_NOT_FOUND) {
429 err = findPage->readItem(nsIndex, ItemType::BLOB_DATA, key, static_cast<uint8_t*>(data) + offset, item.varLength.dataSize, static_cast<uint8_t> (chunkStart) + chunkNum);
433 assert(static_cast<uint8_t> (chunkStart) + chunkNum == item.chunkIndex);
434 offset += item.varLength.dataSize;
437 assert(offset == dataSize);
439 if (err == ESP_ERR_NVS_NOT_FOUND) {
440 eraseMultiPageBlob(nsIndex, key); // cleanup if a chunk is not found
445 esp_err_t Storage::readItem(uint8_t nsIndex, ItemType datatype, const char* key, void* data, size_t dataSize)
447 if (mState != StorageState::ACTIVE) {
448 return ESP_ERR_NVS_NOT_INITIALIZED;
452 Page* findPage = nullptr;
453 if (datatype == ItemType::BLOB) {
454 auto err = readMultiPageBlob(nsIndex, key, data, dataSize);
455 if (err != ESP_ERR_NVS_NOT_FOUND) {
457 } // else check if the blob is stored with earlier version format without index
460 auto err = findItem(nsIndex, datatype, key, findPage, item);
464 return findPage->readItem(nsIndex, datatype, key, data, dataSize);
468 esp_err_t Storage::eraseMultiPageBlob(uint8_t nsIndex, const char* key, VerOffset chunkStart)
470 if (mState != StorageState::ACTIVE) {
471 return ESP_ERR_NVS_NOT_INITIALIZED;
474 Page* findPage = nullptr;
476 auto err = findItem(nsIndex, ItemType::BLOB_IDX, key, findPage, item, Page::CHUNK_ANY, chunkStart);
480 /* Erase the index first and make children blobs orphan*/
481 err = findPage->eraseItem(nsIndex, ItemType::BLOB_IDX, key, Page::CHUNK_ANY, chunkStart);
486 uint8_t chunkCount = item.blobIndex.chunkCount;
488 if (chunkStart == VerOffset::VER_ANY) {
489 chunkStart = item.blobIndex.chunkStart;
491 assert(chunkStart == item.blobIndex.chunkStart);
494 /* Now erase corresponding chunks*/
495 for (uint8_t chunkNum = 0; chunkNum < chunkCount; chunkNum++) {
496 err = findItem(nsIndex, ItemType::BLOB_DATA, key, findPage, item, static_cast<uint8_t> (chunkStart) + chunkNum);
498 if (err != ESP_OK && err != ESP_ERR_NVS_NOT_FOUND) {
500 } else if (err == ESP_ERR_NVS_NOT_FOUND) {
501 continue; // Keep erasing other chunks
503 err = findPage->eraseItem(nsIndex, ItemType::BLOB_DATA, key, static_cast<uint8_t> (chunkStart) + chunkNum);
513 esp_err_t Storage::eraseItem(uint8_t nsIndex, ItemType datatype, const char* key)
515 if (mState != StorageState::ACTIVE) {
516 return ESP_ERR_NVS_NOT_INITIALIZED;
519 if (datatype == ItemType::BLOB) {
520 return eraseMultiPageBlob(nsIndex, key);
524 Page* findPage = nullptr;
525 auto err = findItem(nsIndex, datatype, key, findPage, item);
530 return findPage->eraseItem(nsIndex, datatype, key);
533 esp_err_t Storage::eraseNamespace(uint8_t nsIndex)
535 if (mState != StorageState::ACTIVE) {
536 return ESP_ERR_NVS_NOT_INITIALIZED;
539 for (auto it = std::begin(mPageManager); it != std::end(mPageManager); ++it) {
541 auto err = it->eraseItem(nsIndex, ItemType::ANY, nullptr);
542 if (err == ESP_ERR_NVS_NOT_FOUND) {
545 else if (err != ESP_OK) {
554 esp_err_t Storage::getItemDataSize(uint8_t nsIndex, ItemType datatype, const char* key, size_t& dataSize)
556 if (mState != StorageState::ACTIVE) {
557 return ESP_ERR_NVS_NOT_INITIALIZED;
561 Page* findPage = nullptr;
562 auto err = findItem(nsIndex, datatype, key, findPage, item);
564 if (datatype != ItemType::BLOB) {
567 err = findItem(nsIndex, ItemType::BLOB_IDX, key, findPage, item);
571 dataSize = item.blobIndex.dataSize;
575 dataSize = item.varLength.dataSize;
579 void Storage::debugDump()
581 for (auto p = mPageManager.begin(); p != mPageManager.end(); ++p) {
587 void Storage::debugCheck()
589 std::map<std::string, Page*> keys;
591 for (auto p = mPageManager.begin(); p != mPageManager.end(); ++p) {
592 size_t itemIndex = 0;
593 size_t usedCount = 0;
595 while (p->findItem(Page::NS_ANY, ItemType::ANY, nullptr, itemIndex, item) == ESP_OK) {
596 std::stringstream keyrepr;
597 keyrepr << static_cast<unsigned>(item.nsIndex) << "_" << static_cast<unsigned>(item.datatype) << "_" << item.key <<"_"<<static_cast<unsigned>(item.chunkIndex);
598 std::string keystr = keyrepr.str();
599 if (keys.find(keystr) != std::end(keys)) {
600 printf("Duplicate key: %s\n", keystr.c_str());
604 keys.insert(std::make_pair(keystr, static_cast<Page*>(p)));
605 itemIndex += item.span;
606 usedCount += item.span;
608 assert(usedCount == p->getUsedEntryCount());
611 #endif //ESP_PLATFORM
613 esp_err_t Storage::fillStats(nvs_stats_t& nvsStats)
615 nvsStats.namespace_count = mNamespaces.size();
616 return mPageManager.fillStats(nvsStats);
619 esp_err_t Storage::calcEntriesInNamespace(uint8_t nsIndex, size_t& usedEntries)
623 if (mState != StorageState::ACTIVE) {
624 return ESP_ERR_NVS_NOT_INITIALIZED;
627 for (auto it = std::begin(mPageManager); it != std::end(mPageManager); ++it) {
628 size_t itemIndex = 0;
631 auto err = it->findItem(nsIndex, ItemType::ANY, nullptr, itemIndex, item);
632 if (err == ESP_ERR_NVS_NOT_FOUND) {
635 else if (err != ESP_OK) {
638 usedEntries += item.span;
639 itemIndex += item.span;
640 if (itemIndex >= it->ENTRY_COUNT) break;