1 // Copyright 2020 The Pigweed Authors
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License"); you may not
4 // use this file except in compliance with the License. You may obtain a copy of
5 // the License at
6 //
7 //     https://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
11 // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12 // License for the specific language governing permissions and limitations under
13 // the License.
14 
15 #define PW_LOG_MODULE_NAME "KVS"
16 #define PW_LOG_LEVEL PW_KVS_LOG_LEVEL
17 
18 #include "pw_kvs/key_value_store.h"
19 
20 #include <algorithm>
21 #include <cinttypes>
22 #include <cstring>
23 #include <type_traits>
24 
25 #include "pw_assert/assert.h"
26 #include "pw_kvs_private/config.h"
27 #include "pw_log/shorter.h"
28 #include "pw_status/try.h"
29 
30 namespace pw::kvs {
31 namespace {
32 
33 using std::byte;
34 
InvalidKey(Key key)35 constexpr bool InvalidKey(Key key) {
36   return key.empty() || (key.size() > internal::Entry::kMaxKeyLength);
37 }
38 
39 }  // namespace
40 
KeyValueStore(FlashPartition * partition,std::span<const EntryFormat> formats,const Options & options,size_t redundancy,Vector<SectorDescriptor> & sector_descriptor_list,const SectorDescriptor ** temp_sectors_to_skip,Vector<KeyDescriptor> & key_descriptor_list,Address * addresses)41 KeyValueStore::KeyValueStore(FlashPartition* partition,
42                              std::span<const EntryFormat> formats,
43                              const Options& options,
44                              size_t redundancy,
45                              Vector<SectorDescriptor>& sector_descriptor_list,
46                              const SectorDescriptor** temp_sectors_to_skip,
47                              Vector<KeyDescriptor>& key_descriptor_list,
48                              Address* addresses)
49     : partition_(*partition),
50       formats_(formats),
51       sectors_(sector_descriptor_list, *partition, temp_sectors_to_skip),
52       entry_cache_(key_descriptor_list, addresses, redundancy),
53       options_(options),
54       initialized_(InitializationState::kNotInitialized),
55       error_detected_(false),
56       internal_stats_({}),
57       last_transaction_id_(0) {}
58 
Init()59 Status KeyValueStore::Init() {
60   initialized_ = InitializationState::kNotInitialized;
61   error_detected_ = false;
62   last_transaction_id_ = 0;
63 
64   INF("Initializing key value store");
65   if (partition_.sector_count() > sectors_.max_size()) {
66     ERR("KVS init failed: kMaxUsableSectors (=%u) must be at least as "
67         "large as the number of sectors in the flash partition (=%u)",
68         unsigned(sectors_.max_size()),
69         unsigned(partition_.sector_count()));
70     return Status::FailedPrecondition();
71   }
72 
73   if (partition_.sector_count() < 2) {
74     ERR("KVS init failed: FlashParition sector count (=%u) must be at 2. KVS "
75         "requires at least 1 working sector + 1 free/reserved sector",
76         unsigned(partition_.sector_count()));
77     return Status::FailedPrecondition();
78   }
79 
80   const size_t sector_size_bytes = partition_.sector_size_bytes();
81 
82   // TODO: investigate doing this as a static assert/compile-time check.
83   if (sector_size_bytes > SectorDescriptor::max_sector_size()) {
84     ERR("KVS init failed: sector_size_bytes (=%u) is greater than maximum "
85         "allowed sector size (=%u)",
86         unsigned(sector_size_bytes),
87         unsigned(SectorDescriptor::max_sector_size()));
88     return Status::FailedPrecondition();
89   }
90 
91   Status metadata_result = InitializeMetadata();
92 
93   if (!error_detected_) {
94     initialized_ = InitializationState::kReady;
95   } else {
96     initialized_ = InitializationState::kNeedsMaintenance;
97 
98     if (options_.recovery != ErrorRecovery::kManual) {
99       size_t pre_fix_redundancy_errors =
100           internal_stats_.missing_redundant_entries_recovered;
101       Status recovery_status = FixErrors();
102 
103       if (recovery_status.ok()) {
104         if (metadata_result.IsOutOfRange()) {
105           internal_stats_.missing_redundant_entries_recovered =
106               pre_fix_redundancy_errors;
107           INF("KVS init: Redundancy level successfully updated");
108         } else {
109           WRN("KVS init: Corruption detected and fully repaired");
110         }
111         initialized_ = InitializationState::kReady;
112       } else if (recovery_status.IsResourceExhausted()) {
113         WRN("KVS init: Unable to maintain required free sector");
114       } else {
115         WRN("KVS init: Corruption detected and unable repair");
116       }
117     } else {
118       WRN("KVS init: Corruption detected, no repair attempted due to options");
119     }
120   }
121 
122   INF("KeyValueStore init complete: active keys %u, deleted keys %u, sectors "
123       "%u, logical sector size %u bytes",
124       unsigned(size()),
125       unsigned(entry_cache_.total_entries() - size()),
126       unsigned(sectors_.size()),
127       unsigned(partition_.sector_size_bytes()));
128 
129   // Report any corruption was not repaired.
130   if (error_detected_) {
131     WRN("KVS init: Corruption found but not repaired, KVS unavailable until "
132         "successful maintenance.");
133     return Status::DataLoss();
134   }
135 
136   return OkStatus();
137 }
138 
InitializeMetadata()139 Status KeyValueStore::InitializeMetadata() {
140   const size_t sector_size_bytes = partition_.sector_size_bytes();
141 
142   sectors_.Reset();
143   entry_cache_.Reset();
144 
145   DBG("First pass: Read all entries from all sectors");
146   Address sector_address = 0;
147 
148   size_t total_corrupt_bytes = 0;
149   size_t corrupt_entries = 0;
150   bool empty_sector_found = false;
151   size_t entry_copies_missing = 0;
152 
153   for (SectorDescriptor& sector : sectors_) {
154     Address entry_address = sector_address;
155 
156     size_t sector_corrupt_bytes = 0;
157 
158     for (int num_entries_in_sector = 0; true; num_entries_in_sector++) {
159       DBG("Load entry: sector=%u, entry#=%d, address=%u",
160           unsigned(sector_address),
161           num_entries_in_sector,
162           unsigned(entry_address));
163 
164       if (!sectors_.AddressInSector(sector, entry_address)) {
165         DBG("Fell off end of sector; moving to the next sector");
166         break;
167       }
168 
169       Address next_entry_address;
170       Status status = LoadEntry(entry_address, &next_entry_address);
171       if (status.IsNotFound()) {
172         DBG("Hit un-written data in sector; moving to the next sector");
173         break;
174       } else if (!status.ok()) {
175         // The entry could not be read, indicating likely data corruption within
176         // the sector. Try to scan the remainder of the sector for other
177         // entries.
178 
179         error_detected_ = true;
180         corrupt_entries++;
181 
182         status = ScanForEntry(sector,
183                               entry_address + Entry::kMinAlignmentBytes,
184                               &next_entry_address);
185         if (!status.ok()) {
186           // No further entries in this sector. Mark the remaining bytes in the
187           // sector as corrupt (since we can't reliably know the size of the
188           // corrupt entry).
189           sector_corrupt_bytes +=
190               sector_size_bytes - (entry_address - sector_address);
191           break;
192         }
193 
194         sector_corrupt_bytes += next_entry_address - entry_address;
195       }
196 
197       // Entry loaded successfully; so get ready to load the next one.
198       entry_address = next_entry_address;
199 
200       // Update of the number of writable bytes in this sector.
201       sector.set_writable_bytes(sector_size_bytes -
202                                 (entry_address - sector_address));
203     }
204 
205     if (sector_corrupt_bytes > 0) {
206       // If the sector contains corrupt data, prevent any further entries from
207       // being written to it by indicating that it has no space. This should
208       // also make it a decent GC candidate. Valid keys in the sector are still
209       // readable as normal.
210       sector.mark_corrupt();
211       error_detected_ = true;
212 
213       WRN("Sector %u contains %uB of corrupt data",
214           sectors_.Index(sector),
215           unsigned(sector_corrupt_bytes));
216     }
217 
218     if (sector.Empty(sector_size_bytes)) {
219       empty_sector_found = true;
220     }
221     sector_address += sector_size_bytes;
222     total_corrupt_bytes += sector_corrupt_bytes;
223   }
224 
225   DBG("Second pass: Count valid bytes in each sector");
226   Address newest_key = 0;
227 
228   // For every valid entry, for each address, count the valid bytes in that
229   // sector. If the address fails to read, remove the address and mark the
230   // sector as corrupt. Track which entry has the newest transaction ID for
231   // initializing last_new_sector_.
232   for (EntryMetadata& metadata : entry_cache_) {
233     if (metadata.addresses().size() < redundancy()) {
234       DBG("Key 0x%08x missing copies, has %u, needs %u",
235           unsigned(metadata.hash()),
236           unsigned(metadata.addresses().size()),
237           unsigned(redundancy()));
238       entry_copies_missing++;
239     }
240     size_t index = 0;
241     while (index < metadata.addresses().size()) {
242       Address address = metadata.addresses()[index];
243       Entry entry;
244 
245       Status read_result = Entry::Read(partition_, address, formats_, &entry);
246 
247       SectorDescriptor& sector = sectors_.FromAddress(address);
248 
249       if (read_result.ok()) {
250         sector.AddValidBytes(entry.size());
251         index++;
252       } else {
253         corrupt_entries++;
254         total_corrupt_bytes += sector.writable_bytes();
255         error_detected_ = true;
256         sector.mark_corrupt();
257 
258         // Remove the bad address and stay at this index. The removal
259         // replaces out the removed address with the back address so
260         // this index needs to be rechecked with the new address.
261         metadata.RemoveAddress(address);
262       }
263     }
264 
265     if (metadata.IsNewerThan(last_transaction_id_)) {
266       last_transaction_id_ = metadata.transaction_id();
267       newest_key = metadata.addresses().back();
268     }
269   }
270 
271   sectors_.set_last_new_sector(newest_key);
272 
273   if (!empty_sector_found) {
274     DBG("No empty sector found");
275     error_detected_ = true;
276   }
277 
278   if (entry_copies_missing > 0) {
279     bool other_errors = error_detected_;
280     error_detected_ = true;
281 
282     if (!other_errors && entry_copies_missing == entry_cache_.total_entries()) {
283       INF("KVS configuration changed to redundancy of %u total copies per key",
284           unsigned(redundancy()));
285       return Status::OutOfRange();
286     }
287   }
288 
289   if (error_detected_) {
290     WRN("Corruption detected. Found %u corrupt bytes, %u corrupt entries, "
291         "and %u keys missing redundant copies.",
292         unsigned(total_corrupt_bytes),
293         unsigned(corrupt_entries),
294         unsigned(entry_copies_missing));
295     return Status::FailedPrecondition();
296   }
297   return OkStatus();
298 }
299 
GetStorageStats() const300 KeyValueStore::StorageStats KeyValueStore::GetStorageStats() const {
301   StorageStats stats{};
302   const size_t sector_size = partition_.sector_size_bytes();
303   bool found_empty_sector = false;
304   stats.sector_erase_count = internal_stats_.sector_erase_count;
305   stats.corrupt_sectors_recovered = internal_stats_.corrupt_sectors_recovered;
306   stats.missing_redundant_entries_recovered =
307       internal_stats_.missing_redundant_entries_recovered;
308 
309   for (const SectorDescriptor& sector : sectors_) {
310     stats.in_use_bytes += sector.valid_bytes();
311     stats.reclaimable_bytes += sector.RecoverableBytes(sector_size);
312 
313     if (!found_empty_sector && sector.Empty(sector_size)) {
314       // The KVS tries to always keep an empty sector for GC, so don't count
315       // the first empty sector seen as writable space. However, a free sector
316       // cannot always be assumed to exist; if a GC operation fails, all sectors
317       // may be partially written, in which case the space reported might be
318       // inaccurate.
319       found_empty_sector = true;
320       continue;
321     }
322 
323     stats.writable_bytes += sector.writable_bytes();
324   }
325 
326   return stats;
327 }
328 
329 // Check KVS for any error conditions. Primarily intended for test and
330 // internal use.
CheckForErrors()331 bool KeyValueStore::CheckForErrors() {
332   // Check for corrupted sectors
333   for (SectorDescriptor& sector : sectors_) {
334     if (sector.corrupt()) {
335       error_detected_ = true;
336       return error_detected();
337     }
338   }
339 
340   // Check for missing redundancy.
341   if (redundancy() > 1) {
342     for (const EntryMetadata& metadata : entry_cache_) {
343       if (metadata.addresses().size() < redundancy()) {
344         error_detected_ = true;
345         return error_detected();
346       }
347     }
348   }
349 
350   return error_detected();
351 }
352 
LoadEntry(Address entry_address,Address * next_entry_address)353 Status KeyValueStore::LoadEntry(Address entry_address,
354                                 Address* next_entry_address) {
355   Entry entry;
356   PW_TRY(Entry::Read(partition_, entry_address, formats_, &entry));
357 
358   // Read the key from flash & validate the entry (which reads the value).
359   Entry::KeyBuffer key_buffer;
360   PW_TRY_ASSIGN(size_t key_length, entry.ReadKey(key_buffer));
361   const Key key(key_buffer.data(), key_length);
362 
363   PW_TRY(entry.VerifyChecksumInFlash());
364 
365   // A valid entry was found, so update the next entry address before doing any
366   // of the checks that happen in AddNewOrUpdateExisting.
367   *next_entry_address = entry.next_address();
368   return entry_cache_.AddNewOrUpdateExisting(
369       entry.descriptor(key), entry.address(), partition_.sector_size_bytes());
370 }
371 
372 // Scans flash memory within a sector to find a KVS entry magic.
ScanForEntry(const SectorDescriptor & sector,Address start_address,Address * next_entry_address)373 Status KeyValueStore::ScanForEntry(const SectorDescriptor& sector,
374                                    Address start_address,
375                                    Address* next_entry_address) {
376   DBG("Scanning sector %u for entries starting from address %u",
377       sectors_.Index(sector),
378       unsigned(start_address));
379 
380   // Entries must start at addresses which are aligned on a multiple of
381   // Entry::kMinAlignmentBytes. However, that multiple can vary between entries.
382   // When scanning, we don't have an entry to tell us what the current alignment
383   // is, so the minimum alignment is used to be exhaustive.
384   for (Address address = AlignUp(start_address, Entry::kMinAlignmentBytes);
385        sectors_.AddressInSector(sector, address);
386        address += Entry::kMinAlignmentBytes) {
387     uint32_t magic;
388     StatusWithSize read_result =
389         partition_.Read(address, std::as_writable_bytes(std::span(&magic, 1)));
390     if (!read_result.ok()) {
391       continue;
392     }
393     if (formats_.KnownMagic(magic)) {
394       DBG("Found entry magic at address %u", unsigned(address));
395       *next_entry_address = address;
396       return OkStatus();
397     }
398   }
399 
400   return Status::NotFound();
401 }
402 
Get(Key key,std::span<byte> value_buffer,size_t offset_bytes) const403 StatusWithSize KeyValueStore::Get(Key key,
404                                   std::span<byte> value_buffer,
405                                   size_t offset_bytes) const {
406   PW_TRY_WITH_SIZE(CheckReadOperation(key));
407 
408   EntryMetadata metadata;
409   PW_TRY_WITH_SIZE(FindExisting(key, &metadata));
410 
411   return Get(key, metadata, value_buffer, offset_bytes);
412 }
413 
PutBytes(Key key,std::span<const byte> value)414 Status KeyValueStore::PutBytes(Key key, std::span<const byte> value) {
415   PW_TRY(CheckWriteOperation(key));
416   DBG("Writing key/value; key length=%u, value length=%u",
417       unsigned(key.size()),
418       unsigned(value.size()));
419 
420   if (Entry::size(partition_, key, value) > partition_.sector_size_bytes()) {
421     DBG("%u B value with %u B key cannot fit in one sector",
422         unsigned(value.size()),
423         unsigned(key.size()));
424     return Status::InvalidArgument();
425   }
426 
427   EntryMetadata metadata;
428   Status status = FindEntry(key, &metadata);
429 
430   if (status.ok()) {
431     // TODO: figure out logging how to support multiple addresses.
432     DBG("Overwriting entry for key 0x%08x in %u sectors including %u",
433         unsigned(metadata.hash()),
434         unsigned(metadata.addresses().size()),
435         sectors_.Index(metadata.first_address()));
436     return WriteEntryForExistingKey(metadata, EntryState::kValid, key, value);
437   }
438 
439   if (status.IsNotFound()) {
440     return WriteEntryForNewKey(key, value);
441   }
442 
443   return status;
444 }
445 
Delete(Key key)446 Status KeyValueStore::Delete(Key key) {
447   PW_TRY(CheckWriteOperation(key));
448 
449   EntryMetadata metadata;
450   PW_TRY(FindExisting(key, &metadata));
451 
452   // TODO: figure out logging how to support multiple addresses.
453   DBG("Writing tombstone for key 0x%08x in %u sectors including %u",
454       unsigned(metadata.hash()),
455       unsigned(metadata.addresses().size()),
456       sectors_.Index(metadata.first_address()));
457   return WriteEntryForExistingKey(metadata, EntryState::kDeleted, key, {});
458 }
459 
ReadKey()460 void KeyValueStore::Item::ReadKey() {
461   key_buffer_.fill('\0');
462 
463   Entry entry;
464   if (kvs_.ReadEntry(*iterator_, entry).ok()) {
465     entry.ReadKey(key_buffer_);
466   }
467 }
468 
operator ++()469 KeyValueStore::iterator& KeyValueStore::iterator::operator++() {
470   // Skip to the next entry that is valid (not deleted).
471   while (++item_.iterator_ != item_.kvs_.entry_cache_.end() &&
472          item_.iterator_->state() != EntryState::kValid) {
473   }
474   return *this;
475 }
476 
begin() const477 KeyValueStore::iterator KeyValueStore::begin() const {
478   internal::EntryCache::const_iterator cache_iterator = entry_cache_.begin();
479   // Skip over any deleted entries at the start of the descriptor list.
480   while (cache_iterator != entry_cache_.end() &&
481          cache_iterator->state() != EntryState::kValid) {
482     ++cache_iterator;
483   }
484   return iterator(*this, cache_iterator);
485 }
486 
ValueSize(Key key) const487 StatusWithSize KeyValueStore::ValueSize(Key key) const {
488   PW_TRY_WITH_SIZE(CheckReadOperation(key));
489 
490   EntryMetadata metadata;
491   PW_TRY_WITH_SIZE(FindExisting(key, &metadata));
492 
493   return ValueSize(metadata);
494 }
495 
ReadEntry(const EntryMetadata & metadata,Entry & entry) const496 Status KeyValueStore::ReadEntry(const EntryMetadata& metadata,
497                                 Entry& entry) const {
498   // Try to read an entry
499   Status read_result = Status::DataLoss();
500   for (Address address : metadata.addresses()) {
501     read_result = Entry::Read(partition_, address, formats_, &entry);
502     if (read_result.ok()) {
503       return read_result;
504     }
505 
506     // Found a bad address. Set the sector as corrupt.
507     error_detected_ = true;
508     sectors_.FromAddress(address).mark_corrupt();
509   }
510 
511   ERR("No valid entries for key. Data has been lost!");
512   return read_result;
513 }
514 
FindEntry(Key key,EntryMetadata * found_entry) const515 Status KeyValueStore::FindEntry(Key key, EntryMetadata* found_entry) const {
516   StatusWithSize find_result =
517       entry_cache_.Find(partition_, sectors_, formats_, key, found_entry);
518 
519   if (find_result.size() > 0u) {
520     error_detected_ = true;
521   }
522   return find_result.status();
523 }
524 
FindExisting(Key key,EntryMetadata * metadata) const525 Status KeyValueStore::FindExisting(Key key, EntryMetadata* metadata) const {
526   Status status = FindEntry(key, metadata);
527 
528   // If the key's hash collides with an existing key or if the key is deleted,
529   // treat it as if it is not in the KVS.
530   if (status.IsAlreadyExists() ||
531       (status.ok() && metadata->state() == EntryState::kDeleted)) {
532     return Status::NotFound();
533   }
534   return status;
535 }
536 
Get(Key key,const EntryMetadata & metadata,std::span<std::byte> value_buffer,size_t offset_bytes) const537 StatusWithSize KeyValueStore::Get(Key key,
538                                   const EntryMetadata& metadata,
539                                   std::span<std::byte> value_buffer,
540                                   size_t offset_bytes) const {
541   Entry entry;
542 
543   PW_TRY_WITH_SIZE(ReadEntry(metadata, entry));
544 
545   StatusWithSize result = entry.ReadValue(value_buffer, offset_bytes);
546   if (result.ok() && options_.verify_on_read && offset_bytes == 0u) {
547     Status verify_result =
548         entry.VerifyChecksum(key, value_buffer.first(result.size()));
549     if (!verify_result.ok()) {
550       std::memset(value_buffer.data(), 0, result.size());
551       return StatusWithSize(verify_result, 0);
552     }
553 
554     return StatusWithSize(verify_result, result.size());
555   }
556   return result;
557 }
558 
FixedSizeGet(Key key,void * value,size_t size_bytes) const559 Status KeyValueStore::FixedSizeGet(Key key,
560                                    void* value,
561                                    size_t size_bytes) const {
562   PW_TRY(CheckWriteOperation(key));
563 
564   EntryMetadata metadata;
565   PW_TRY(FindExisting(key, &metadata));
566 
567   return FixedSizeGet(key, metadata, value, size_bytes);
568 }
569 
FixedSizeGet(Key key,const EntryMetadata & metadata,void * value,size_t size_bytes) const570 Status KeyValueStore::FixedSizeGet(Key key,
571                                    const EntryMetadata& metadata,
572                                    void* value,
573                                    size_t size_bytes) const {
574   // Ensure that the size of the stored value matches the size of the type.
575   // Otherwise, report error. This check avoids potential memory corruption.
576   PW_TRY_ASSIGN(const size_t actual_size, ValueSize(metadata));
577 
578   if (actual_size != size_bytes) {
579     DBG("Requested %u B read, but value is %u B",
580         unsigned(size_bytes),
581         unsigned(actual_size));
582     return Status::InvalidArgument();
583   }
584 
585   StatusWithSize result =
586       Get(key, metadata, std::span(static_cast<byte*>(value), size_bytes), 0);
587 
588   return result.status();
589 }
590 
ValueSize(const EntryMetadata & metadata) const591 StatusWithSize KeyValueStore::ValueSize(const EntryMetadata& metadata) const {
592   Entry entry;
593   PW_TRY_WITH_SIZE(ReadEntry(metadata, entry));
594 
595   return StatusWithSize(entry.value_size());
596 }
597 
CheckWriteOperation(Key key) const598 Status KeyValueStore::CheckWriteOperation(Key key) const {
599   if (InvalidKey(key)) {
600     return Status::InvalidArgument();
601   }
602 
603   // For normal write operation the KVS must be fully ready.
604   if (!initialized()) {
605     return Status::FailedPrecondition();
606   }
607   return OkStatus();
608 }
609 
CheckReadOperation(Key key) const610 Status KeyValueStore::CheckReadOperation(Key key) const {
611   if (InvalidKey(key)) {
612     return Status::InvalidArgument();
613   }
614 
615   // Operations that are explicitly read-only can be done after init() has been
616   // called but not fully ready (when needing maintenance).
617   if (initialized_ == InitializationState::kNotInitialized) {
618     return Status::FailedPrecondition();
619   }
620   return OkStatus();
621 }
622 
WriteEntryForExistingKey(EntryMetadata & metadata,EntryState new_state,Key key,std::span<const byte> value)623 Status KeyValueStore::WriteEntryForExistingKey(EntryMetadata& metadata,
624                                                EntryState new_state,
625                                                Key key,
626                                                std::span<const byte> value) {
627   // Read the original entry to get the size for sector accounting purposes.
628   Entry entry;
629   PW_TRY(ReadEntry(metadata, entry));
630 
631   return WriteEntry(key, value, new_state, &metadata, &entry);
632 }
633 
WriteEntryForNewKey(Key key,std::span<const byte> value)634 Status KeyValueStore::WriteEntryForNewKey(Key key,
635                                           std::span<const byte> value) {
636   if (entry_cache_.full()) {
637     WRN("KVS full: trying to store a new entry, but can't. Have %u entries",
638         unsigned(entry_cache_.total_entries()));
639     return Status::ResourceExhausted();
640   }
641 
642   return WriteEntry(key, value, EntryState::kValid);
643 }
644 
WriteEntry(Key key,std::span<const byte> value,EntryState new_state,EntryMetadata * prior_metadata,const Entry * prior_entry)645 Status KeyValueStore::WriteEntry(Key key,
646                                  std::span<const byte> value,
647                                  EntryState new_state,
648                                  EntryMetadata* prior_metadata,
649                                  const Entry* prior_entry) {
650   // If new entry and prior entry have matching value size, state, and checksum,
651   // check if the values match. Directly compare the prior and new values
652   // because the checksum can not be depended on to establish equality, it can
653   // only be depended on to establish inequality.
654   if (prior_entry != nullptr && prior_entry->value_size() == value.size() &&
655       prior_metadata->state() == new_state &&
656       prior_entry->ValueMatches(value).ok()) {
657     // The new value matches the prior value, don't need to write anything. Just
658     // keep the existing entry.
659     DBG("Write for key 0x%08x with matching value skipped",
660         unsigned(prior_metadata->hash()));
661     return OkStatus();
662   }
663 
664   // List of addresses for sectors with space for this entry.
665   Address* reserved_addresses = entry_cache_.TempReservedAddressesForWrite();
666 
667   // Find addresses to write the entry to. This may involve garbage collecting
668   // one or more sectors.
669   const size_t entry_size = Entry::size(partition_, key, value);
670   PW_TRY(GetAddressesForWrite(reserved_addresses, entry_size));
671 
672   // Write the entry at the first address that was found.
673   Entry entry = CreateEntry(reserved_addresses[0], key, value, new_state);
674   PW_TRY(AppendEntry(entry, key, value));
675 
676   // After writing the first entry successfully, update the key descriptors.
677   // Once a single new the entry is written, the old entries are invalidated.
678   size_t prior_size = prior_entry != nullptr ? prior_entry->size() : 0;
679   EntryMetadata new_metadata =
680       CreateOrUpdateKeyDescriptor(entry, key, prior_metadata, prior_size);
681 
682   // Write the additional copies of the entry, if redundancy is greater than 1.
683   for (size_t i = 1; i < redundancy(); ++i) {
684     entry.set_address(reserved_addresses[i]);
685     PW_TRY(AppendEntry(entry, key, value));
686     new_metadata.AddNewAddress(reserved_addresses[i]);
687   }
688   return OkStatus();
689 }
690 
CreateOrUpdateKeyDescriptor(const Entry & entry,Key key,EntryMetadata * prior_metadata,size_t prior_size)691 KeyValueStore::EntryMetadata KeyValueStore::CreateOrUpdateKeyDescriptor(
692     const Entry& entry,
693     Key key,
694     EntryMetadata* prior_metadata,
695     size_t prior_size) {
696   // If there is no prior descriptor, create a new one.
697   if (prior_metadata == nullptr) {
698     return entry_cache_.AddNew(entry.descriptor(key), entry.address());
699   }
700 
701   return UpdateKeyDescriptor(
702       entry, entry.address(), prior_metadata, prior_size);
703 }
704 
UpdateKeyDescriptor(const Entry & entry,Address new_address,EntryMetadata * prior_metadata,size_t prior_size)705 KeyValueStore::EntryMetadata KeyValueStore::UpdateKeyDescriptor(
706     const Entry& entry,
707     Address new_address,
708     EntryMetadata* prior_metadata,
709     size_t prior_size) {
710   // Remove valid bytes for the old entry and its copies, which are now stale.
711   for (Address address : prior_metadata->addresses()) {
712     sectors_.FromAddress(address).RemoveValidBytes(prior_size);
713   }
714 
715   prior_metadata->Reset(entry.descriptor(prior_metadata->hash()), new_address);
716   return *prior_metadata;
717 }
718 
GetAddressesForWrite(Address * write_addresses,size_t write_size)719 Status KeyValueStore::GetAddressesForWrite(Address* write_addresses,
720                                            size_t write_size) {
721   for (size_t i = 0; i < redundancy(); i++) {
722     SectorDescriptor* sector;
723     PW_TRY(
724         GetSectorForWrite(&sector, write_size, std::span(write_addresses, i)));
725     write_addresses[i] = sectors_.NextWritableAddress(*sector);
726 
727     DBG("Found space for entry in sector %u at address %u",
728         sectors_.Index(sector),
729         unsigned(write_addresses[i]));
730   }
731 
732   return OkStatus();
733 }
734 
735 // Finds a sector to use for writing a new entry to. Does automatic garbage
736 // collection if needed and allowed.
737 //
738 //                 OK: Sector found with needed space.
739 // RESOURCE_EXHAUSTED: No sector available with the needed space.
GetSectorForWrite(SectorDescriptor ** sector,size_t entry_size,std::span<const Address> reserved)740 Status KeyValueStore::GetSectorForWrite(SectorDescriptor** sector,
741                                         size_t entry_size,
742                                         std::span<const Address> reserved) {
743   Status result = sectors_.FindSpace(sector, entry_size, reserved);
744 
745   size_t gc_sector_count = 0;
746   bool do_auto_gc = options_.gc_on_write != GargbageCollectOnWrite::kDisabled;
747 
748   // Do garbage collection as needed, so long as policy allows.
749   while (result.IsResourceExhausted() && do_auto_gc) {
750     if (options_.gc_on_write == GargbageCollectOnWrite::kOneSector) {
751       // If GC config option is kOneSector clear the flag to not do any more
752       // GC after this try.
753       do_auto_gc = false;
754     }
755     // Garbage collect and then try again to find the best sector.
756     Status gc_status = GarbageCollect(reserved);
757     if (!gc_status.ok()) {
758       if (gc_status.IsNotFound()) {
759         // Not enough space, and no reclaimable bytes, this KVS is full!
760         return Status::ResourceExhausted();
761       }
762       return gc_status;
763     }
764 
765     result = sectors_.FindSpace(sector, entry_size, reserved);
766 
767     gc_sector_count++;
768     // Allow total sectors + 2 number of GC cycles so that once reclaimable
769     // bytes in all the sectors have been reclaimed can try and free up space by
770     // moving entries for keys other than the one being worked on in to sectors
771     // that have copies of the key trying to be written.
772     if (gc_sector_count > (partition_.sector_count() + 2)) {
773       ERR("Did more GC sectors than total sectors!!!!");
774       return Status::ResourceExhausted();
775     }
776   }
777 
778   if (!result.ok()) {
779     WRN("Unable to find sector to write %u B", unsigned(entry_size));
780   }
781   return result;
782 }
783 
MarkSectorCorruptIfNotOk(Status status,SectorDescriptor * sector)784 Status KeyValueStore::MarkSectorCorruptIfNotOk(Status status,
785                                                SectorDescriptor* sector) {
786   if (!status.ok()) {
787     DBG("  Sector %u corrupt", sectors_.Index(sector));
788     sector->mark_corrupt();
789     error_detected_ = true;
790   }
791   return status;
792 }
793 
AppendEntry(const Entry & entry,Key key,std::span<const byte> value)794 Status KeyValueStore::AppendEntry(const Entry& entry,
795                                   Key key,
796                                   std::span<const byte> value) {
797   const StatusWithSize result = entry.Write(key, value);
798 
799   SectorDescriptor& sector = sectors_.FromAddress(entry.address());
800 
801   if (!result.ok()) {
802     ERR("Failed to write %u bytes at %#x. %u actually written",
803         unsigned(entry.size()),
804         unsigned(entry.address()),
805         unsigned(result.size()));
806     PW_TRY(MarkSectorCorruptIfNotOk(result.status(), &sector));
807   }
808 
809   if (options_.verify_on_write) {
810     PW_TRY(MarkSectorCorruptIfNotOk(entry.VerifyChecksumInFlash(), &sector));
811   }
812 
813   sector.RemoveWritableBytes(result.size());
814   sector.AddValidBytes(result.size());
815   return OkStatus();
816 }
817 
CopyEntryToSector(Entry & entry,SectorDescriptor * new_sector,Address new_address)818 StatusWithSize KeyValueStore::CopyEntryToSector(Entry& entry,
819                                                 SectorDescriptor* new_sector,
820                                                 Address new_address) {
821   const StatusWithSize result = entry.Copy(new_address);
822 
823   PW_TRY_WITH_SIZE(MarkSectorCorruptIfNotOk(result.status(), new_sector));
824 
825   if (options_.verify_on_write) {
826     Entry new_entry;
827     PW_TRY_WITH_SIZE(MarkSectorCorruptIfNotOk(
828         Entry::Read(partition_, new_address, formats_, &new_entry),
829         new_sector));
830     // TODO: add test that catches doing the verify on the old entry.
831     PW_TRY_WITH_SIZE(MarkSectorCorruptIfNotOk(new_entry.VerifyChecksumInFlash(),
832                                               new_sector));
833   }
834   // Entry was written successfully; update descriptor's address and the sector
835   // descriptors to reflect the new entry.
836   new_sector->RemoveWritableBytes(result.size());
837   new_sector->AddValidBytes(result.size());
838 
839   return result;
840 }
841 
RelocateEntry(const EntryMetadata & metadata,KeyValueStore::Address & address,std::span<const Address> reserved_addresses)842 Status KeyValueStore::RelocateEntry(
843     const EntryMetadata& metadata,
844     KeyValueStore::Address& address,
845     std::span<const Address> reserved_addresses) {
846   Entry entry;
847   PW_TRY(ReadEntry(metadata, entry));
848 
849   // Find a new sector for the entry and write it to the new location. For
850   // relocation the find should not not be a sector already containing the key
851   // but can be the always empty sector, since this is part of the GC process
852   // that will result in a new empty sector. Also find a sector that does not
853   // have reclaimable space (mostly for the full GC, where that would result in
854   // an immediate extra relocation).
855   SectorDescriptor* new_sector;
856 
857   PW_TRY(sectors_.FindSpaceDuringGarbageCollection(
858       &new_sector, entry.size(), metadata.addresses(), reserved_addresses));
859 
860   Address new_address = sectors_.NextWritableAddress(*new_sector);
861   PW_TRY_ASSIGN(const size_t result_size,
862                 CopyEntryToSector(entry, new_sector, new_address));
863   sectors_.FromAddress(address).RemoveValidBytes(result_size);
864   address = new_address;
865 
866   return OkStatus();
867 }
868 
FullMaintenanceHelper(MaintenanceType maintenance_type)869 Status KeyValueStore::FullMaintenanceHelper(MaintenanceType maintenance_type) {
870   if (initialized_ == InitializationState::kNotInitialized) {
871     return Status::FailedPrecondition();
872   }
873 
874   // Full maintenance can be a potentially heavy operation, and should be
875   // relatively infrequent, so log start/end at INFO level.
876   INF("Beginning full maintenance");
877   CheckForErrors();
878 
879   if (error_detected_) {
880     PW_TRY(Repair());
881   }
882   StatusWithSize update_status = UpdateEntriesToPrimaryFormat();
883   Status overall_status = update_status.status();
884 
885   // Make sure all the entries are on the primary format.
886   if (!overall_status.ok()) {
887     ERR("Failed to update all entries to the primary format");
888   }
889 
890   SectorDescriptor* sector = sectors_.last_new();
891 
892   // Calculate number of bytes for the threshold.
893   size_t threshold_bytes =
894       (partition_.size_bytes() * kGcUsageThresholdPercentage) / 100;
895 
896   // Is bytes in use over the threshold.
897   StorageStats stats = GetStorageStats();
898   bool over_usage_threshold = stats.in_use_bytes > threshold_bytes;
899   bool heavy = (maintenance_type == MaintenanceType::kHeavy);
900   bool force_gc = heavy || over_usage_threshold || (update_status.size() > 0);
901 
902   // TODO: look in to making an iterator method for cycling through sectors
903   // starting from last_new_sector_.
904   Status gc_status;
905   for (size_t j = 0; j < sectors_.size(); j++) {
906     sector += 1;
907     if (sector == sectors_.end()) {
908       sector = sectors_.begin();
909     }
910 
911     if (sector->RecoverableBytes(partition_.sector_size_bytes()) > 0 &&
912         (force_gc || sector->valid_bytes() == 0)) {
913       gc_status = GarbageCollectSector(*sector, {});
914       if (!gc_status.ok()) {
915         ERR("Failed to garbage collect all sectors");
916         break;
917       }
918     }
919   }
920   if (overall_status.ok()) {
921     overall_status = gc_status;
922   }
923 
924   if (overall_status.ok()) {
925     INF("Full maintenance complete");
926   } else {
927     ERR("Full maintenance finished with some errors");
928   }
929   return overall_status;
930 }
931 
PartialMaintenance()932 Status KeyValueStore::PartialMaintenance() {
933   if (initialized_ == InitializationState::kNotInitialized) {
934     return Status::FailedPrecondition();
935   }
936 
937   CheckForErrors();
938   // Do automatic repair, if KVS options allow for it.
939   if (error_detected_ && options_.recovery != ErrorRecovery::kManual) {
940     PW_TRY(Repair());
941   }
942   return GarbageCollect(std::span<const Address>());
943 }
944 
GarbageCollect(std::span<const Address> reserved_addresses)945 Status KeyValueStore::GarbageCollect(
946     std::span<const Address> reserved_addresses) {
947   DBG("Garbage Collect a single sector");
948   for ([[maybe_unused]] Address address : reserved_addresses) {
949     DBG("   Avoid address %u", unsigned(address));
950   }
951 
952   // Step 1: Find the sector to garbage collect
953   SectorDescriptor* sector_to_gc =
954       sectors_.FindSectorToGarbageCollect(reserved_addresses);
955 
956   if (sector_to_gc == nullptr) {
957     // Nothing to GC.
958     return Status::NotFound();
959   }
960 
961   // Step 2: Garbage collect the selected sector.
962   return GarbageCollectSector(*sector_to_gc, reserved_addresses);
963 }
964 
RelocateKeyAddressesInSector(SectorDescriptor & sector_to_gc,const EntryMetadata & metadata,std::span<const Address> reserved_addresses)965 Status KeyValueStore::RelocateKeyAddressesInSector(
966     SectorDescriptor& sector_to_gc,
967     const EntryMetadata& metadata,
968     std::span<const Address> reserved_addresses) {
969   for (FlashPartition::Address& address : metadata.addresses()) {
970     if (sectors_.AddressInSector(sector_to_gc, address)) {
971       DBG("  Relocate entry for Key 0x%08" PRIx32 ", sector %u",
972           metadata.hash(),
973           sectors_.Index(sectors_.FromAddress(address)));
974       PW_TRY(RelocateEntry(metadata, address, reserved_addresses));
975     }
976   }
977 
978   return OkStatus();
979 };
980 
GarbageCollectSector(SectorDescriptor & sector_to_gc,std::span<const Address> reserved_addresses)981 Status KeyValueStore::GarbageCollectSector(
982     SectorDescriptor& sector_to_gc,
983     std::span<const Address> reserved_addresses) {
984   DBG("  Garbage Collect sector %u", sectors_.Index(sector_to_gc));
985 
986   // Step 1: Move any valid entries in the GC sector to other sectors
987   if (sector_to_gc.valid_bytes() != 0) {
988     for (EntryMetadata& metadata : entry_cache_) {
989       PW_TRY(RelocateKeyAddressesInSector(
990           sector_to_gc, metadata, reserved_addresses));
991     }
992   }
993 
994   if (sector_to_gc.valid_bytes() != 0) {
995     ERR("  Failed to relocate valid entries from sector being garbage "
996         "collected, %u valid bytes remain",
997         unsigned(sector_to_gc.valid_bytes()));
998     return Status::Internal();
999   }
1000 
1001   // Step 2: Reinitialize the sector
1002   if (!sector_to_gc.Empty(partition_.sector_size_bytes())) {
1003     sector_to_gc.mark_corrupt();
1004     internal_stats_.sector_erase_count++;
1005     PW_TRY(partition_.Erase(sectors_.BaseAddress(sector_to_gc), 1));
1006     sector_to_gc.set_writable_bytes(partition_.sector_size_bytes());
1007   }
1008 
1009   DBG("  Garbage Collect sector %u complete", sectors_.Index(sector_to_gc));
1010   return OkStatus();
1011 }
1012 
UpdateEntriesToPrimaryFormat()1013 StatusWithSize KeyValueStore::UpdateEntriesToPrimaryFormat() {
1014   size_t entries_updated = 0;
1015   for (EntryMetadata& prior_metadata : entry_cache_) {
1016     Entry entry;
1017     PW_TRY_WITH_SIZE(ReadEntry(prior_metadata, entry));
1018     if (formats_.primary().magic == entry.magic()) {
1019       // Ignore entries that are already on the primary format.
1020       continue;
1021     }
1022 
1023     DBG("Updating entry 0x%08x from old format [0x%08x] to new format "
1024         "[0x%08x]",
1025         unsigned(prior_metadata.hash()),
1026         unsigned(entry.magic()),
1027         unsigned(formats_.primary().magic));
1028 
1029     entries_updated++;
1030 
1031     last_transaction_id_ += 1;
1032     PW_TRY_WITH_SIZE(entry.Update(formats_.primary(), last_transaction_id_));
1033 
1034     // List of addresses for sectors with space for this entry.
1035     Address* reserved_addresses = entry_cache_.TempReservedAddressesForWrite();
1036 
1037     // Find addresses to write the entry to. This may involve garbage collecting
1038     // one or more sectors.
1039     PW_TRY_WITH_SIZE(GetAddressesForWrite(reserved_addresses, entry.size()));
1040 
1041     PW_TRY_WITH_SIZE(
1042         CopyEntryToSector(entry,
1043                           &sectors_.FromAddress(reserved_addresses[0]),
1044                           reserved_addresses[0]));
1045 
1046     // After writing the first entry successfully, update the key descriptors.
1047     // Once a single new the entry is written, the old entries are invalidated.
1048     EntryMetadata new_metadata = UpdateKeyDescriptor(
1049         entry, reserved_addresses[0], &prior_metadata, entry.size());
1050 
1051     // Write the additional copies of the entry, if redundancy is greater
1052     // than 1.
1053     for (size_t i = 1; i < redundancy(); ++i) {
1054       PW_TRY_WITH_SIZE(
1055           CopyEntryToSector(entry,
1056                             &sectors_.FromAddress(reserved_addresses[i]),
1057                             reserved_addresses[i]));
1058       new_metadata.AddNewAddress(reserved_addresses[i]);
1059     }
1060   }
1061 
1062   return StatusWithSize(entries_updated);
1063 }
1064 
1065 // Add any missing redundant entries/copies for a key.
AddRedundantEntries(EntryMetadata & metadata)1066 Status KeyValueStore::AddRedundantEntries(EntryMetadata& metadata) {
1067   Entry entry;
1068   PW_TRY(ReadEntry(metadata, entry));
1069   PW_TRY(entry.VerifyChecksumInFlash());
1070 
1071   while (metadata.addresses().size() < redundancy()) {
1072     SectorDescriptor* new_sector;
1073     PW_TRY(GetSectorForWrite(&new_sector, entry.size(), metadata.addresses()));
1074 
1075     Address new_address = sectors_.NextWritableAddress(*new_sector);
1076     PW_TRY(CopyEntryToSector(entry, new_sector, new_address));
1077 
1078     metadata.AddNewAddress(new_address);
1079   }
1080   return OkStatus();
1081 }
1082 
RepairCorruptSectors()1083 Status KeyValueStore::RepairCorruptSectors() {
1084   // Try to GC each corrupt sector, even if previous sectors fail. If GC of a
1085   // sector failed on the first pass, then do a second pass, since a later
1086   // sector might have cleared up space or otherwise unblocked the earlier
1087   // failed sector.
1088   Status repair_status = OkStatus();
1089 
1090   size_t loop_count = 0;
1091   do {
1092     loop_count++;
1093     // Error of RESOURCE_EXHAUSTED indicates no space found for relocation.
1094     // Reset back to OK for the next pass.
1095     if (repair_status.IsResourceExhausted()) {
1096       repair_status = OkStatus();
1097     }
1098 
1099     DBG("   Pass %u", unsigned(loop_count));
1100     for (SectorDescriptor& sector : sectors_) {
1101       if (sector.corrupt()) {
1102         DBG("   Found sector %u with corruption", sectors_.Index(sector));
1103         Status sector_status = GarbageCollectSector(sector, {});
1104         if (sector_status.ok()) {
1105           internal_stats_.corrupt_sectors_recovered += 1;
1106         } else if (repair_status.ok() || repair_status.IsResourceExhausted()) {
1107           repair_status = sector_status;
1108         }
1109       }
1110     }
1111     DBG("   Pass %u complete", unsigned(loop_count));
1112   } while (!repair_status.ok() && loop_count < 2);
1113 
1114   return repair_status;
1115 }
1116 
EnsureFreeSectorExists()1117 Status KeyValueStore::EnsureFreeSectorExists() {
1118   Status repair_status = OkStatus();
1119   bool empty_sector_found = false;
1120 
1121   DBG("   Find empty sector");
1122   for (SectorDescriptor& sector : sectors_) {
1123     if (sector.Empty(partition_.sector_size_bytes())) {
1124       empty_sector_found = true;
1125       DBG("   Empty sector found");
1126       break;
1127     }
1128   }
1129   if (empty_sector_found == false) {
1130     DBG("   No empty sector found, attempting to GC a free sector");
1131     Status sector_status = GarbageCollect(std::span<const Address, 0>());
1132     if (repair_status.ok() && !sector_status.ok()) {
1133       DBG("   Unable to free an empty sector");
1134       repair_status = sector_status;
1135     }
1136   }
1137 
1138   return repair_status;
1139 }
1140 
EnsureEntryRedundancy()1141 Status KeyValueStore::EnsureEntryRedundancy() {
1142   Status repair_status = OkStatus();
1143 
1144   if (redundancy() == 1) {
1145     DBG("   Redundancy not in use, nothting to check");
1146     return OkStatus();
1147   }
1148 
1149   DBG("   Write any needed additional duplicate copies of keys to fulfill %u"
1150       " redundancy",
1151       unsigned(redundancy()));
1152   for (EntryMetadata& metadata : entry_cache_) {
1153     if (metadata.addresses().size() >= redundancy()) {
1154       continue;
1155     }
1156 
1157     DBG("   Key with %u of %u copies found, adding missing copies",
1158         unsigned(metadata.addresses().size()),
1159         unsigned(redundancy()));
1160     Status fill_status = AddRedundantEntries(metadata);
1161     if (fill_status.ok()) {
1162       internal_stats_.missing_redundant_entries_recovered += 1;
1163       DBG("   Key missing copies added");
1164     } else {
1165       DBG("   Failed to add key missing copies");
1166       if (repair_status.ok()) {
1167         repair_status = fill_status;
1168       }
1169     }
1170   }
1171 
1172   return repair_status;
1173 }
1174 
FixErrors()1175 Status KeyValueStore::FixErrors() {
1176   DBG("Fixing KVS errors");
1177 
1178   // Step 1: Garbage collect any sectors marked as corrupt.
1179   Status overall_status = RepairCorruptSectors();
1180 
1181   // Step 2: Make sure there is at least 1 empty sector. This needs to be a
1182   // seperate check of sectors from step 1, because a found empty sector might
1183   // get written to by a later GC that fails and does not result in a free
1184   // sector.
1185   Status repair_status = EnsureFreeSectorExists();
1186   if (overall_status.ok()) {
1187     overall_status = repair_status;
1188   }
1189 
1190   // Step 3: Make sure each stored key has the full number of redundant
1191   // entries.
1192   repair_status = EnsureEntryRedundancy();
1193   if (overall_status.ok()) {
1194     overall_status = repair_status;
1195   }
1196 
1197   if (overall_status.ok()) {
1198     error_detected_ = false;
1199     initialized_ = InitializationState::kReady;
1200   }
1201   return overall_status;
1202 }
1203 
Repair()1204 Status KeyValueStore::Repair() {
1205   // If errors have been detected, just reinit the KVS metadata. This does a
1206   // full deep error check and any needed repairs. Then repair any errors.
1207   INF("Starting KVS repair");
1208 
1209   DBG("Reinitialize KVS metadata");
1210   InitializeMetadata();
1211 
1212   return FixErrors();
1213 }
1214 
CreateEntry(Address address,Key key,std::span<const byte> value,EntryState state)1215 KeyValueStore::Entry KeyValueStore::CreateEntry(Address address,
1216                                                 Key key,
1217                                                 std::span<const byte> value,
1218                                                 EntryState state) {
1219   // Always bump the transaction ID when creating a new entry.
1220   //
1221   // Burning transaction IDs prevents inconsistencies between flash and memory
1222   // that which could happen if a write succeeds, but for some reason the read
1223   // and verify step fails. Here's how this would happen:
1224   //
1225   //   1. The entry is written but for some reason the flash reports failure OR
1226   //      The write succeeds, but the read / verify operation fails.
1227   //   2. The transaction ID is NOT incremented, because of the failure
1228   //   3. (later) A new entry is written, re-using the transaction ID (oops)
1229   //
1230   // By always burning transaction IDs, the above problem can't happen.
1231   last_transaction_id_ += 1;
1232 
1233   if (state == EntryState::kDeleted) {
1234     return Entry::Tombstone(
1235         partition_, address, formats_.primary(), key, last_transaction_id_);
1236   }
1237   return Entry::Valid(partition_,
1238                       address,
1239                       formats_.primary(),
1240                       key,
1241                       value,
1242                       last_transaction_id_);
1243 }
1244 
LogDebugInfo() const1245 void KeyValueStore::LogDebugInfo() const {
1246   const size_t sector_size_bytes = partition_.sector_size_bytes();
1247   DBG("====================== KEY VALUE STORE DUMP =========================");
1248   DBG(" ");
1249   DBG("Flash partition:");
1250   DBG("  Sector count     = %u", unsigned(partition_.sector_count()));
1251   DBG("  Sector max count = %u", unsigned(sectors_.max_size()));
1252   DBG("  Sectors in use   = %u", unsigned(sectors_.size()));
1253   DBG("  Sector size      = %u", unsigned(sector_size_bytes));
1254   DBG("  Total size       = %u", unsigned(partition_.size_bytes()));
1255   DBG("  Alignment        = %u", unsigned(partition_.alignment_bytes()));
1256   DBG(" ");
1257   DBG("Key descriptors:");
1258   DBG("  Entry count     = %u", unsigned(entry_cache_.total_entries()));
1259   DBG("  Max entry count = %u", unsigned(entry_cache_.max_entries()));
1260   DBG(" ");
1261   DBG("      #     hash        version    address   address (hex)");
1262   size_t count = 0;
1263   for (const EntryMetadata& metadata : entry_cache_) {
1264     DBG("   |%3zu: | %8zx  |%8zu  | %8zu | %8zx",
1265         count++,
1266         size_t(metadata.hash()),
1267         size_t(metadata.transaction_id()),
1268         size_t(metadata.first_address()),
1269         size_t(metadata.first_address()));
1270   }
1271   DBG(" ");
1272 
1273   DBG("Sector descriptors:");
1274   DBG("      #     tail free  valid    has_space");
1275   for (const SectorDescriptor& sd : sectors_) {
1276     DBG("   |%3u: | %8zu  |%8zu  | %s",
1277         sectors_.Index(sd),
1278         size_t(sd.writable_bytes()),
1279         sd.valid_bytes(),
1280         sd.writable_bytes() ? "YES" : "");
1281   }
1282   DBG(" ");
1283 
1284   // TODO: This should stop logging after some threshold.
1285   // size_t dumped_bytes = 0;
1286   DBG("Sector raw data:");
1287   for (size_t sector_id = 0; sector_id < sectors_.size(); ++sector_id) {
1288     // Read sector data. Yes, this will blow the stack on embedded.
1289     std::array<byte, 500> raw_sector_data;  // TODO!!!
1290     [[maybe_unused]] StatusWithSize sws =
1291         partition_.Read(sector_id * sector_size_bytes, raw_sector_data);
1292     DBG("Read: %u bytes", unsigned(sws.size()));
1293 
1294     DBG("  base    addr  offs   0  1  2  3  4  5  6  7");
1295     for (size_t i = 0; i < sector_size_bytes; i += 8) {
1296       DBG("  %3zu %8zx %5zu | %02x %02x %02x %02x %02x %02x %02x %02x",
1297           sector_id,
1298           (sector_id * sector_size_bytes) + i,
1299           i,
1300           static_cast<unsigned int>(raw_sector_data[i + 0]),
1301           static_cast<unsigned int>(raw_sector_data[i + 1]),
1302           static_cast<unsigned int>(raw_sector_data[i + 2]),
1303           static_cast<unsigned int>(raw_sector_data[i + 3]),
1304           static_cast<unsigned int>(raw_sector_data[i + 4]),
1305           static_cast<unsigned int>(raw_sector_data[i + 5]),
1306           static_cast<unsigned int>(raw_sector_data[i + 6]),
1307           static_cast<unsigned int>(raw_sector_data[i + 7]));
1308 
1309       // TODO: Fix exit condition.
1310       if (i > 128) {
1311         break;
1312       }
1313     }
1314     DBG(" ");
1315   }
1316 
1317   DBG("////////////////////// KEY VALUE STORE DUMP END /////////////////////");
1318 }
1319 
LogSectors() const1320 void KeyValueStore::LogSectors() const {
1321   DBG("Sector descriptors: count %u", unsigned(sectors_.size()));
1322   for (auto& sector : sectors_) {
1323     DBG("  - Sector %u: valid %u, recoverable %u, free %u",
1324         sectors_.Index(sector),
1325         unsigned(sector.valid_bytes()),
1326         unsigned(sector.RecoverableBytes(partition_.sector_size_bytes())),
1327         unsigned(sector.writable_bytes()));
1328   }
1329 }
1330 
LogKeyDescriptor() const1331 void KeyValueStore::LogKeyDescriptor() const {
1332   DBG("Key descriptors: count %u", unsigned(entry_cache_.total_entries()));
1333   for (const EntryMetadata& metadata : entry_cache_) {
1334     DBG("  - Key: %s, hash %#x, transaction ID %u, first address %#x",
1335         metadata.state() == EntryState::kDeleted ? "Deleted" : "Valid",
1336         unsigned(metadata.hash()),
1337         unsigned(metadata.transaction_id()),
1338         unsigned(metadata.first_address()));
1339   }
1340 }
1341 
1342 }  // namespace pw::kvs
1343