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));
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));
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 std::fill_n(item.data, sizeof(item.data), 0xff);
227 item.blobIndex.dataSize = dataSize;
228 item.blobIndex.chunkCount = chunkCount;
229 item.blobIndex.chunkStart = chunkStart;
231 err = getCurrentPage().writeItem(nsIndex, ItemType::BLOB_IDX, key, item.data, sizeof(item.data));
232 assert(err != ESP_ERR_NVS_PAGE_FULL);
238 /* Anything failed, then we should erase all the written chunks*/
240 for (auto it = std::begin(usedPages); it != std::end(usedPages); it++) {
241 it->mPage->eraseItem(nsIndex, ItemType::BLOB_DATA, key, ii++);
244 usedPages.clearAndFreeNodes();
248 esp_err_t Storage::writeItem(uint8_t nsIndex, ItemType datatype, const char* key, const void* data, size_t dataSize)
250 if (mState != StorageState::ACTIVE) {
251 return ESP_ERR_NVS_NOT_INITIALIZED;
254 Page* findPage = nullptr;
258 if (datatype == ItemType::BLOB) {
259 err = findItem(nsIndex, ItemType::BLOB_IDX, key, findPage, item);
261 err = findItem(nsIndex, datatype, key, findPage, item);
264 if (err != ESP_OK && err != ESP_ERR_NVS_NOT_FOUND) {
268 if (datatype == ItemType::BLOB) {
269 VerOffset prevStart, nextStart;
270 prevStart = nextStart = VerOffset::VER_0_OFFSET;
272 // Do a sanity check that the item in question is actually being modified.
273 // If it isn't, it is cheaper to purposefully not write out new data.
274 // since it may invoke an erasure of flash.
275 if (cmpMultiPageBlob(nsIndex, key, data, dataSize) == ESP_OK) {
279 if (findPage->state() == Page::PageState::UNINITIALIZED ||
280 findPage->state() == Page::PageState::INVALID) {
281 ESP_ERROR_CHECK(findItem(nsIndex, datatype, key, findPage, item));
283 /* Get the version of the previous index with same <ns,key> */
284 prevStart = item.blobIndex.chunkStart;
285 assert(prevStart == VerOffset::VER_0_OFFSET || prevStart == VerOffset::VER_1_OFFSET);
287 /* Toggle the version by changing the offset */
289 = (prevStart == VerOffset::VER_1_OFFSET) ? VerOffset::VER_0_OFFSET : VerOffset::VER_1_OFFSET;
291 /* Write the blob with new version*/
292 err = writeMultiPageBlob(nsIndex, key, data, dataSize, nextStart);
294 if (err == ESP_ERR_NVS_PAGE_FULL) {
295 return ESP_ERR_NVS_NOT_ENOUGH_SPACE;
302 /* Erase the blob with earlier version*/
303 err = eraseMultiPageBlob(nsIndex, key, prevStart);
305 if (err == ESP_ERR_FLASH_OP_FAIL) {
306 return ESP_ERR_NVS_REMOVE_FAILED;
314 /* Support for earlier versions where BLOBS were stored without index */
315 err = findItem(nsIndex, datatype, key, findPage, item);
316 if (err != ESP_OK && err != ESP_ERR_NVS_NOT_FOUND) {
321 // Do a sanity check that the item in question is actually being modified.
322 // If it isn't, it is cheaper to purposefully not write out new data.
323 // since it may invoke an erasure of flash.
324 if (findPage != nullptr &&
325 findPage->cmpItem(nsIndex, datatype, key, data, dataSize) == ESP_OK) {
329 Page& page = getCurrentPage();
330 err = page.writeItem(nsIndex, datatype, key, data, dataSize);
331 if (err == ESP_ERR_NVS_PAGE_FULL) {
332 if (page.state() != Page::PageState::FULL) {
333 err = page.markFull();
338 err = mPageManager.requestNewPage();
343 err = getCurrentPage().writeItem(nsIndex, datatype, key, data, dataSize);
344 if (err == ESP_ERR_NVS_PAGE_FULL) {
345 return ESP_ERR_NVS_NOT_ENOUGH_SPACE;
350 } else if (err != ESP_OK) {
356 if (findPage->state() == Page::PageState::UNINITIALIZED ||
357 findPage->state() == Page::PageState::INVALID) {
358 ESP_ERROR_CHECK(findItem(nsIndex, datatype, key, findPage, item));
360 err = findPage->eraseItem(nsIndex, datatype, key);
361 if (err == ESP_ERR_FLASH_OP_FAIL) {
362 return ESP_ERR_NVS_REMOVE_FAILED;
374 esp_err_t Storage::createOrOpenNamespace(const char* nsName, bool canCreate, uint8_t& nsIndex)
376 if (mState != StorageState::ACTIVE) {
377 return ESP_ERR_NVS_NOT_INITIALIZED;
379 auto it = std::find_if(mNamespaces.begin(), mNamespaces.end(), [=] (const NamespaceEntry& e) -> bool {
380 return strncmp(nsName, e.mName, sizeof(e.mName) - 1) == 0;
382 if (it == std::end(mNamespaces)) {
384 return ESP_ERR_NVS_NOT_FOUND;
388 for (ns = 1; ns < 255; ++ns) {
389 if (mNamespaceUsage.get(ns) == false) {
395 return ESP_ERR_NVS_NOT_ENOUGH_SPACE;
398 auto err = writeItem(Page::NS_INDEX, ItemType::U8, nsName, &ns, sizeof(ns));
402 mNamespaceUsage.set(ns, true);
405 NamespaceEntry* entry = new NamespaceEntry;
407 strncpy(entry->mName, nsName, sizeof(entry->mName) - 1);
408 entry->mName[sizeof(entry->mName) - 1] = 0;
409 mNamespaces.push_back(entry);
412 nsIndex = it->mIndex;
417 esp_err_t Storage::readMultiPageBlob(uint8_t nsIndex, const char* key, void* data, size_t dataSize)
420 Page* findPage = nullptr;
422 /* First read the blob index */
423 auto err = findItem(nsIndex, ItemType::BLOB_IDX, key, findPage, item);
428 uint8_t chunkCount = item.blobIndex.chunkCount;
429 VerOffset chunkStart = item.blobIndex.chunkStart;
430 size_t readSize = item.blobIndex.dataSize;
433 assert(dataSize == readSize);
435 /* Now read corresponding chunks */
436 for (uint8_t chunkNum = 0; chunkNum < chunkCount; chunkNum++) {
437 err = findItem(nsIndex, ItemType::BLOB_DATA, key, findPage, item, static_cast<uint8_t> (chunkStart) + chunkNum);
439 if (err == ESP_ERR_NVS_NOT_FOUND) {
444 err = findPage->readItem(nsIndex, ItemType::BLOB_DATA, key, static_cast<uint8_t*>(data) + offset, item.varLength.dataSize, static_cast<uint8_t> (chunkStart) + chunkNum);
448 assert(static_cast<uint8_t> (chunkStart) + chunkNum == item.chunkIndex);
449 offset += item.varLength.dataSize;
452 assert(offset == dataSize);
454 if (err == ESP_ERR_NVS_NOT_FOUND) {
455 eraseMultiPageBlob(nsIndex, key); // cleanup if a chunk is not found
460 esp_err_t Storage::cmpMultiPageBlob(uint8_t nsIndex, const char* key, const void* data, size_t dataSize)
463 Page* findPage = nullptr;
465 /* First read the blob index */
466 auto err = findItem(nsIndex, ItemType::BLOB_IDX, key, findPage, item);
471 uint8_t chunkCount = item.blobIndex.chunkCount;
472 VerOffset chunkStart = item.blobIndex.chunkStart;
473 size_t readSize = item.blobIndex.dataSize;
476 if (dataSize != readSize) {
477 return ESP_ERR_NVS_CONTENT_DIFFERS;
480 /* Now read corresponding chunks */
481 for (uint8_t chunkNum = 0; chunkNum < chunkCount; chunkNum++) {
482 err = findItem(nsIndex, ItemType::BLOB_DATA, key, findPage, item, static_cast<uint8_t> (chunkStart) + chunkNum);
484 if (err == ESP_ERR_NVS_NOT_FOUND) {
489 err = findPage->cmpItem(nsIndex, ItemType::BLOB_DATA, key, static_cast<const uint8_t*>(data) + offset, item.varLength.dataSize, static_cast<uint8_t> (chunkStart) + chunkNum);
493 assert(static_cast<uint8_t> (chunkStart) + chunkNum == item.chunkIndex);
494 offset += item.varLength.dataSize;
497 assert(offset == dataSize);
502 esp_err_t Storage::readItem(uint8_t nsIndex, ItemType datatype, const char* key, void* data, size_t dataSize)
504 if (mState != StorageState::ACTIVE) {
505 return ESP_ERR_NVS_NOT_INITIALIZED;
509 Page* findPage = nullptr;
510 if (datatype == ItemType::BLOB) {
511 auto err = readMultiPageBlob(nsIndex, key, data, dataSize);
512 if (err != ESP_ERR_NVS_NOT_FOUND) {
514 } // else check if the blob is stored with earlier version format without index
517 auto err = findItem(nsIndex, datatype, key, findPage, item);
521 return findPage->readItem(nsIndex, datatype, key, data, dataSize);
525 esp_err_t Storage::eraseMultiPageBlob(uint8_t nsIndex, const char* key, VerOffset chunkStart)
527 if (mState != StorageState::ACTIVE) {
528 return ESP_ERR_NVS_NOT_INITIALIZED;
531 Page* findPage = nullptr;
533 auto err = findItem(nsIndex, ItemType::BLOB_IDX, key, findPage, item, Page::CHUNK_ANY, chunkStart);
537 /* Erase the index first and make children blobs orphan*/
538 err = findPage->eraseItem(nsIndex, ItemType::BLOB_IDX, key, Page::CHUNK_ANY, chunkStart);
543 uint8_t chunkCount = item.blobIndex.chunkCount;
545 if (chunkStart == VerOffset::VER_ANY) {
546 chunkStart = item.blobIndex.chunkStart;
548 assert(chunkStart == item.blobIndex.chunkStart);
551 /* Now erase corresponding chunks*/
552 for (uint8_t chunkNum = 0; chunkNum < chunkCount; chunkNum++) {
553 err = findItem(nsIndex, ItemType::BLOB_DATA, key, findPage, item, static_cast<uint8_t> (chunkStart) + chunkNum);
555 if (err != ESP_OK && err != ESP_ERR_NVS_NOT_FOUND) {
557 } else if (err == ESP_ERR_NVS_NOT_FOUND) {
558 continue; // Keep erasing other chunks
560 err = findPage->eraseItem(nsIndex, ItemType::BLOB_DATA, key, static_cast<uint8_t> (chunkStart) + chunkNum);
570 esp_err_t Storage::eraseItem(uint8_t nsIndex, ItemType datatype, const char* key)
572 if (mState != StorageState::ACTIVE) {
573 return ESP_ERR_NVS_NOT_INITIALIZED;
576 if (datatype == ItemType::BLOB) {
577 return eraseMultiPageBlob(nsIndex, key);
581 Page* findPage = nullptr;
582 auto err = findItem(nsIndex, datatype, key, findPage, item);
587 if (item.datatype == ItemType::BLOB_DATA || item.datatype == ItemType::BLOB_IDX) {
588 return eraseMultiPageBlob(nsIndex, key);
591 return findPage->eraseItem(nsIndex, datatype, key);
594 esp_err_t Storage::eraseNamespace(uint8_t nsIndex)
596 if (mState != StorageState::ACTIVE) {
597 return ESP_ERR_NVS_NOT_INITIALIZED;
600 for (auto it = std::begin(mPageManager); it != std::end(mPageManager); ++it) {
602 auto err = it->eraseItem(nsIndex, ItemType::ANY, nullptr);
603 if (err == ESP_ERR_NVS_NOT_FOUND) {
606 else if (err != ESP_OK) {
615 esp_err_t Storage::getItemDataSize(uint8_t nsIndex, ItemType datatype, const char* key, size_t& dataSize)
617 if (mState != StorageState::ACTIVE) {
618 return ESP_ERR_NVS_NOT_INITIALIZED;
622 Page* findPage = nullptr;
623 auto err = findItem(nsIndex, datatype, key, findPage, item);
625 if (datatype != ItemType::BLOB) {
628 err = findItem(nsIndex, ItemType::BLOB_IDX, key, findPage, item);
632 dataSize = item.blobIndex.dataSize;
636 dataSize = item.varLength.dataSize;
640 void Storage::debugDump()
642 for (auto p = mPageManager.begin(); p != mPageManager.end(); ++p) {
648 void Storage::debugCheck()
650 std::map<std::string, Page*> keys;
652 for (auto p = mPageManager.begin(); p != mPageManager.end(); ++p) {
653 size_t itemIndex = 0;
654 size_t usedCount = 0;
656 while (p->findItem(Page::NS_ANY, ItemType::ANY, nullptr, itemIndex, item) == ESP_OK) {
657 std::stringstream keyrepr;
658 keyrepr << static_cast<unsigned>(item.nsIndex) << "_" << static_cast<unsigned>(item.datatype) << "_" << item.key <<"_"<<static_cast<unsigned>(item.chunkIndex);
659 std::string keystr = keyrepr.str();
660 if (keys.find(keystr) != std::end(keys)) {
661 printf("Duplicate key: %s\n", keystr.c_str());
665 keys.insert(std::make_pair(keystr, static_cast<Page*>(p)));
666 itemIndex += item.span;
667 usedCount += item.span;
669 assert(usedCount == p->getUsedEntryCount());
672 #endif //ESP_PLATFORM
674 esp_err_t Storage::fillStats(nvs_stats_t& nvsStats)
676 nvsStats.namespace_count = mNamespaces.size();
677 return mPageManager.fillStats(nvsStats);
680 esp_err_t Storage::calcEntriesInNamespace(uint8_t nsIndex, size_t& usedEntries)
684 if (mState != StorageState::ACTIVE) {
685 return ESP_ERR_NVS_NOT_INITIALIZED;
688 for (auto it = std::begin(mPageManager); it != std::end(mPageManager); ++it) {
689 size_t itemIndex = 0;
692 auto err = it->findItem(nsIndex, ItemType::ANY, nullptr, itemIndex, item);
693 if (err == ESP_ERR_NVS_NOT_FOUND) {
696 else if (err != ESP_OK) {
699 usedEntries += item.span;
700 itemIndex += item.span;
701 if (itemIndex >= it->ENTRY_COUNT) break;
707 void Storage::fillEntryInfo(Item &item, nvs_entry_info_t &info)
709 info.type = static_cast<nvs_type_t>(item.datatype);
710 strncpy(info.key, item.key, sizeof(info.key));
712 for (auto &name : mNamespaces) {
713 if(item.nsIndex == name.mIndex) {
714 strncpy(info.namespace_name, name.mName, sizeof(info.namespace_name));
720 bool Storage::findEntry(nvs_opaque_iterator_t* it, const char* namespace_name)
723 it->nsIndex = Page::NS_ANY;
724 it->page = mPageManager.begin();
726 if (namespace_name != nullptr) {
727 if(createOrOpenNamespace(namespace_name, false, it->nsIndex) != ESP_OK) {
732 return nextEntry(it);
735 inline bool isIterableItem(Item& item)
737 return (item.nsIndex != 0 &&
738 item.datatype != ItemType::BLOB &&
739 item.datatype != ItemType::BLOB_IDX);
742 inline bool isMultipageBlob(Item& item)
744 return (item.datatype == ItemType::BLOB_DATA && item.chunkIndex != 0);
747 bool Storage::nextEntry(nvs_opaque_iterator_t* it)
752 for (auto page = it->page; page != mPageManager.end(); ++page) {
754 err = page->findItem(it->nsIndex, (ItemType)it->type, nullptr, it->entryIndex, item);
755 it->entryIndex += item.span;
756 if(err == ESP_OK && isIterableItem(item) && !isMultipageBlob(item)) {
757 fillEntryInfo(item, it->entry_info);
761 } while (err != ESP_ERR_NVS_NOT_FOUND);