blob: 4a686d8f07e369089fc030b15fbbce7d7b88a123 [file] [log] [blame]
Wyatt Heplerb7609542020-01-24 10:29:54 -08001// 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
Wyatt Heplerb7609542020-01-24 10:29:54 -080015#include "pw_kvs/key_value_store.h"
16
Wyatt Heplerbab0e202020-02-04 07:40:08 -080017#include <algorithm>
Wyatt Hepler5a33d8c2020-02-06 09:32:58 -080018#include <cinttypes>
Wyatt Heplerb7609542020-01-24 10:29:54 -080019#include <cstring>
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -080020#include <type_traits>
Wyatt Heplerb7609542020-01-24 10:29:54 -080021
Keir Mierle8c352dc2020-02-02 13:58:19 -080022#define PW_LOG_USE_ULTRA_SHORT_NAMES 1
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -080023#include "pw_kvs_private/format.h"
24#include "pw_kvs_private/macros.h"
Keir Mierle8c352dc2020-02-02 13:58:19 -080025#include "pw_log/log.h"
Wyatt Heplerb7609542020-01-24 10:29:54 -080026
Wyatt Hepler2ad60672020-01-21 08:00:16 -080027namespace pw::kvs {
Wyatt Heplerb7609542020-01-24 10:29:54 -080028
Wyatt Hepleracaacf92020-01-24 10:58:30 -080029using std::byte;
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -080030using std::string_view;
Wyatt Hepleracaacf92020-01-24 10:58:30 -080031
Wyatt Heplerad0a7932020-02-06 08:20:38 -080032KeyValueStore::KeyValueStore(FlashPartition* partition,
33 const EntryHeaderFormat& format,
34 const Options& options)
35 : partition_(*partition),
36 entry_header_format_(format),
37 options_(options),
38 key_descriptor_list_{},
39 key_descriptor_list_size_(0),
40 sector_map_{},
41 sector_map_size_(partition_.sector_count()),
42 last_new_sector_(sector_map_.data()),
43 working_buffer_{} {}
44
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -080045Status KeyValueStore::Init() {
Wyatt Heplerad0a7932020-02-06 08:20:38 -080046 if (kMaxUsableSectors < sector_map_size_) {
47 CRT("KeyValueStore::kMaxUsableSectors must be at least as large as the "
48 "number of sectors in the flash partition");
49 return Status::FAILED_PRECONDITION;
50 }
51
52 if (kMaxUsableSectors > sector_map_size_) {
53 DBG("KeyValueStore::kMaxUsableSectors is %zu sectors larger than needed",
54 kMaxUsableSectors - sector_map_size_);
55 }
56
Keir Mierle8c352dc2020-02-02 13:58:19 -080057 // Reset the number of occupied key descriptors; we will fill them later.
58 key_descriptor_list_size_ = 0;
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -080059
David Rogers8ce55cd2020-02-04 19:41:48 -080060 // TODO: init last_new_sector_ to a random sector. Since the on-flash stored
61 // information does not allow recovering the previous last_new_sector_ after
62 // clean start, random is a good second choice.
63
Keir Mierle8c352dc2020-02-02 13:58:19 -080064 const size_t sector_size_bytes = partition_.sector_size_bytes();
Keir Mierle8c352dc2020-02-02 13:58:19 -080065
David Rogersf0a35442020-02-04 12:16:38 -080066 if (working_buffer_.size() < sector_size_bytes) {
67 CRT("ERROR: working_buffer_ (%zu bytes) is smaller than sector "
68 "size (%zu bytes)",
69 working_buffer_.size(),
70 sector_size_bytes);
71 return Status::INVALID_ARGUMENT;
72 }
73
Keir Mierle8c352dc2020-02-02 13:58:19 -080074 DBG("First pass: Read all entries from all sectors");
Wyatt Heplerad0a7932020-02-06 08:20:38 -080075 for (size_t sector_id = 0; sector_id < sector_map_size_; ++sector_id) {
Keir Mierle8c352dc2020-02-02 13:58:19 -080076 // Track writable bytes in this sector. Updated after reading each entry.
77 sector_map_[sector_id].tail_free_bytes = sector_size_bytes;
78
79 const Address sector_address = sector_id * sector_size_bytes;
80 Address entry_address = sector_address;
81
82 for (int num_entries_in_sector = 0;; num_entries_in_sector++) {
83 DBG("Load entry: sector=%zu, entry#=%d, address=%zu",
84 sector_id,
85 num_entries_in_sector,
86 size_t(entry_address));
87
88 if (!AddressInSector(sector_map_[sector_id], entry_address)) {
89 DBG("Fell off end of sector; moving to the next sector");
90 break;
91 }
92
93 Address next_entry_address;
94 Status status = LoadEntry(entry_address, &next_entry_address);
95 if (status == Status::NOT_FOUND) {
96 DBG("Hit un-written data in sector; moving to the next sector");
97 break;
98 }
99 if (status == Status::DATA_LOSS) {
100 // It's not clear KVS can make a unilateral decision about what to do
101 // in corruption cases. It's an application decision, for which we
102 // should offer some configurability. For now, entirely bail out of
103 // loading and give up.
104 //
105 // Later, scan for remaining valid keys; since it's entirely possible
106 // that there is a duplicate of the key elsewhere and everything is
107 // fine. Later, we can wipe and maybe recover the sector.
108 //
109 // TODO: Implement rest-of-sector scanning for valid entries.
110 return Status::DATA_LOSS;
111 }
112 TRY(status);
113
114 // Entry loaded successfully; so get ready to load the next one.
115 entry_address = next_entry_address;
116
117 // Update of the number of writable bytes in this sector.
118 sector_map_[sector_id].tail_free_bytes =
119 sector_size_bytes - (entry_address - sector_address);
120 }
121 }
122
123 DBG("Second pass: Count valid bytes in each sector");
124 // Initialize the sector sizes.
Wyatt Heplerad0a7932020-02-06 08:20:38 -0800125 for (size_t sector_id = 0; sector_id < sector_map_size_; ++sector_id) {
Keir Mierle8c352dc2020-02-02 13:58:19 -0800126 sector_map_[sector_id].valid_bytes = 0;
127 }
128 // For every valid key, increment the valid bytes for that sector.
129 for (size_t key_id = 0; key_id < key_descriptor_list_size_; ++key_id) {
130 uint32_t sector_id =
131 key_descriptor_list_[key_id].address / sector_size_bytes;
Keir Mierle8c352dc2020-02-02 13:58:19 -0800132 EntryHeader header;
Wyatt Hepler4d78cd62020-02-05 13:05:58 -0800133 TRY(ReadEntryHeader(key_descriptor_list_[key_id].address, &header));
Wyatt Hepler93b889d2020-02-05 09:01:18 -0800134 sector_map_[sector_id].valid_bytes += header.size();
Keir Mierle8c352dc2020-02-02 13:58:19 -0800135 }
Wyatt Hepler729f28c2020-02-05 09:46:00 -0800136 initialized_ = true;
Keir Mierle8c352dc2020-02-02 13:58:19 -0800137 return Status::OK;
138}
139
140Status KeyValueStore::LoadEntry(Address entry_address,
141 Address* next_entry_address) {
Keir Mierle8c352dc2020-02-02 13:58:19 -0800142 EntryHeader header;
Wyatt Hepler4d78cd62020-02-05 13:05:58 -0800143 TRY(ReadEntryHeader(entry_address, &header));
Keir Mierle8c352dc2020-02-02 13:58:19 -0800144 // TODO: Should likely add a "LogHeader" method or similar.
145 DBG("Header: ");
146 DBG(" Address = 0x%zx", size_t(entry_address));
147 DBG(" Magic = 0x%zx", size_t(header.magic()));
Wyatt Hepler6e3a83b2020-02-04 07:36:45 -0800148 DBG(" Checksum = 0x%zx", size_t(header.checksum()));
Keir Mierle8c352dc2020-02-02 13:58:19 -0800149 DBG(" Key length = 0x%zx", size_t(header.key_length()));
150 DBG(" Value length = 0x%zx", size_t(header.value_length()));
Wyatt Hepler93b889d2020-02-05 09:01:18 -0800151 DBG(" Entry size = 0x%zx", size_t(header.size()));
Wyatt Hepler116d1162020-02-06 09:42:59 -0800152 DBG(" Alignment = 0x%zx", size_t(header.alignment_bytes()));
Keir Mierle8c352dc2020-02-02 13:58:19 -0800153
154 if (HeaderLooksLikeUnwrittenData(header)) {
155 return Status::NOT_FOUND;
156 }
Keir Mierle8c352dc2020-02-02 13:58:19 -0800157
158 // TODO: Handle multiple magics for formats that have changed.
159 if (header.magic() != entry_header_format_.magic) {
160 // TODO: It may be cleaner to have some logging helpers for these cases.
161 CRT("Found corrupt magic: %zx; expecting %zx; at address %zx",
162 size_t(header.magic()),
163 size_t(entry_header_format_.magic),
164 size_t(entry_address));
165 return Status::DATA_LOSS;
166 }
167
168 // Read the key from flash & validate the entry (which reads the value).
169 KeyBuffer key_buffer;
Wyatt Hepler4d78cd62020-02-05 13:05:58 -0800170 TRY(ReadEntryKey(entry_address, header.key_length(), key_buffer.data()));
Wyatt Heplerbab0e202020-02-04 07:40:08 -0800171 const string_view key(key_buffer.data(), header.key_length());
172
Wyatt Hepler6e3a83b2020-02-04 07:36:45 -0800173 TRY(header.VerifyChecksumInFlash(
Wyatt Hepler4d78cd62020-02-05 13:05:58 -0800174 &partition_, entry_address, entry_header_format_.checksum));
175
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800176 KeyDescriptor key_descriptor(
177 key,
178 header.key_version(),
179 entry_address,
180 header.deleted() ? KeyDescriptor::kDeleted : KeyDescriptor::kValid);
Keir Mierle8c352dc2020-02-02 13:58:19 -0800181
182 DBG("Key hash: %zx (%zu)",
183 size_t(key_descriptor.key_hash),
184 size_t(key_descriptor.key_hash));
185
186 TRY(AppendNewOrOverwriteStaleExistingDescriptor(key_descriptor));
187
188 // TODO: Extract this to something like "NextValidEntryAddress".
Wyatt Hepler97fc7942020-02-06 15:55:45 -0800189 *next_entry_address = key_descriptor.address + header.size();
Keir Mierle8c352dc2020-02-02 13:58:19 -0800190
191 return Status::OK;
192}
193
194// TODO: This method is the trigger of the O(valid_entries * all_entries) time
195// complexity for reading. At some cost to memory, this could be optimized by
196// using a hash table instead of scanning, but in practice this should be fine
197// for a small number of keys
198Status KeyValueStore::AppendNewOrOverwriteStaleExistingDescriptor(
199 const KeyDescriptor& key_descriptor) {
200 // With the new key descriptor, either add it to the descriptor table or
201 // overwrite an existing entry with an older version of the key.
202 KeyDescriptor* existing_descriptor = FindDescriptor(key_descriptor.key_hash);
203 if (existing_descriptor) {
204 if (existing_descriptor->key_version < key_descriptor.key_version) {
205 // Existing entry is old; replace the existing entry with the new one.
206 *existing_descriptor = key_descriptor;
207 } else {
208 // Otherwise, check for data integrity and leave the existing entry.
209 if (existing_descriptor->key_version == key_descriptor.key_version) {
210 ERR("Data loss: Duplicated old(=%zu) and new(=%zu) version",
211 size_t(existing_descriptor->key_version),
212 size_t(key_descriptor.key_version));
213 return Status::DATA_LOSS;
214 }
215 DBG("Found stale entry when appending; ignoring");
216 }
217 return Status::OK;
218 }
219 // Write new entry.
220 KeyDescriptor* newly_allocated_key_descriptor;
221 TRY(AppendEmptyDescriptor(&newly_allocated_key_descriptor));
222 *newly_allocated_key_descriptor = key_descriptor;
223 return Status::OK;
224}
225
226// TODO: Need a better name.
227Status KeyValueStore::AppendEmptyDescriptor(KeyDescriptor** new_descriptor) {
228 if (KeyListFull()) {
229 // TODO: Is this the right return code?
230 return Status::RESOURCE_EXHAUSTED;
231 }
232 *new_descriptor = &key_descriptor_list_[key_descriptor_list_size_++];
233 return Status::OK;
234}
235
236// TODO: Finish.
237bool KeyValueStore::HeaderLooksLikeUnwrittenData(
238 const EntryHeader& header) const {
239 // TODO: This is not correct; it should call through to flash memory.
240 return header.magic() == 0xffffffff;
241}
242
243KeyValueStore::KeyDescriptor* KeyValueStore::FindDescriptor(uint32_t hash) {
244 for (size_t key_id = 0; key_id < key_descriptor_list_size_; key_id++) {
245 if (key_descriptor_list_[key_id].key_hash == hash) {
246 return &(key_descriptor_list_[key_id]);
247 }
248 }
249 return nullptr;
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800250}
251
252StatusWithSize KeyValueStore::Get(string_view key,
253 span<byte> value_buffer) const {
Wyatt Hepler729f28c2020-02-05 09:46:00 -0800254 TRY(CheckOperation(key));
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800255
David Rogers2761aeb2020-01-31 17:09:00 -0800256 const KeyDescriptor* key_descriptor;
257 TRY(FindKeyDescriptor(key, &key_descriptor));
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800258
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800259 if (key_descriptor->deleted()) {
260 return Status::NOT_FOUND;
261 }
262
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800263 EntryHeader header;
Wyatt Hepler4d78cd62020-02-05 13:05:58 -0800264 TRY(ReadEntryHeader(key_descriptor->address, &header));
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800265
Keir Mierle8c352dc2020-02-02 13:58:19 -0800266 StatusWithSize result = ReadEntryValue(*key_descriptor, header, value_buffer);
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800267 if (result.ok() && options_.verify_on_read) {
Wyatt Hepler6e3a83b2020-02-04 07:36:45 -0800268 return header.VerifyChecksum(entry_header_format_.checksum,
269 key,
270 value_buffer.subspan(0, result.size()));
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800271 }
272 return result;
273}
274
275Status KeyValueStore::Put(string_view key, span<const byte> value) {
Keir Mierle8c352dc2020-02-02 13:58:19 -0800276 DBG("Writing key/value; key length=%zu, value length=%zu",
277 key.size(),
278 value.size());
Wyatt Hepler729f28c2020-02-05 09:46:00 -0800279
280 TRY(CheckOperation(key));
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800281
282 if (value.size() > (1 << 24)) {
283 // TODO: Reject sizes that are larger than the maximum?
284 }
285
David Rogers2761aeb2020-01-31 17:09:00 -0800286 KeyDescriptor* key_descriptor;
287 if (FindKeyDescriptor(key, &key_descriptor).ok()) {
Wyatt Hepler5a33d8c2020-02-06 09:32:58 -0800288 DBG("Writing over existing entry for key 0x%08" PRIx32,
289 key_descriptor->key_hash);
290 return WriteEntryForExistingKey(
291 key_descriptor, KeyDescriptor::kValid, key, value);
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800292 }
David Rogers2761aeb2020-01-31 17:09:00 -0800293
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800294 return WriteEntryForNewKey(key, value);
295}
296
297Status KeyValueStore::Delete(string_view key) {
Wyatt Hepler729f28c2020-02-05 09:46:00 -0800298 TRY(CheckOperation(key));
299
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800300 KeyDescriptor* key_descriptor;
301 TRY(FindKeyDescriptor(key, &key_descriptor));
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800302
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800303 if (key_descriptor->deleted()) {
304 return Status::NOT_FOUND;
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800305 }
306
Wyatt Hepler5a33d8c2020-02-06 09:32:58 -0800307 DBG("Writing tombstone for key 0x%08" PRIx32, key_descriptor->key_hash);
308 return WriteEntryForExistingKey(
309 key_descriptor, KeyDescriptor::kDeleted, key, {});
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800310}
311
312KeyValueStore::iterator& KeyValueStore::iterator::operator++() {
313 // Skip to the next entry that is valid (not deleted).
314 while (++index_ < item_.kvs_.key_descriptor_list_size_ &&
315 descriptor().deleted()) {
316 }
317 return *this;
318}
319
320const KeyValueStore::Item& KeyValueStore::iterator::operator*() {
321 std::memset(item_.key_buffer_.data(), 0, item_.key_buffer_.size());
322
323 EntryHeader header;
324 if (item_.kvs_.ReadEntryHeader(descriptor().address, &header).ok()) {
325 item_.kvs_.ReadEntryKey(
326 descriptor().address, header.key_length(), item_.key_buffer_.data());
327 }
328
329 return item_;
330}
331
332KeyValueStore::iterator KeyValueStore::begin() const {
333 size_t i = 0;
334 // Skip over any deleted entries at the start of the descriptor list.
335 while (i < key_descriptor_list_size_ && key_descriptor_list_[i].deleted()) {
336 i += 1;
337 }
338 return iterator(*this, i);
339}
340
341// TODO(hepler): The valid entry count could be tracked in the KVS to avoid the
342// need for this for-loop.
343size_t KeyValueStore::size() const {
344 size_t valid_entries = 0;
345
346 for (size_t i = 0; i < key_descriptor_list_size_; ++i) {
347 if (!key_descriptor_list_[i].deleted()) {
348 valid_entries += 1;
349 }
350 }
351
352 return valid_entries;
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800353}
354
Wyatt Heplered163b02020-02-03 17:49:32 -0800355StatusWithSize KeyValueStore::ValueSize(std::string_view key) const {
Wyatt Hepler729f28c2020-02-05 09:46:00 -0800356 TRY(CheckOperation(key));
Wyatt Heplered163b02020-02-03 17:49:32 -0800357
358 const KeyDescriptor* key_descriptor;
359 TRY(FindKeyDescriptor(key, &key_descriptor));
360
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800361 if (key_descriptor->deleted()) {
362 return Status::NOT_FOUND;
363 }
364
Wyatt Heplered163b02020-02-03 17:49:32 -0800365 EntryHeader header;
Wyatt Hepler4d78cd62020-02-05 13:05:58 -0800366 TRY(ReadEntryHeader(key_descriptor->address, &header));
Wyatt Heplered163b02020-02-03 17:49:32 -0800367
368 return StatusWithSize(header.value_length());
369}
370
Wyatt Hepler4d78cd62020-02-05 13:05:58 -0800371uint32_t KeyValueStore::HashKey(string_view string) {
372 uint32_t hash = 0;
373 uint32_t coefficient = 65599u;
374
375 for (char ch : string) {
376 hash += coefficient * unsigned(ch);
377 coefficient *= 65599u;
378 }
379
380 return hash;
381}
382
Wyatt Hepler6e3a83b2020-02-04 07:36:45 -0800383Status KeyValueStore::FixedSizeGet(std::string_view key,
384 byte* value,
385 size_t size_bytes) const {
386 // Ensure that the size of the stored value matches the size of the type.
387 // Otherwise, report error. This check avoids potential memory corruption.
388 StatusWithSize result = ValueSize(key);
389 if (!result.ok()) {
390 return result.status();
Keir Mierle8c352dc2020-02-02 13:58:19 -0800391 }
Wyatt Hepler6e3a83b2020-02-04 07:36:45 -0800392 if (result.size() != size_bytes) {
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800393 DBG("Requested %zu B read, but value is %zu B", size_bytes, result.size());
Wyatt Hepler6e3a83b2020-02-04 07:36:45 -0800394 return Status::INVALID_ARGUMENT;
Wyatt Heplerbab0e202020-02-04 07:40:08 -0800395 }
Wyatt Hepler6e3a83b2020-02-04 07:36:45 -0800396 return Get(key, span(value, size_bytes)).status();
Keir Mierle8c352dc2020-02-02 13:58:19 -0800397}
398
Wyatt Hepler729f28c2020-02-05 09:46:00 -0800399Status KeyValueStore::CheckOperation(string_view key) const {
Wyatt Hepleracaacf92020-01-24 10:58:30 -0800400 if (InvalidKey(key)) {
Wyatt Heplerb7609542020-01-24 10:29:54 -0800401 return Status::INVALID_ARGUMENT;
402 }
Wyatt Hepler729f28c2020-02-05 09:46:00 -0800403 if (!initialized_) {
Wyatt Heplerb7609542020-01-24 10:29:54 -0800404 return Status::FAILED_PRECONDITION;
405 }
Wyatt Heplerb7609542020-01-24 10:29:54 -0800406 return Status::OK;
407}
408
David Rogers2761aeb2020-01-31 17:09:00 -0800409Status KeyValueStore::FindKeyDescriptor(string_view key,
410 const KeyDescriptor** result) const {
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800411 char key_buffer[kMaxKeyLength];
412 const uint32_t hash = HashKey(key);
Wyatt Heplerb7609542020-01-24 10:29:54 -0800413
David Rogers2761aeb2020-01-31 17:09:00 -0800414 for (auto& descriptor : key_descriptors()) {
415 if (descriptor.key_hash == hash) {
Wyatt Hepler4d78cd62020-02-05 13:05:58 -0800416 TRY(ReadEntryKey(descriptor.address, key.size(), key_buffer));
Wyatt Heplerb7609542020-01-24 10:29:54 -0800417
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800418 if (key == string_view(key_buffer, key.size())) {
Wyatt Hepler5a33d8c2020-02-06 09:32:58 -0800419 DBG("Found match for key hash 0x%08" PRIx32, hash);
David Rogers2761aeb2020-01-31 17:09:00 -0800420 *result = &descriptor;
Wyatt Heplerb7609542020-01-24 10:29:54 -0800421 return Status::OK;
422 }
Wyatt Heplerb7609542020-01-24 10:29:54 -0800423 }
424 }
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800425 return Status::NOT_FOUND;
426}
427
Wyatt Hepler4d78cd62020-02-05 13:05:58 -0800428Status KeyValueStore::ReadEntryHeader(Address address,
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800429 EntryHeader* header) const {
Wyatt Hepler4d78cd62020-02-05 13:05:58 -0800430 return partition_.Read(address, sizeof(*header), header).status();
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800431}
432
Wyatt Hepler4d78cd62020-02-05 13:05:58 -0800433Status KeyValueStore::ReadEntryKey(Address address,
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800434 size_t key_length,
435 char* key) const {
436 // TODO: This check probably shouldn't be here; this is like
437 // checking that the Cortex M's RAM isn't corrupt. This should be
438 // done at boot time.
439 // ^^ This argument sometimes comes from EntryHeader::key_value_len,
440 // which is read directly from flash. If it's corrupted, we shouldn't try
441 // to read a bunch of extra data.
442 if (key_length == 0u || key_length > kMaxKeyLength) {
443 return Status::DATA_LOSS;
444 }
445 // The key is immediately after the entry header.
Wyatt Hepler4d78cd62020-02-05 13:05:58 -0800446 return partition_.Read(address + sizeof(EntryHeader), key_length, key)
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800447 .status();
448}
449
David Rogers2761aeb2020-01-31 17:09:00 -0800450StatusWithSize KeyValueStore::ReadEntryValue(
451 const KeyDescriptor& key_descriptor,
452 const EntryHeader& header,
453 span<byte> value) const {
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800454 const size_t read_size = std::min(header.value_length(), value.size());
David Rogers2761aeb2020-01-31 17:09:00 -0800455 StatusWithSize result = partition_.Read(
456 key_descriptor.address + sizeof(header) + header.key_length(),
Keir Mierle8c352dc2020-02-02 13:58:19 -0800457 value.subspan(0, read_size));
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800458 TRY(result);
459 if (read_size != header.value_length()) {
460 return StatusWithSize(Status::RESOURCE_EXHAUSTED, read_size);
461 }
462 return StatusWithSize(read_size);
463}
464
David Rogers2761aeb2020-01-31 17:09:00 -0800465Status KeyValueStore::WriteEntryForExistingKey(KeyDescriptor* key_descriptor,
Wyatt Hepler5a33d8c2020-02-06 09:32:58 -0800466 KeyDescriptor::State new_state,
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800467 string_view key,
468 span<const byte> value) {
Wyatt Hepler5a33d8c2020-02-06 09:32:58 -0800469 // Find the original entry and sector to update the sector's valid_bytes.
470 EntryHeader original_entry;
471 TRY(ReadEntryHeader(key_descriptor->address, &original_entry));
472 SectorDescriptor& old_sector = SectorFromAddress(key_descriptor->address);
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800473
David Rogers2761aeb2020-01-31 17:09:00 -0800474 SectorDescriptor* sector;
Wyatt Hepler97fc7942020-02-06 15:55:45 -0800475 TRY(FindOrRecoverSectorWithSpace(
476 &sector, EntryHeader::size(partition_.alignment_bytes(), key, value)));
Wyatt Hepler5a33d8c2020-02-06 09:32:58 -0800477
David Rogers8ce55cd2020-02-04 19:41:48 -0800478 DBG("Writing existing entry; found sector: %zu", SectorIndex(sector));
Wyatt Hepler5a33d8c2020-02-06 09:32:58 -0800479 TRY(AppendEntry(sector, key_descriptor, key, value, new_state));
480
David Rogers2be76b02020-02-06 17:33:05 -0800481 old_sector.RemoveValidBytes(original_entry.size());
Wyatt Hepler5a33d8c2020-02-06 09:32:58 -0800482 return Status::OK;
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800483}
484
485Status KeyValueStore::WriteEntryForNewKey(string_view key,
486 span<const byte> value) {
David Rogers2761aeb2020-01-31 17:09:00 -0800487 if (KeyListFull()) {
Keir Mierle8c352dc2020-02-02 13:58:19 -0800488 WRN("KVS full: trying to store a new entry, but can't. Have %zu entries",
489 key_descriptor_list_size_);
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800490 return Status::RESOURCE_EXHAUSTED;
491 }
492
David Rogers2761aeb2020-01-31 17:09:00 -0800493 // Modify the key descriptor at the end of the array, without bumping the map
494 // size so the key descriptor is prepared and written without committing
495 // first.
496 KeyDescriptor& key_descriptor =
497 key_descriptor_list_[key_descriptor_list_size_];
498 key_descriptor.key_hash = HashKey(key);
499 key_descriptor.key_version = 0; // will be incremented by AppendEntry()
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800500 key_descriptor.state = KeyDescriptor::kValid;
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800501
David Rogers2761aeb2020-01-31 17:09:00 -0800502 SectorDescriptor* sector;
Wyatt Hepler97fc7942020-02-06 15:55:45 -0800503 TRY(FindOrRecoverSectorWithSpace(
504 &sector, EntryHeader::size(partition_.alignment_bytes(), key, value)));
David Rogers8ce55cd2020-02-04 19:41:48 -0800505 DBG("Writing new entry; found sector: %zu", SectorIndex(sector));
David Rogers2761aeb2020-01-31 17:09:00 -0800506 TRY(AppendEntry(sector, &key_descriptor, key, value));
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800507
Keir Mierle8c352dc2020-02-02 13:58:19 -0800508 // Only increment bump our size when we are certain the write succeeded.
David Rogers2761aeb2020-01-31 17:09:00 -0800509 key_descriptor_list_size_ += 1;
Wyatt Heplerb7609542020-01-24 10:29:54 -0800510 return Status::OK;
511}
512
David Rogers2761aeb2020-01-31 17:09:00 -0800513Status KeyValueStore::RelocateEntry(KeyDescriptor& key_descriptor) {
David Rogersf0a35442020-02-04 12:16:38 -0800514 struct TempEntry {
515 std::array<char, kMaxKeyLength + 1> key;
516 std::array<char, sizeof(working_buffer_) - sizeof(key)> value;
517 };
518 TempEntry* entry = reinterpret_cast<TempEntry*>(working_buffer_.data());
519
David Rogersdf025cd2020-02-06 17:05:34 -0800520 DBG("Relocating entry"); // TODO: add entry info to the log statement.
521
David Rogersf0a35442020-02-04 12:16:38 -0800522 // Read the entry to be relocated. Store the header in a local variable and
523 // store the key and value in the TempEntry stored in the static allocated
524 // working_buffer_.
525 EntryHeader header;
Wyatt Hepler4d78cd62020-02-05 13:05:58 -0800526 TRY(ReadEntryHeader(key_descriptor.address, &header));
527 TRY(ReadEntryKey(
528 key_descriptor.address, header.key_length(), entry->key.data()));
David Rogersf0a35442020-02-04 12:16:38 -0800529 string_view key = string_view(entry->key.data(), header.key_length());
530 StatusWithSize result = ReadEntryValue(
531 key_descriptor, header, as_writable_bytes(span(entry->value)));
532 if (!result.status().ok()) {
533 return Status::INTERNAL;
534 }
535
536 auto value = span(entry->value.data(), result.size());
537
538 TRY(header.VerifyChecksum(
539 entry_header_format_.checksum, key, as_bytes(value)));
540
Wyatt Hepler5a33d8c2020-02-06 09:32:58 -0800541 SectorDescriptor& old_sector = SectorFromAddress(key_descriptor.address);
David Rogersf0a35442020-02-04 12:16:38 -0800542
543 // Find a new sector for the entry and write it to the new location.
David Rogers8ce55cd2020-02-04 19:41:48 -0800544 SectorDescriptor* new_sector;
Wyatt Hepler5a33d8c2020-02-06 09:32:58 -0800545 TRY(FindSectorWithSpace(&new_sector, header.size(), &old_sector, true));
David Rogersdf025cd2020-02-06 17:05:34 -0800546 TRY(AppendEntry(new_sector, &key_descriptor, key, as_bytes(value)));
547
548 // Do the valid bytes accounting for the sector the entry was relocated out
549 // of.
David Rogers2be76b02020-02-06 17:33:05 -0800550 old_sector.RemoveValidBytes(header.size());
David Rogersdf025cd2020-02-06 17:05:34 -0800551
552 return Status::OK;
David Rogersa12786b2020-01-31 16:02:33 -0800553}
554
David Rogers8db5a722020-02-03 18:28:34 -0800555// Find either an existing sector with enough space that is not the sector to
556// skip, or an empty sector. Maintains the invariant that there is always at
557// least 1 empty sector unless set to bypass the rule.
Wyatt Hepler5a33d8c2020-02-06 09:32:58 -0800558Status KeyValueStore::FindSectorWithSpace(
559 SectorDescriptor** found_sector,
560 size_t size,
561 const SectorDescriptor* sector_to_skip,
562 bool bypass_empty_sector_rule) {
David Rogers8ce55cd2020-02-04 19:41:48 -0800563 // The last_new_sector_ is the sector that was last selected as the "new empty
564 // sector" to write to. This last new sector is used as the starting point for
565 // the next "find a new empty sector to write to" operation. By using the last
566 // new sector as the start point we will cycle which empty sector is selected
567 // next, spreading the wear across all the empty sectors and get a wear
568 // leveling benefit, rather than putting more wear on the lower number
569 // sectors.
570 //
571 // Locally use the sector index for ease of iterating through the sectors. For
572 // the persistent storage use SectorDescriptor* rather than sector index
573 // because SectorDescriptor* is the standard way to identify a sector.
574 size_t last_new_sector_index_ = SectorIndex(last_new_sector_);
Wyatt Heplerad0a7932020-02-06 08:20:38 -0800575 size_t start = (last_new_sector_index_ + 1) % sector_map_size_;
David Rogers2761aeb2020-01-31 17:09:00 -0800576 SectorDescriptor* first_empty_sector = nullptr;
David Rogers8db5a722020-02-03 18:28:34 -0800577 bool at_least_two_empty_sectors = bypass_empty_sector_rule;
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800578
David Rogers67f4b6c2020-02-06 16:17:09 -0800579 DBG("Find sector with %zu bytes available", size);
580 if (sector_to_skip != nullptr) {
581 DBG(" Skip sector %zu", SectorIndex(sector_to_skip));
582 }
583 if (bypass_empty_sector_rule) {
584 DBG(" Bypassing empty sector rule");
585 }
586
David Rogers8ce55cd2020-02-04 19:41:48 -0800587 // Look for a partial sector to use with enough space. Immediately use the
588 // first one of those that is found. While scanning for a partial sector, keep
589 // track of the first empty sector and if a second sector was seen.
David Rogers1541d612020-02-06 23:47:02 -0800590 for (size_t j = 0; j < sector_map_size_; j++) {
591 size_t i = (j + start) % sector_map_size_;
David Rogers2761aeb2020-01-31 17:09:00 -0800592 SectorDescriptor& sector = sector_map_[i];
Keir Mierle8c352dc2020-02-02 13:58:19 -0800593
David Rogers8db5a722020-02-03 18:28:34 -0800594 if (sector_to_skip == &sector) {
David Rogers67f4b6c2020-02-06 16:17:09 -0800595 DBG(" Skipping the skip sector %zu", i);
David Rogers8db5a722020-02-03 18:28:34 -0800596 continue;
597 }
598
David Rogers67f4b6c2020-02-06 16:17:09 -0800599 DBG(" Examining sector %zu with %hu bytes available",
600 i,
601 sector.tail_free_bytes);
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800602 if (!SectorEmpty(sector) && sector.HasSpace(size)) {
David Rogers67f4b6c2020-02-06 16:17:09 -0800603 DBG(" Partially occupied sector %zu with enough space; done!", i);
David Rogers8ce55cd2020-02-04 19:41:48 -0800604 *found_sector = &sector;
605 return Status::OK;
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800606 }
607
608 if (SectorEmpty(sector)) {
609 if (first_empty_sector == nullptr) {
610 first_empty_sector = &sector;
611 } else {
612 at_least_two_empty_sectors = true;
Wyatt Hepler2ad60672020-01-21 08:00:16 -0800613 }
Wyatt Heplerb7609542020-01-24 10:29:54 -0800614 }
615 }
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800616
David Rogers8ce55cd2020-02-04 19:41:48 -0800617 // If the scan for a partial sector does not find a suitable sector, use the
618 // first empty sector that was found. Normally it is required to keep 1 empty
619 // sector after the sector found here, but that rule can be bypassed in
620 // special circumstances (such as during garbage collection).
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800621 if (at_least_two_empty_sectors) {
David Rogers67f4b6c2020-02-06 16:17:09 -0800622 DBG(" Found a usable empty sector; returning the first found (%zu)",
David Rogers8ce55cd2020-02-04 19:41:48 -0800623 SectorIndex(first_empty_sector));
624 last_new_sector_ = first_empty_sector;
625 *found_sector = first_empty_sector;
626 return Status::OK;
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800627 }
David Rogers8ce55cd2020-02-04 19:41:48 -0800628
629 // No sector was found.
David Rogers67f4b6c2020-02-06 16:17:09 -0800630 DBG(" Unable to find a usable sector");
David Rogers8ce55cd2020-02-04 19:41:48 -0800631 *found_sector = nullptr;
632 return Status::RESOURCE_EXHAUSTED;
Wyatt Heplerb7609542020-01-24 10:29:54 -0800633}
634
David Rogers2761aeb2020-01-31 17:09:00 -0800635Status KeyValueStore::FindOrRecoverSectorWithSpace(SectorDescriptor** sector,
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800636 size_t size) {
David Rogers8ce55cd2020-02-04 19:41:48 -0800637 Status result = FindSectorWithSpace(sector, size);
638 if (result.ok()) {
639 return result;
Wyatt Heplerb7609542020-01-24 10:29:54 -0800640 }
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800641 if (options_.partial_gc_on_write) {
David Rogers1541d612020-02-06 23:47:02 -0800642 // Garbage collect and then try again to find the best sector.
643 TRY(GarbageCollectOneSector());
644 return FindSectorWithSpace(sector, size);
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800645 }
David Rogers8ce55cd2020-02-04 19:41:48 -0800646 return result;
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800647}
648
David Rogers2761aeb2020-01-31 17:09:00 -0800649KeyValueStore::SectorDescriptor* KeyValueStore::FindSectorToGarbageCollect() {
650 SectorDescriptor* sector_candidate = nullptr;
David Rogersa12786b2020-01-31 16:02:33 -0800651 size_t candidate_bytes = 0;
652
653 // Step 1: Try to find a sectors with stale keys and no valid keys (no
654 // relocation needed). If any such sectors are found, use the sector with the
655 // most reclaimable bytes.
Wyatt Heplerad0a7932020-02-06 08:20:38 -0800656 for (auto& sector : sectors()) {
David Rogersa12786b2020-01-31 16:02:33 -0800657 if ((sector.valid_bytes == 0) &&
658 (RecoverableBytes(sector) > candidate_bytes)) {
659 sector_candidate = &sector;
660 candidate_bytes = RecoverableBytes(sector);
661 }
662 }
663
664 // Step 2: If step 1 yields no sectors, just find the sector with the most
665 // reclaimable bytes.
666 if (sector_candidate == nullptr) {
Wyatt Heplerad0a7932020-02-06 08:20:38 -0800667 for (auto& sector : sectors()) {
David Rogersa12786b2020-01-31 16:02:33 -0800668 if (RecoverableBytes(sector) > candidate_bytes) {
669 sector_candidate = &sector;
670 candidate_bytes = RecoverableBytes(sector);
671 }
672 }
673 }
674
David Rogers67f4b6c2020-02-06 16:17:09 -0800675 DBG("Found sector %zu to Garbage Collect, %zu recoverable bytes",
676 SectorIndex(sector_candidate),
677 RecoverableBytes(*sector_candidate));
David Rogersa12786b2020-01-31 16:02:33 -0800678 return sector_candidate;
679}
680
David Rogers1541d612020-02-06 23:47:02 -0800681Status KeyValueStore::GarbageCollectOneSector() {
David Rogers67f4b6c2020-02-06 16:17:09 -0800682 DBG("Garbage Collect a single sector");
683
David Rogersa12786b2020-01-31 16:02:33 -0800684 // Step 1: Find the sector to garbage collect
David Rogers2761aeb2020-01-31 17:09:00 -0800685 SectorDescriptor* sector_to_gc = FindSectorToGarbageCollect();
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800686
David Rogersa12786b2020-01-31 16:02:33 -0800687 if (sector_to_gc == nullptr) {
688 return Status::RESOURCE_EXHAUSTED;
689 }
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800690
David Rogersa12786b2020-01-31 16:02:33 -0800691 // Step 2: Move any valid entries in the GC sector to other sectors
692 if (sector_to_gc->valid_bytes != 0) {
David Rogers2761aeb2020-01-31 17:09:00 -0800693 for (auto& descriptor : key_descriptors()) {
694 if (AddressInSector(*sector_to_gc, descriptor.address)) {
David Rogers67f4b6c2020-02-06 16:17:09 -0800695 DBG(" Relocate entry");
David Rogers2761aeb2020-01-31 17:09:00 -0800696 TRY(RelocateEntry(descriptor));
David Rogersa12786b2020-01-31 16:02:33 -0800697 }
Wyatt Heplerb7609542020-01-24 10:29:54 -0800698 }
699 }
Wyatt Heplerb7609542020-01-24 10:29:54 -0800700
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800701 if (sector_to_gc->valid_bytes != 0) {
David Rogers67f4b6c2020-02-06 16:17:09 -0800702 ERR(" Failed to relocate valid entries from sector being garbage "
703 "collected, %hu valid bytes remain",
704 sector_to_gc->valid_bytes);
Wyatt Heplerb7609542020-01-24 10:29:54 -0800705 return Status::INTERNAL;
706 }
707
David Rogersa12786b2020-01-31 16:02:33 -0800708 // Step 3: Reinitialize the sector
709 sector_to_gc->tail_free_bytes = 0;
710 TRY(partition_.Erase(SectorBaseAddress(sector_to_gc), 1));
711 sector_to_gc->tail_free_bytes = partition_.sector_size_bytes();
Wyatt Heplerb7609542020-01-24 10:29:54 -0800712
David Rogers67f4b6c2020-02-06 16:17:09 -0800713 DBG(" Garbage Collect complete");
David Rogers50185ad2020-02-07 00:02:46 -0800714 LogSectors();
David Rogersa12786b2020-01-31 16:02:33 -0800715 return Status::OK;
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800716}
717
David Rogers2761aeb2020-01-31 17:09:00 -0800718Status KeyValueStore::AppendEntry(SectorDescriptor* sector,
719 KeyDescriptor* key_descriptor,
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800720 const string_view key,
Wyatt Hepler5a33d8c2020-02-06 09:32:58 -0800721 span<const byte> value,
722 KeyDescriptor::State new_state) {
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800723 // write header, key, and value
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800724 EntryHeader header;
725
Wyatt Hepler5a33d8c2020-02-06 09:32:58 -0800726 if (new_state == KeyDescriptor::kDeleted) {
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800727 header = EntryHeader::Tombstone(entry_header_format_.magic,
728 entry_header_format_.checksum,
729 key,
Wyatt Hepler97fc7942020-02-06 15:55:45 -0800730 partition_.alignment_bytes(),
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800731 key_descriptor->key_version + 1);
732 } else {
733 header = EntryHeader::Valid(entry_header_format_.magic,
734 entry_header_format_.checksum,
735 key,
736 value,
Wyatt Hepler97fc7942020-02-06 15:55:45 -0800737 partition_.alignment_bytes(),
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800738 key_descriptor->key_version + 1);
739 }
740
Wyatt Hepler97fc7942020-02-06 15:55:45 -0800741 DBG("Appending %zu B entry with key version: %x",
742 header.size(),
743 unsigned(header.key_version()));
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800744
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800745 Address address = NextWritableAddress(sector);
Keir Mierle8c352dc2020-02-02 13:58:19 -0800746 DBG("Appending to address: %zx", size_t(address));
Wyatt Hepler5a33d8c2020-02-06 09:32:58 -0800747
748 // Handles writing multiple concatenated buffers, while breaking up the writes
749 // into alignment-sized blocks.
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800750 TRY_ASSIGN(
Wyatt Hepler116d1162020-02-06 09:42:59 -0800751 const size_t written,
752 partition_.WriteAligned(
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800753 address, {as_bytes(span(&header, 1)), as_bytes(span(key)), value}));
754
755 if (options_.verify_on_write) {
Wyatt Hepler0a223582020-02-04 17:47:40 -0800756 TRY(header.VerifyChecksumInFlash(
757 &partition_, address, entry_header_format_.checksum));
Wyatt Heplerb7609542020-01-24 10:29:54 -0800758 }
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800759
David Rogers2761aeb2020-01-31 17:09:00 -0800760 key_descriptor->address = address;
761 key_descriptor->key_version = header.key_version();
Wyatt Hepler5a33d8c2020-02-06 09:32:58 -0800762 key_descriptor->state = new_state;
763
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800764 sector->valid_bytes += written;
David Rogers2be76b02020-02-06 17:33:05 -0800765 sector->RemoveFreeBytes(written);
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800766 return Status::OK;
Wyatt Heplerb7609542020-01-24 10:29:54 -0800767}
768
Keir Mierle8c352dc2020-02-02 13:58:19 -0800769void KeyValueStore::LogDebugInfo() {
Keir Mierle8c352dc2020-02-02 13:58:19 -0800770 const size_t sector_size_bytes = partition_.sector_size_bytes();
771 DBG("====================== KEY VALUE STORE DUMP =========================");
772 DBG(" ");
773 DBG("Flash partition:");
Wyatt Heplerad0a7932020-02-06 08:20:38 -0800774 DBG(" Sector count = %zu", partition_.sector_count());
775 DBG(" Sector max count = %zu", kMaxUsableSectors);
776 DBG(" Sectors in use = %zu", sector_map_size_);
Keir Mierle8c352dc2020-02-02 13:58:19 -0800777 DBG(" Sector size = %zu", sector_size_bytes);
778 DBG(" Total size = %zu", partition_.size_bytes());
779 DBG(" Alignment = %zu", partition_.alignment_bytes());
780 DBG(" ");
781 DBG("Key descriptors:");
782 DBG(" Entry count = %zu", key_descriptor_list_size_);
783 DBG(" Max entry count = %zu", kMaxEntries);
784 DBG(" ");
785 DBG(" # hash version address address (hex)");
786 for (size_t i = 0; i < key_descriptor_list_size_; ++i) {
787 const KeyDescriptor& kd = key_descriptor_list_[i];
788 DBG(" |%3zu: | %8zx |%8zu | %8zu | %8zx",
789 i,
790 size_t(kd.key_hash),
791 size_t(kd.key_version),
792 size_t(kd.address),
793 size_t(kd.address));
794 }
795 DBG(" ");
796
797 DBG("Sector descriptors:");
798 DBG(" # tail free valid has_space");
Wyatt Heplerad0a7932020-02-06 08:20:38 -0800799 for (size_t sector_id = 0; sector_id < sector_map_size_; ++sector_id) {
Keir Mierle8c352dc2020-02-02 13:58:19 -0800800 const SectorDescriptor& sd = sector_map_[sector_id];
801 DBG(" |%3zu: | %8zu |%8zu | %s",
802 sector_id,
803 size_t(sd.tail_free_bytes),
804 size_t(sd.valid_bytes),
805 sd.tail_free_bytes ? "YES" : "");
806 }
807 DBG(" ");
808
809 // TODO: This should stop logging after some threshold.
810 // size_t dumped_bytes = 0;
811 DBG("Sector raw data:");
Wyatt Heplerad0a7932020-02-06 08:20:38 -0800812 for (size_t sector_id = 0; sector_id < sector_map_size_; ++sector_id) {
Keir Mierle8c352dc2020-02-02 13:58:19 -0800813 // Read sector data. Yes, this will blow the stack on embedded.
814 std::array<byte, 500> raw_sector_data; // TODO
815 StatusWithSize sws =
816 partition_.Read(sector_id * sector_size_bytes, raw_sector_data);
817 DBG("Read: %zu bytes", sws.size());
818
819 DBG(" base addr offs 0 1 2 3 4 5 6 7");
820 for (size_t i = 0; i < sector_size_bytes; i += 8) {
821 DBG(" %3zu %8zx %5zu | %02x %02x %02x %02x %02x %02x %02x %02x",
822 sector_id,
823 (sector_id * sector_size_bytes) + i,
824 i,
825 static_cast<unsigned int>(raw_sector_data[i + 0]),
826 static_cast<unsigned int>(raw_sector_data[i + 1]),
827 static_cast<unsigned int>(raw_sector_data[i + 2]),
828 static_cast<unsigned int>(raw_sector_data[i + 3]),
829 static_cast<unsigned int>(raw_sector_data[i + 4]),
830 static_cast<unsigned int>(raw_sector_data[i + 5]),
831 static_cast<unsigned int>(raw_sector_data[i + 6]),
832 static_cast<unsigned int>(raw_sector_data[i + 7]));
833
834 // TODO: Fix exit condition.
835 if (i > 128) {
836 break;
837 }
838 }
839 DBG(" ");
840 }
841
842 DBG("////////////////////// KEY VALUE STORE DUMP END /////////////////////");
843}
844
David Rogers50185ad2020-02-07 00:02:46 -0800845void KeyValueStore::LogSectors(void) {
846 for (auto& sector : sectors()) {
847 DBG(" - Sector %zu: valid %hu, recoverable %zu, free %hu",
848 SectorIndex(&sector),
849 sector.valid_bytes,
850 RecoverableBytes(sector),
851 sector.tail_free_bytes);
852 }
853}
854
Wyatt Hepler2ad60672020-01-21 08:00:16 -0800855} // namespace pw::kvs