blob: 29fa778e4bc78382cde11f950a3d0500ad3bcde0 [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 Heplerd31d9702020-02-14 08:46:36 -080023#include "pw_kvs_private/entry.h"
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -080024#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),
Wyatt Hepler1c329ca2020-02-07 18:07:23 -080038 sectors_(partition_.sector_count()),
39 last_new_sector_(sectors_.data()),
Wyatt Heplerad0a7932020-02-06 08:20:38 -080040 working_buffer_{} {}
41
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -080042Status KeyValueStore::Init() {
Wyatt Hepler1c329ca2020-02-07 18:07:23 -080043 if (kMaxUsableSectors < sectors_.size()) {
Wyatt Heplerad0a7932020-02-06 08:20:38 -080044 CRT("KeyValueStore::kMaxUsableSectors must be at least as large as the "
45 "number of sectors in the flash partition");
46 return Status::FAILED_PRECONDITION;
47 }
48
Wyatt Hepler1c329ca2020-02-07 18:07:23 -080049 if (kMaxUsableSectors > sectors_.size()) {
Wyatt Heplerad0a7932020-02-06 08:20:38 -080050 DBG("KeyValueStore::kMaxUsableSectors is %zu sectors larger than needed",
Wyatt Hepler1c329ca2020-02-07 18:07:23 -080051 kMaxUsableSectors - sectors_.size());
Wyatt Heplerad0a7932020-02-06 08:20:38 -080052 }
53
Keir Mierle8c352dc2020-02-02 13:58:19 -080054 // Reset the number of occupied key descriptors; we will fill them later.
Wyatt Hepler1c329ca2020-02-07 18:07:23 -080055 key_descriptors_.clear();
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -080056
David Rogers8ce55cd2020-02-04 19:41:48 -080057 // TODO: init last_new_sector_ to a random sector. Since the on-flash stored
58 // information does not allow recovering the previous last_new_sector_ after
59 // clean start, random is a good second choice.
60
Keir Mierle8c352dc2020-02-02 13:58:19 -080061 const size_t sector_size_bytes = partition_.sector_size_bytes();
Keir Mierle8c352dc2020-02-02 13:58:19 -080062
David Rogersf0a35442020-02-04 12:16:38 -080063 if (working_buffer_.size() < sector_size_bytes) {
Wyatt Heplere541e072020-02-14 09:10:53 -080064 CRT("working_buffer_ (%zu bytes) is smaller than sector size (%zu bytes)",
David Rogersf0a35442020-02-04 12:16:38 -080065 working_buffer_.size(),
66 sector_size_bytes);
67 return Status::INVALID_ARGUMENT;
68 }
69
Keir Mierle8c352dc2020-02-02 13:58:19 -080070 DBG("First pass: Read all entries from all sectors");
Wyatt Hepler1c329ca2020-02-07 18:07:23 -080071 for (size_t sector_id = 0; sector_id < sectors_.size(); ++sector_id) {
Keir Mierle8c352dc2020-02-02 13:58:19 -080072 // Track writable bytes in this sector. Updated after reading each entry.
Wyatt Hepler1c329ca2020-02-07 18:07:23 -080073 sectors_[sector_id].tail_free_bytes = sector_size_bytes;
Keir Mierle8c352dc2020-02-02 13:58:19 -080074
75 const Address sector_address = sector_id * sector_size_bytes;
76 Address entry_address = sector_address;
77
78 for (int num_entries_in_sector = 0;; num_entries_in_sector++) {
79 DBG("Load entry: sector=%zu, entry#=%d, address=%zu",
80 sector_id,
81 num_entries_in_sector,
82 size_t(entry_address));
83
Wyatt Hepler1c329ca2020-02-07 18:07:23 -080084 if (!AddressInSector(sectors_[sector_id], entry_address)) {
Keir Mierle8c352dc2020-02-02 13:58:19 -080085 DBG("Fell off end of sector; moving to the next sector");
86 break;
87 }
88
89 Address next_entry_address;
90 Status status = LoadEntry(entry_address, &next_entry_address);
91 if (status == Status::NOT_FOUND) {
92 DBG("Hit un-written data in sector; moving to the next sector");
93 break;
94 }
95 if (status == Status::DATA_LOSS) {
96 // It's not clear KVS can make a unilateral decision about what to do
97 // in corruption cases. It's an application decision, for which we
98 // should offer some configurability. For now, entirely bail out of
99 // loading and give up.
100 //
101 // Later, scan for remaining valid keys; since it's entirely possible
102 // that there is a duplicate of the key elsewhere and everything is
103 // fine. Later, we can wipe and maybe recover the sector.
104 //
105 // TODO: Implement rest-of-sector scanning for valid entries.
106 return Status::DATA_LOSS;
107 }
108 TRY(status);
109
110 // Entry loaded successfully; so get ready to load the next one.
111 entry_address = next_entry_address;
112
113 // Update of the number of writable bytes in this sector.
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800114 sectors_[sector_id].tail_free_bytes =
Keir Mierle8c352dc2020-02-02 13:58:19 -0800115 sector_size_bytes - (entry_address - sector_address);
116 }
117 }
118
119 DBG("Second pass: Count valid bytes in each sector");
120 // Initialize the sector sizes.
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800121 for (SectorDescriptor& sector : sectors_) {
122 sector.valid_bytes = 0;
Keir Mierle8c352dc2020-02-02 13:58:19 -0800123 }
124 // For every valid key, increment the valid bytes for that sector.
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800125 for (KeyDescriptor& key_descriptor : key_descriptors_) {
126 uint32_t sector_id = key_descriptor.address / sector_size_bytes;
Wyatt Heplere541e072020-02-14 09:10:53 -0800127 Entry entry;
128 TRY(Entry::Read(partition_, key_descriptor.address, &entry));
129 sectors_[sector_id].valid_bytes += entry.size();
Keir Mierle8c352dc2020-02-02 13:58:19 -0800130 }
Wyatt Hepler729f28c2020-02-05 09:46:00 -0800131 initialized_ = true;
Keir Mierle8c352dc2020-02-02 13:58:19 -0800132 return Status::OK;
133}
134
135Status KeyValueStore::LoadEntry(Address entry_address,
136 Address* next_entry_address) {
Wyatt Heplere541e072020-02-14 09:10:53 -0800137 Entry entry;
138 TRY(Entry::Read(partition_, entry_address, &entry));
Keir Mierle8c352dc2020-02-02 13:58:19 -0800139
140 // TODO: Handle multiple magics for formats that have changed.
Wyatt Heplere541e072020-02-14 09:10:53 -0800141 if (entry.magic() != entry_header_format_.magic) {
Keir Mierle8c352dc2020-02-02 13:58:19 -0800142 // TODO: It may be cleaner to have some logging helpers for these cases.
Wyatt Heplere541e072020-02-14 09:10:53 -0800143 ERR("Found corrupt magic: %zx; expecting %zx; at address %zx",
144 size_t(entry.magic()),
Keir Mierle8c352dc2020-02-02 13:58:19 -0800145 size_t(entry_header_format_.magic),
146 size_t(entry_address));
147 return Status::DATA_LOSS;
148 }
149
150 // Read the key from flash & validate the entry (which reads the value).
151 KeyBuffer key_buffer;
Wyatt Heplere541e072020-02-14 09:10:53 -0800152 TRY_ASSIGN(size_t key_length, entry.ReadKey(key_buffer));
153 const string_view key(key_buffer.data(), key_length);
Wyatt Heplerbab0e202020-02-04 07:40:08 -0800154
Wyatt Heplere541e072020-02-14 09:10:53 -0800155 TRY(entry.VerifyChecksumInFlash(entry_header_format_.checksum));
Wyatt Hepler4d78cd62020-02-05 13:05:58 -0800156
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800157 KeyDescriptor key_descriptor(
158 key,
Wyatt Heplere541e072020-02-14 09:10:53 -0800159 entry.key_version(),
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800160 entry_address,
Wyatt Heplere541e072020-02-14 09:10:53 -0800161 entry.deleted() ? KeyDescriptor::kDeleted : KeyDescriptor::kValid);
Keir Mierle8c352dc2020-02-02 13:58:19 -0800162
163 DBG("Key hash: %zx (%zu)",
164 size_t(key_descriptor.key_hash),
165 size_t(key_descriptor.key_hash));
166
167 TRY(AppendNewOrOverwriteStaleExistingDescriptor(key_descriptor));
168
Wyatt Heplere541e072020-02-14 09:10:53 -0800169 *next_entry_address = entry.next_address();
Keir Mierle8c352dc2020-02-02 13:58:19 -0800170 return Status::OK;
171}
172
173// TODO: This method is the trigger of the O(valid_entries * all_entries) time
174// complexity for reading. At some cost to memory, this could be optimized by
175// using a hash table instead of scanning, but in practice this should be fine
176// for a small number of keys
177Status KeyValueStore::AppendNewOrOverwriteStaleExistingDescriptor(
178 const KeyDescriptor& key_descriptor) {
179 // With the new key descriptor, either add it to the descriptor table or
180 // overwrite an existing entry with an older version of the key.
181 KeyDescriptor* existing_descriptor = FindDescriptor(key_descriptor.key_hash);
182 if (existing_descriptor) {
183 if (existing_descriptor->key_version < key_descriptor.key_version) {
184 // Existing entry is old; replace the existing entry with the new one.
185 *existing_descriptor = key_descriptor;
186 } else {
187 // Otherwise, check for data integrity and leave the existing entry.
188 if (existing_descriptor->key_version == key_descriptor.key_version) {
189 ERR("Data loss: Duplicated old(=%zu) and new(=%zu) version",
190 size_t(existing_descriptor->key_version),
191 size_t(key_descriptor.key_version));
192 return Status::DATA_LOSS;
193 }
194 DBG("Found stale entry when appending; ignoring");
195 }
196 return Status::OK;
197 }
198 // Write new entry.
199 KeyDescriptor* newly_allocated_key_descriptor;
200 TRY(AppendEmptyDescriptor(&newly_allocated_key_descriptor));
201 *newly_allocated_key_descriptor = key_descriptor;
202 return Status::OK;
203}
204
205// TODO: Need a better name.
206Status KeyValueStore::AppendEmptyDescriptor(KeyDescriptor** new_descriptor) {
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800207 if (key_descriptors_.full()) {
Keir Mierle8c352dc2020-02-02 13:58:19 -0800208 return Status::RESOURCE_EXHAUSTED;
209 }
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800210 key_descriptors_.emplace_back();
211 *new_descriptor = &key_descriptors_.back();
Keir Mierle8c352dc2020-02-02 13:58:19 -0800212 return Status::OK;
213}
214
Keir Mierle8c352dc2020-02-02 13:58:19 -0800215KeyValueStore::KeyDescriptor* KeyValueStore::FindDescriptor(uint32_t hash) {
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800216 for (KeyDescriptor& key_descriptor : key_descriptors_) {
217 if (key_descriptor.key_hash == hash) {
218 return &key_descriptor;
Keir Mierle8c352dc2020-02-02 13:58:19 -0800219 }
220 }
221 return nullptr;
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800222}
223
224StatusWithSize KeyValueStore::Get(string_view key,
225 span<byte> value_buffer) const {
Wyatt Hepler50f70772020-02-13 11:25:10 -0800226 TRY_WITH_SIZE(CheckOperation(key));
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800227
David Rogers2761aeb2020-01-31 17:09:00 -0800228 const KeyDescriptor* key_descriptor;
Wyatt Hepler2d401692020-02-13 16:01:23 -0800229 TRY_WITH_SIZE(FindExistingKeyDescriptor(key, &key_descriptor));
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800230
Wyatt Heplere541e072020-02-14 09:10:53 -0800231 Entry entry;
232 TRY_WITH_SIZE(Entry::Read(partition_, key_descriptor->address, &entry));
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800233
Wyatt Heplere541e072020-02-14 09:10:53 -0800234 StatusWithSize result = entry.ReadValue(value_buffer);
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800235 if (result.ok() && options_.verify_on_read) {
David Rogerscf680ab2020-02-12 23:28:32 -0800236 Status verify_result =
Wyatt Heplere541e072020-02-14 09:10:53 -0800237 entry.VerifyChecksum(entry_header_format_.checksum,
238 key,
239 value_buffer.subspan(0, result.size()));
David Rogerscf680ab2020-02-12 23:28:32 -0800240 if (!verify_result.ok()) {
Wyatt Hepler50f70772020-02-13 11:25:10 -0800241 std::memset(
242 value_buffer.subspan(0, result.size()).data(), 0, result.size());
243 return StatusWithSize(verify_result);
David Rogerscf680ab2020-02-12 23:28:32 -0800244 }
245
246 return StatusWithSize(verify_result, result.size());
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800247 }
248 return result;
249}
250
251Status KeyValueStore::Put(string_view key, span<const byte> value) {
Keir Mierle8c352dc2020-02-02 13:58:19 -0800252 DBG("Writing key/value; key length=%zu, value length=%zu",
253 key.size(),
254 value.size());
Wyatt Hepler729f28c2020-02-05 09:46:00 -0800255
256 TRY(CheckOperation(key));
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800257
258 if (value.size() > (1 << 24)) {
259 // TODO: Reject sizes that are larger than the maximum?
260 }
261
David Rogers2761aeb2020-01-31 17:09:00 -0800262 KeyDescriptor* key_descriptor;
Wyatt Hepler2d401692020-02-13 16:01:23 -0800263 Status status = FindKeyDescriptor(key, &key_descriptor);
264
265 if (status.ok()) {
David Rogers3464d0a2020-02-07 11:45:46 -0800266 DBG("Writing over existing entry for key 0x%08" PRIx32 " in sector %zu",
267 key_descriptor->key_hash,
268 SectorIndex(SectorFromAddress(key_descriptor->address)));
Wyatt Hepler5a33d8c2020-02-06 09:32:58 -0800269 return WriteEntryForExistingKey(
270 key_descriptor, KeyDescriptor::kValid, key, value);
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800271 }
David Rogers2761aeb2020-01-31 17:09:00 -0800272
Wyatt Hepler2d401692020-02-13 16:01:23 -0800273 if (status == Status::NOT_FOUND) {
274 return WriteEntryForNewKey(key, value);
275 }
276
277 return status;
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800278}
279
280Status KeyValueStore::Delete(string_view key) {
Wyatt Hepler729f28c2020-02-05 09:46:00 -0800281 TRY(CheckOperation(key));
282
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800283 KeyDescriptor* key_descriptor;
Wyatt Hepler2d401692020-02-13 16:01:23 -0800284 TRY(FindExistingKeyDescriptor(key, &key_descriptor));
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800285
David Rogers3464d0a2020-02-07 11:45:46 -0800286 DBG("Writing tombstone for existing key 0x%08" PRIx32 " in sector %zu",
287 key_descriptor->key_hash,
288 SectorIndex(SectorFromAddress(key_descriptor->address)));
Wyatt Hepler5a33d8c2020-02-06 09:32:58 -0800289 return WriteEntryForExistingKey(
290 key_descriptor, KeyDescriptor::kDeleted, key, {});
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800291}
292
293KeyValueStore::iterator& KeyValueStore::iterator::operator++() {
294 // Skip to the next entry that is valid (not deleted).
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800295 while (++index_ < item_.kvs_.key_descriptors_.size() &&
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800296 descriptor().deleted()) {
297 }
298 return *this;
299}
300
301const KeyValueStore::Item& KeyValueStore::iterator::operator*() {
302 std::memset(item_.key_buffer_.data(), 0, item_.key_buffer_.size());
303
Wyatt Heplere541e072020-02-14 09:10:53 -0800304 Entry entry;
305 if (Entry::Read(item_.kvs_.partition_, descriptor().address, &entry).ok()) {
306 entry.ReadKey(item_.key_buffer_);
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800307 }
308
309 return item_;
310}
311
312KeyValueStore::iterator KeyValueStore::begin() const {
313 size_t i = 0;
314 // Skip over any deleted entries at the start of the descriptor list.
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800315 while (i < key_descriptors_.size() && key_descriptors_[i].deleted()) {
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800316 i += 1;
317 }
318 return iterator(*this, i);
319}
320
321// TODO(hepler): The valid entry count could be tracked in the KVS to avoid the
322// need for this for-loop.
323size_t KeyValueStore::size() const {
324 size_t valid_entries = 0;
325
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800326 for (const KeyDescriptor& key_descriptor : key_descriptors_) {
327 if (!key_descriptor.deleted()) {
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800328 valid_entries += 1;
329 }
330 }
331
332 return valid_entries;
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800333}
334
Wyatt Heplered163b02020-02-03 17:49:32 -0800335StatusWithSize KeyValueStore::ValueSize(std::string_view key) const {
Wyatt Hepler50f70772020-02-13 11:25:10 -0800336 TRY_WITH_SIZE(CheckOperation(key));
Wyatt Heplered163b02020-02-03 17:49:32 -0800337
338 const KeyDescriptor* key_descriptor;
Wyatt Hepler2d401692020-02-13 16:01:23 -0800339 TRY_WITH_SIZE(FindExistingKeyDescriptor(key, &key_descriptor));
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800340
Wyatt Heplere541e072020-02-14 09:10:53 -0800341 Entry entry;
342 TRY_WITH_SIZE(Entry::Read(partition_, key_descriptor->address, &entry));
Wyatt Heplered163b02020-02-03 17:49:32 -0800343
Wyatt Heplere541e072020-02-14 09:10:53 -0800344 return StatusWithSize(entry.value_size());
Wyatt Heplered163b02020-02-03 17:49:32 -0800345}
346
Wyatt Hepler4d78cd62020-02-05 13:05:58 -0800347uint32_t KeyValueStore::HashKey(string_view string) {
348 uint32_t hash = 0;
349 uint32_t coefficient = 65599u;
350
351 for (char ch : string) {
352 hash += coefficient * unsigned(ch);
353 coefficient *= 65599u;
354 }
355
356 return hash;
357}
358
Wyatt Hepler6e3a83b2020-02-04 07:36:45 -0800359Status KeyValueStore::FixedSizeGet(std::string_view key,
360 byte* value,
361 size_t size_bytes) const {
362 // Ensure that the size of the stored value matches the size of the type.
363 // Otherwise, report error. This check avoids potential memory corruption.
364 StatusWithSize result = ValueSize(key);
365 if (!result.ok()) {
366 return result.status();
Keir Mierle8c352dc2020-02-02 13:58:19 -0800367 }
Wyatt Hepler6e3a83b2020-02-04 07:36:45 -0800368 if (result.size() != size_bytes) {
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800369 DBG("Requested %zu B read, but value is %zu B", size_bytes, result.size());
Wyatt Hepler6e3a83b2020-02-04 07:36:45 -0800370 return Status::INVALID_ARGUMENT;
Wyatt Heplerbab0e202020-02-04 07:40:08 -0800371 }
Wyatt Hepler6e3a83b2020-02-04 07:36:45 -0800372 return Get(key, span(value, size_bytes)).status();
Keir Mierle8c352dc2020-02-02 13:58:19 -0800373}
374
Wyatt Hepler729f28c2020-02-05 09:46:00 -0800375Status KeyValueStore::CheckOperation(string_view key) const {
Wyatt Hepleracaacf92020-01-24 10:58:30 -0800376 if (InvalidKey(key)) {
Wyatt Heplerb7609542020-01-24 10:29:54 -0800377 return Status::INVALID_ARGUMENT;
378 }
Wyatt Hepler729f28c2020-02-05 09:46:00 -0800379 if (!initialized_) {
Wyatt Heplerb7609542020-01-24 10:29:54 -0800380 return Status::FAILED_PRECONDITION;
381 }
Wyatt Heplerb7609542020-01-24 10:29:54 -0800382 return Status::OK;
383}
384
Wyatt Hepler2d401692020-02-13 16:01:23 -0800385// Searches for a KeyDescriptor that matches this key and sets *result to point
386// to it if one is found.
387//
388// OK: there is a matching descriptor and *result is set
389// NOT_FOUND: there is no descriptor that matches this key, but this key
390// has a unique hash (and could potentially be added to the KVS)
391// ALREADY_EXISTS: there is no descriptor that matches this key, but the
392// key's hash collides with the hash for an existing descriptor
393//
David Rogers2761aeb2020-01-31 17:09:00 -0800394Status KeyValueStore::FindKeyDescriptor(string_view key,
395 const KeyDescriptor** result) const {
Wyatt Heplere541e072020-02-14 09:10:53 -0800396 Entry::KeyBuffer key_buffer;
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800397 const uint32_t hash = HashKey(key);
Wyatt Heplerb7609542020-01-24 10:29:54 -0800398
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800399 for (auto& descriptor : key_descriptors_) {
David Rogers2761aeb2020-01-31 17:09:00 -0800400 if (descriptor.key_hash == hash) {
Wyatt Heplere541e072020-02-14 09:10:53 -0800401 TRY(Entry::ReadKey(
402 partition_, descriptor.address, key.size(), key_buffer));
Wyatt Heplerb7609542020-01-24 10:29:54 -0800403
Wyatt Heplere541e072020-02-14 09:10:53 -0800404 if (key == string_view(key_buffer.data(), key.size())) {
Wyatt Hepler5a33d8c2020-02-06 09:32:58 -0800405 DBG("Found match for key hash 0x%08" PRIx32, hash);
David Rogers2761aeb2020-01-31 17:09:00 -0800406 *result = &descriptor;
Wyatt Heplerb7609542020-01-24 10:29:54 -0800407 return Status::OK;
Wyatt Hepler2d401692020-02-13 16:01:23 -0800408 } else {
409 WRN("Found key hash collision for 0x%08" PRIx32, hash);
410 return Status::ALREADY_EXISTS;
Wyatt Heplerb7609542020-01-24 10:29:54 -0800411 }
Wyatt Heplerb7609542020-01-24 10:29:54 -0800412 }
413 }
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800414 return Status::NOT_FOUND;
415}
416
Wyatt Hepler2d401692020-02-13 16:01:23 -0800417// Searches for a KeyDescriptor that matches this key and sets *result to point
418// to it if one is found.
419//
420// OK: there is a matching descriptor and *result is set
421// NOT_FOUND: there is no descriptor that matches this key
422//
423Status KeyValueStore::FindExistingKeyDescriptor(
424 string_view key, const KeyDescriptor** result) const {
425 Status status = FindKeyDescriptor(key, result);
426
427 // If the key's hash collides with an existing key or if the key is deleted,
428 // treat it as if it is not in the KVS.
429 if (status == Status::ALREADY_EXISTS ||
430 (status.ok() && (*result)->deleted())) {
431 return Status::NOT_FOUND;
432 }
433 return status;
434}
435
David Rogers2761aeb2020-01-31 17:09:00 -0800436Status KeyValueStore::WriteEntryForExistingKey(KeyDescriptor* key_descriptor,
Wyatt Hepler5a33d8c2020-02-06 09:32:58 -0800437 KeyDescriptor::State new_state,
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800438 string_view key,
439 span<const byte> value) {
Wyatt Hepler5a33d8c2020-02-06 09:32:58 -0800440 // Find the original entry and sector to update the sector's valid_bytes.
Wyatt Hepler30a52152020-02-12 11:26:05 -0800441 Entry original_entry;
Wyatt Heplere541e072020-02-14 09:10:53 -0800442 TRY(Entry::Read(partition_, key_descriptor->address, &original_entry));
David Rogers3464d0a2020-02-07 11:45:46 -0800443 SectorDescriptor* old_sector = SectorFromAddress(key_descriptor->address);
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800444
David Rogers2761aeb2020-01-31 17:09:00 -0800445 SectorDescriptor* sector;
Wyatt Hepler97fc7942020-02-06 15:55:45 -0800446 TRY(FindOrRecoverSectorWithSpace(
Wyatt Hepler30a52152020-02-12 11:26:05 -0800447 &sector, Entry::size(partition_.alignment_bytes(), key, value)));
David Rogers8ce55cd2020-02-04 19:41:48 -0800448 DBG("Writing existing entry; found sector: %zu", SectorIndex(sector));
David Rogers3464d0a2020-02-07 11:45:46 -0800449
450 if (old_sector != SectorFromAddress(key_descriptor->address)) {
451 DBG("Sector for old entry (size %zu) was garbage collected. Old entry "
452 "relocated to sector %zu",
453 original_entry.size(),
454 SectorIndex(SectorFromAddress(key_descriptor->address)));
455
456 old_sector = SectorFromAddress(key_descriptor->address);
457 }
458
Wyatt Hepler5a33d8c2020-02-06 09:32:58 -0800459 TRY(AppendEntry(sector, key_descriptor, key, value, new_state));
460
David Rogers3464d0a2020-02-07 11:45:46 -0800461 old_sector->RemoveValidBytes(original_entry.size());
Wyatt Hepler5a33d8c2020-02-06 09:32:58 -0800462 return Status::OK;
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800463}
464
465Status KeyValueStore::WriteEntryForNewKey(string_view key,
466 span<const byte> value) {
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800467 if (key_descriptors_.full()) {
Keir Mierle8c352dc2020-02-02 13:58:19 -0800468 WRN("KVS full: trying to store a new entry, but can't. Have %zu entries",
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800469 key_descriptors_.size());
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800470 return Status::RESOURCE_EXHAUSTED;
471 }
472
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800473 // Create the KeyDescriptor that will be added to the list. The version and
474 // address will be set by AppendEntry.
475 KeyDescriptor key_descriptor(key, 0, 0);
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800476
David Rogers2761aeb2020-01-31 17:09:00 -0800477 SectorDescriptor* sector;
Wyatt Hepler97fc7942020-02-06 15:55:45 -0800478 TRY(FindOrRecoverSectorWithSpace(
Wyatt Hepler30a52152020-02-12 11:26:05 -0800479 &sector, Entry::size(partition_.alignment_bytes(), key, value)));
David Rogers8ce55cd2020-02-04 19:41:48 -0800480 DBG("Writing new entry; found sector: %zu", SectorIndex(sector));
Wyatt Hepler0af6ad92020-02-13 15:54:46 -0800481 TRY(AppendEntry(sector, &key_descriptor, key, value, KeyDescriptor::kValid));
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800482
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800483 // Only add the entry when we are certain the write succeeded.
484 key_descriptors_.push_back(key_descriptor);
Wyatt Heplerb7609542020-01-24 10:29:54 -0800485 return Status::OK;
486}
487
David Rogers2761aeb2020-01-31 17:09:00 -0800488Status KeyValueStore::RelocateEntry(KeyDescriptor& key_descriptor) {
David Rogersf0a35442020-02-04 12:16:38 -0800489 struct TempEntry {
Wyatt Heplere541e072020-02-14 09:10:53 -0800490 Entry::KeyBuffer key;
David Rogersf0a35442020-02-04 12:16:38 -0800491 std::array<char, sizeof(working_buffer_) - sizeof(key)> value;
492 };
Wyatt Heplere541e072020-02-14 09:10:53 -0800493 TempEntry* temp_entry = reinterpret_cast<TempEntry*>(working_buffer_.data());
David Rogersf0a35442020-02-04 12:16:38 -0800494
David Rogersdf025cd2020-02-06 17:05:34 -0800495 DBG("Relocating entry"); // TODO: add entry info to the log statement.
496
Wyatt Heplere541e072020-02-14 09:10:53 -0800497 // Read the entry to be relocated. Store the entry in a local variable and
David Rogersf0a35442020-02-04 12:16:38 -0800498 // store the key and value in the TempEntry stored in the static allocated
499 // working_buffer_.
Wyatt Heplere541e072020-02-14 09:10:53 -0800500 Entry entry;
501 TRY(Entry::Read(partition_, key_descriptor.address, &entry));
502 TRY_ASSIGN(size_t key_length, entry.ReadKey(temp_entry->key));
503 string_view key = string_view(temp_entry->key.data(), key_length);
504 auto result = entry.ReadValue(as_writable_bytes(span(temp_entry->value)));
David Rogersf0a35442020-02-04 12:16:38 -0800505 if (!result.status().ok()) {
506 return Status::INTERNAL;
507 }
508
Wyatt Heplere541e072020-02-14 09:10:53 -0800509 auto value = span(temp_entry->value.data(), result.size());
510 TRY(entry.VerifyChecksum(
David Rogersf0a35442020-02-04 12:16:38 -0800511 entry_header_format_.checksum, key, as_bytes(value)));
512
David Rogers3464d0a2020-02-07 11:45:46 -0800513 SectorDescriptor* old_sector = SectorFromAddress(key_descriptor.address);
David Rogersf0a35442020-02-04 12:16:38 -0800514
515 // Find a new sector for the entry and write it to the new location.
David Rogers8ce55cd2020-02-04 19:41:48 -0800516 SectorDescriptor* new_sector;
Wyatt Heplere541e072020-02-14 09:10:53 -0800517 TRY(FindSectorWithSpace(&new_sector, entry.size(), old_sector, true));
Wyatt Hepler0af6ad92020-02-13 15:54:46 -0800518 TRY(AppendEntry(
519 new_sector, &key_descriptor, key, as_bytes(value), key_descriptor.state));
David Rogersdf025cd2020-02-06 17:05:34 -0800520
521 // Do the valid bytes accounting for the sector the entry was relocated out
522 // of.
Wyatt Heplere541e072020-02-14 09:10:53 -0800523 old_sector->RemoveValidBytes(entry.size());
David Rogersdf025cd2020-02-06 17:05:34 -0800524
525 return Status::OK;
David Rogersa12786b2020-01-31 16:02:33 -0800526}
527
David Rogers8db5a722020-02-03 18:28:34 -0800528// Find either an existing sector with enough space that is not the sector to
529// skip, or an empty sector. Maintains the invariant that there is always at
530// least 1 empty sector unless set to bypass the rule.
Wyatt Hepler5a33d8c2020-02-06 09:32:58 -0800531Status KeyValueStore::FindSectorWithSpace(
532 SectorDescriptor** found_sector,
533 size_t size,
534 const SectorDescriptor* sector_to_skip,
535 bool bypass_empty_sector_rule) {
David Rogers8ce55cd2020-02-04 19:41:48 -0800536 // The last_new_sector_ is the sector that was last selected as the "new empty
537 // sector" to write to. This last new sector is used as the starting point for
538 // the next "find a new empty sector to write to" operation. By using the last
539 // new sector as the start point we will cycle which empty sector is selected
540 // next, spreading the wear across all the empty sectors and get a wear
541 // leveling benefit, rather than putting more wear on the lower number
542 // sectors.
543 //
544 // Locally use the sector index for ease of iterating through the sectors. For
545 // the persistent storage use SectorDescriptor* rather than sector index
546 // because SectorDescriptor* is the standard way to identify a sector.
547 size_t last_new_sector_index_ = SectorIndex(last_new_sector_);
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800548 size_t start = (last_new_sector_index_ + 1) % sectors_.size();
David Rogers2761aeb2020-01-31 17:09:00 -0800549 SectorDescriptor* first_empty_sector = nullptr;
David Rogers8db5a722020-02-03 18:28:34 -0800550 bool at_least_two_empty_sectors = bypass_empty_sector_rule;
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800551
David Rogers67f4b6c2020-02-06 16:17:09 -0800552 DBG("Find sector with %zu bytes available", size);
553 if (sector_to_skip != nullptr) {
554 DBG(" Skip sector %zu", SectorIndex(sector_to_skip));
555 }
556 if (bypass_empty_sector_rule) {
557 DBG(" Bypassing empty sector rule");
558 }
559
David Rogers8ce55cd2020-02-04 19:41:48 -0800560 // Look for a partial sector to use with enough space. Immediately use the
561 // first one of those that is found. While scanning for a partial sector, keep
562 // track of the first empty sector and if a second sector was seen.
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800563 for (size_t j = 0; j < sectors_.size(); j++) {
564 size_t i = (j + start) % sectors_.size();
565 SectorDescriptor& sector = sectors_[i];
Keir Mierle8c352dc2020-02-02 13:58:19 -0800566
David Rogers8db5a722020-02-03 18:28:34 -0800567 if (sector_to_skip == &sector) {
David Rogers67f4b6c2020-02-06 16:17:09 -0800568 DBG(" Skipping the skip sector %zu", i);
David Rogers8db5a722020-02-03 18:28:34 -0800569 continue;
570 }
571
David Rogers67f4b6c2020-02-06 16:17:09 -0800572 DBG(" Examining sector %zu with %hu bytes available",
573 i,
574 sector.tail_free_bytes);
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800575 if (!SectorEmpty(sector) && sector.HasSpace(size)) {
David Rogers67f4b6c2020-02-06 16:17:09 -0800576 DBG(" Partially occupied sector %zu with enough space; done!", i);
David Rogers8ce55cd2020-02-04 19:41:48 -0800577 *found_sector = &sector;
578 return Status::OK;
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800579 }
580
581 if (SectorEmpty(sector)) {
582 if (first_empty_sector == nullptr) {
583 first_empty_sector = &sector;
584 } else {
585 at_least_two_empty_sectors = true;
Wyatt Hepler2ad60672020-01-21 08:00:16 -0800586 }
Wyatt Heplerb7609542020-01-24 10:29:54 -0800587 }
588 }
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800589
David Rogers8ce55cd2020-02-04 19:41:48 -0800590 // If the scan for a partial sector does not find a suitable sector, use the
591 // first empty sector that was found. Normally it is required to keep 1 empty
592 // sector after the sector found here, but that rule can be bypassed in
593 // special circumstances (such as during garbage collection).
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800594 if (at_least_two_empty_sectors) {
David Rogers67f4b6c2020-02-06 16:17:09 -0800595 DBG(" Found a usable empty sector; returning the first found (%zu)",
David Rogers8ce55cd2020-02-04 19:41:48 -0800596 SectorIndex(first_empty_sector));
597 last_new_sector_ = first_empty_sector;
598 *found_sector = first_empty_sector;
599 return Status::OK;
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800600 }
David Rogers8ce55cd2020-02-04 19:41:48 -0800601
602 // No sector was found.
David Rogers67f4b6c2020-02-06 16:17:09 -0800603 DBG(" Unable to find a usable sector");
David Rogers8ce55cd2020-02-04 19:41:48 -0800604 *found_sector = nullptr;
605 return Status::RESOURCE_EXHAUSTED;
Wyatt Heplerb7609542020-01-24 10:29:54 -0800606}
607
David Rogers2761aeb2020-01-31 17:09:00 -0800608Status KeyValueStore::FindOrRecoverSectorWithSpace(SectorDescriptor** sector,
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800609 size_t size) {
David Rogers8ce55cd2020-02-04 19:41:48 -0800610 Status result = FindSectorWithSpace(sector, size);
Wyatt Hepler2d401692020-02-13 16:01:23 -0800611 if (result == Status::RESOURCE_EXHAUSTED && options_.partial_gc_on_write) {
David Rogers1541d612020-02-06 23:47:02 -0800612 // Garbage collect and then try again to find the best sector.
613 TRY(GarbageCollectOneSector());
614 return FindSectorWithSpace(sector, size);
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800615 }
David Rogers8ce55cd2020-02-04 19:41:48 -0800616 return result;
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800617}
618
David Rogers2761aeb2020-01-31 17:09:00 -0800619KeyValueStore::SectorDescriptor* KeyValueStore::FindSectorToGarbageCollect() {
620 SectorDescriptor* sector_candidate = nullptr;
David Rogersa12786b2020-01-31 16:02:33 -0800621 size_t candidate_bytes = 0;
622
623 // Step 1: Try to find a sectors with stale keys and no valid keys (no
624 // relocation needed). If any such sectors are found, use the sector with the
625 // most reclaimable bytes.
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800626 for (auto& sector : sectors_) {
David Rogersa12786b2020-01-31 16:02:33 -0800627 if ((sector.valid_bytes == 0) &&
628 (RecoverableBytes(sector) > candidate_bytes)) {
629 sector_candidate = &sector;
630 candidate_bytes = RecoverableBytes(sector);
631 }
632 }
633
634 // Step 2: If step 1 yields no sectors, just find the sector with the most
635 // reclaimable bytes.
636 if (sector_candidate == nullptr) {
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800637 for (auto& sector : sectors_) {
David Rogersa12786b2020-01-31 16:02:33 -0800638 if (RecoverableBytes(sector) > candidate_bytes) {
639 sector_candidate = &sector;
640 candidate_bytes = RecoverableBytes(sector);
641 }
642 }
643 }
644
David Rogers5981f312020-02-13 13:33:56 -0800645 if (sector_candidate != nullptr) {
646 DBG("Found sector %zu to Garbage Collect, %zu recoverable bytes",
647 SectorIndex(sector_candidate),
648 RecoverableBytes(*sector_candidate));
649 } else {
650 DBG("Unable to find sector to garbage collect!");
651 }
David Rogersa12786b2020-01-31 16:02:33 -0800652 return sector_candidate;
653}
654
David Rogers1541d612020-02-06 23:47:02 -0800655Status KeyValueStore::GarbageCollectOneSector() {
David Rogers67f4b6c2020-02-06 16:17:09 -0800656 DBG("Garbage Collect a single sector");
657
David Rogersa12786b2020-01-31 16:02:33 -0800658 // Step 1: Find the sector to garbage collect
David Rogers2761aeb2020-01-31 17:09:00 -0800659 SectorDescriptor* sector_to_gc = FindSectorToGarbageCollect();
David Rogers3464d0a2020-02-07 11:45:46 -0800660 LogSectors();
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800661
David Rogersa12786b2020-01-31 16:02:33 -0800662 if (sector_to_gc == nullptr) {
663 return Status::RESOURCE_EXHAUSTED;
664 }
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800665
David Rogersa12786b2020-01-31 16:02:33 -0800666 // Step 2: Move any valid entries in the GC sector to other sectors
667 if (sector_to_gc->valid_bytes != 0) {
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800668 for (auto& descriptor : key_descriptors_) {
David Rogers2761aeb2020-01-31 17:09:00 -0800669 if (AddressInSector(*sector_to_gc, descriptor.address)) {
David Rogers67f4b6c2020-02-06 16:17:09 -0800670 DBG(" Relocate entry");
David Rogers2761aeb2020-01-31 17:09:00 -0800671 TRY(RelocateEntry(descriptor));
David Rogersa12786b2020-01-31 16:02:33 -0800672 }
Wyatt Heplerb7609542020-01-24 10:29:54 -0800673 }
674 }
Wyatt Heplerb7609542020-01-24 10:29:54 -0800675
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800676 if (sector_to_gc->valid_bytes != 0) {
David Rogers67f4b6c2020-02-06 16:17:09 -0800677 ERR(" Failed to relocate valid entries from sector being garbage "
678 "collected, %hu valid bytes remain",
679 sector_to_gc->valid_bytes);
Wyatt Heplerb7609542020-01-24 10:29:54 -0800680 return Status::INTERNAL;
681 }
682
David Rogersa12786b2020-01-31 16:02:33 -0800683 // Step 3: Reinitialize the sector
684 sector_to_gc->tail_free_bytes = 0;
685 TRY(partition_.Erase(SectorBaseAddress(sector_to_gc), 1));
686 sector_to_gc->tail_free_bytes = partition_.sector_size_bytes();
Wyatt Heplerb7609542020-01-24 10:29:54 -0800687
David Rogers67f4b6c2020-02-06 16:17:09 -0800688 DBG(" Garbage Collect complete");
David Rogers50185ad2020-02-07 00:02:46 -0800689 LogSectors();
David Rogersa12786b2020-01-31 16:02:33 -0800690 return Status::OK;
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800691}
692
David Rogers2761aeb2020-01-31 17:09:00 -0800693Status KeyValueStore::AppendEntry(SectorDescriptor* sector,
694 KeyDescriptor* key_descriptor,
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800695 const string_view key,
Wyatt Hepler5a33d8c2020-02-06 09:32:58 -0800696 span<const byte> value,
697 KeyDescriptor::State new_state) {
Wyatt Heplere541e072020-02-14 09:10:53 -0800698 const Address address = NextWritableAddress(sector);
699 DBG("Appending to address: %#zx", size_t(address));
700
701 Entry entry;
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800702
Wyatt Hepler5a33d8c2020-02-06 09:32:58 -0800703 if (new_state == KeyDescriptor::kDeleted) {
Wyatt Heplere541e072020-02-14 09:10:53 -0800704 entry = Entry::Tombstone(partition_,
705 address,
706 entry_header_format_.magic,
707 entry_header_format_.checksum,
708 key,
709 partition_.alignment_bytes(),
710 key_descriptor->key_version + 1);
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800711 } else {
Wyatt Heplere541e072020-02-14 09:10:53 -0800712 entry = Entry::Valid(partition_,
713 address,
714 entry_header_format_.magic,
715 entry_header_format_.checksum,
716 key,
717 value,
718 partition_.alignment_bytes(),
719 key_descriptor->key_version + 1);
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800720 }
721
Wyatt Hepler97fc7942020-02-06 15:55:45 -0800722 DBG("Appending %zu B entry with key version: %x",
Wyatt Heplere541e072020-02-14 09:10:53 -0800723 entry.size(),
724 unsigned(entry.key_version()));
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800725
Wyatt Heplere541e072020-02-14 09:10:53 -0800726 TRY_ASSIGN(const size_t written, entry.Write(key, value));
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800727
728 if (options_.verify_on_write) {
Wyatt Heplere541e072020-02-14 09:10:53 -0800729 TRY(entry.VerifyChecksumInFlash(entry_header_format_.checksum));
Wyatt Heplerb7609542020-01-24 10:29:54 -0800730 }
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800731
David Rogers2761aeb2020-01-31 17:09:00 -0800732 key_descriptor->address = address;
Wyatt Heplere541e072020-02-14 09:10:53 -0800733 key_descriptor->key_version = entry.key_version();
Wyatt Hepler5a33d8c2020-02-06 09:32:58 -0800734 key_descriptor->state = new_state;
735
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800736 sector->valid_bytes += written;
David Rogers2be76b02020-02-06 17:33:05 -0800737 sector->RemoveFreeBytes(written);
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800738 return Status::OK;
Wyatt Heplerb7609542020-01-24 10:29:54 -0800739}
740
Keir Mierle8c352dc2020-02-02 13:58:19 -0800741void KeyValueStore::LogDebugInfo() {
Keir Mierle8c352dc2020-02-02 13:58:19 -0800742 const size_t sector_size_bytes = partition_.sector_size_bytes();
743 DBG("====================== KEY VALUE STORE DUMP =========================");
744 DBG(" ");
745 DBG("Flash partition:");
Wyatt Heplerad0a7932020-02-06 08:20:38 -0800746 DBG(" Sector count = %zu", partition_.sector_count());
747 DBG(" Sector max count = %zu", kMaxUsableSectors);
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800748 DBG(" Sectors in use = %zu", sectors_.size());
Keir Mierle8c352dc2020-02-02 13:58:19 -0800749 DBG(" Sector size = %zu", sector_size_bytes);
750 DBG(" Total size = %zu", partition_.size_bytes());
751 DBG(" Alignment = %zu", partition_.alignment_bytes());
752 DBG(" ");
753 DBG("Key descriptors:");
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800754 DBG(" Entry count = %zu", key_descriptors_.size());
Keir Mierle8c352dc2020-02-02 13:58:19 -0800755 DBG(" Max entry count = %zu", kMaxEntries);
756 DBG(" ");
757 DBG(" # hash version address address (hex)");
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800758 for (size_t i = 0; i < key_descriptors_.size(); ++i) {
759 const KeyDescriptor& kd = key_descriptors_[i];
Keir Mierle8c352dc2020-02-02 13:58:19 -0800760 DBG(" |%3zu: | %8zx |%8zu | %8zu | %8zx",
761 i,
762 size_t(kd.key_hash),
763 size_t(kd.key_version),
764 size_t(kd.address),
765 size_t(kd.address));
766 }
767 DBG(" ");
768
769 DBG("Sector descriptors:");
770 DBG(" # tail free valid has_space");
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800771 for (size_t sector_id = 0; sector_id < sectors_.size(); ++sector_id) {
772 const SectorDescriptor& sd = sectors_[sector_id];
Keir Mierle8c352dc2020-02-02 13:58:19 -0800773 DBG(" |%3zu: | %8zu |%8zu | %s",
774 sector_id,
775 size_t(sd.tail_free_bytes),
776 size_t(sd.valid_bytes),
777 sd.tail_free_bytes ? "YES" : "");
778 }
779 DBG(" ");
780
781 // TODO: This should stop logging after some threshold.
782 // size_t dumped_bytes = 0;
783 DBG("Sector raw data:");
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800784 for (size_t sector_id = 0; sector_id < sectors_.size(); ++sector_id) {
Keir Mierle8c352dc2020-02-02 13:58:19 -0800785 // Read sector data. Yes, this will blow the stack on embedded.
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800786 std::array<byte, 500> raw_sector_data; // TODO!!!
Keir Mierle8c352dc2020-02-02 13:58:19 -0800787 StatusWithSize sws =
788 partition_.Read(sector_id * sector_size_bytes, raw_sector_data);
789 DBG("Read: %zu bytes", sws.size());
790
791 DBG(" base addr offs 0 1 2 3 4 5 6 7");
792 for (size_t i = 0; i < sector_size_bytes; i += 8) {
793 DBG(" %3zu %8zx %5zu | %02x %02x %02x %02x %02x %02x %02x %02x",
794 sector_id,
795 (sector_id * sector_size_bytes) + i,
796 i,
797 static_cast<unsigned int>(raw_sector_data[i + 0]),
798 static_cast<unsigned int>(raw_sector_data[i + 1]),
799 static_cast<unsigned int>(raw_sector_data[i + 2]),
800 static_cast<unsigned int>(raw_sector_data[i + 3]),
801 static_cast<unsigned int>(raw_sector_data[i + 4]),
802 static_cast<unsigned int>(raw_sector_data[i + 5]),
803 static_cast<unsigned int>(raw_sector_data[i + 6]),
804 static_cast<unsigned int>(raw_sector_data[i + 7]));
805
806 // TODO: Fix exit condition.
807 if (i > 128) {
808 break;
809 }
810 }
811 DBG(" ");
812 }
813
814 DBG("////////////////////// KEY VALUE STORE DUMP END /////////////////////");
815}
816
David Rogerscf680ab2020-02-12 23:28:32 -0800817void KeyValueStore::LogSectors() const {
818 DBG("Sector descriptors: count %zu", sectors_.size());
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800819 for (auto& sector : sectors_) {
David Rogers50185ad2020-02-07 00:02:46 -0800820 DBG(" - Sector %zu: valid %hu, recoverable %zu, free %hu",
821 SectorIndex(&sector),
822 sector.valid_bytes,
823 RecoverableBytes(sector),
824 sector.tail_free_bytes);
825 }
826}
827
David Rogerscf680ab2020-02-12 23:28:32 -0800828void KeyValueStore::LogKeyDescriptor() const {
829 DBG("Key descriptors: count %zu", key_descriptors_.size());
830 for (auto& key : key_descriptors_) {
831 DBG(" - Key: %s, hash %#zx, version %zu, address %#zx",
832 key.deleted() ? "Deleted" : "Valid",
833 static_cast<size_t>(key.key_hash),
834 static_cast<size_t>(key.key_version),
835 static_cast<size_t>(key.address));
836 }
837}
838
David Rogers3464d0a2020-02-07 11:45:46 -0800839void KeyValueStore::SectorDescriptor::RemoveValidBytes(size_t size) {
840 // TODO: add safety check for valid_bytes > size.
841 if (size > valid_bytes) {
842 CRT("!!!!!!!!!!!!!!!");
843 CRT("Remove too many valid bytes!!! remove %zu, only have %hu",
844 size,
845 valid_bytes);
846 valid_bytes = size;
847 }
848 valid_bytes -= size;
849}
850
Wyatt Hepler2ad60672020-01-21 08:00:16 -0800851} // namespace pw::kvs