blob: b18d4f2fe0a4e6fa6fc25b0a5c7cc6e94ce4c64b [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 Heplera00d1ef2020-02-14 14:31:26 -080028namespace {
Wyatt Heplerb7609542020-01-24 10:29:54 -080029
Wyatt Hepleracaacf92020-01-24 10:58:30 -080030using std::byte;
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -080031using std::string_view;
Wyatt Hepleracaacf92020-01-24 10:58:30 -080032
Wyatt Heplera00d1ef2020-02-14 14:31:26 -080033constexpr bool InvalidKey(std::string_view key) {
34 return key.empty() || (key.size() > Entry::kMaxKeyLength);
35}
36
37} // namespace
38
Wyatt Heplerad0a7932020-02-06 08:20:38 -080039KeyValueStore::KeyValueStore(FlashPartition* partition,
40 const EntryHeaderFormat& format,
41 const Options& options)
42 : partition_(*partition),
43 entry_header_format_(format),
44 options_(options),
Wyatt Hepler1c329ca2020-02-07 18:07:23 -080045 sectors_(partition_.sector_count()),
46 last_new_sector_(sectors_.data()),
Wyatt Heplerad0a7932020-02-06 08:20:38 -080047 working_buffer_{} {}
48
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -080049Status KeyValueStore::Init() {
Wyatt Hepler1c329ca2020-02-07 18:07:23 -080050 if (kMaxUsableSectors < sectors_.size()) {
Wyatt Heplerad0a7932020-02-06 08:20:38 -080051 CRT("KeyValueStore::kMaxUsableSectors must be at least as large as the "
52 "number of sectors in the flash partition");
53 return Status::FAILED_PRECONDITION;
54 }
55
Wyatt Hepler1c329ca2020-02-07 18:07:23 -080056 if (kMaxUsableSectors > sectors_.size()) {
Wyatt Heplerad0a7932020-02-06 08:20:38 -080057 DBG("KeyValueStore::kMaxUsableSectors is %zu sectors larger than needed",
Wyatt Hepler1c329ca2020-02-07 18:07:23 -080058 kMaxUsableSectors - sectors_.size());
Wyatt Heplerad0a7932020-02-06 08:20:38 -080059 }
60
Keir Mierle8c352dc2020-02-02 13:58:19 -080061 // Reset the number of occupied key descriptors; we will fill them later.
Wyatt Hepler1c329ca2020-02-07 18:07:23 -080062 key_descriptors_.clear();
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -080063
David Rogers8ce55cd2020-02-04 19:41:48 -080064 // TODO: init last_new_sector_ to a random sector. Since the on-flash stored
65 // information does not allow recovering the previous last_new_sector_ after
66 // clean start, random is a good second choice.
67
Keir Mierle8c352dc2020-02-02 13:58:19 -080068 const size_t sector_size_bytes = partition_.sector_size_bytes();
Keir Mierle8c352dc2020-02-02 13:58:19 -080069
David Rogersf0a35442020-02-04 12:16:38 -080070 if (working_buffer_.size() < sector_size_bytes) {
Wyatt Heplere541e072020-02-14 09:10:53 -080071 CRT("working_buffer_ (%zu bytes) is smaller than sector size (%zu bytes)",
David Rogersf0a35442020-02-04 12:16:38 -080072 working_buffer_.size(),
73 sector_size_bytes);
74 return Status::INVALID_ARGUMENT;
75 }
76
Keir Mierle8c352dc2020-02-02 13:58:19 -080077 DBG("First pass: Read all entries from all sectors");
Wyatt Hepler1c329ca2020-02-07 18:07:23 -080078 for (size_t sector_id = 0; sector_id < sectors_.size(); ++sector_id) {
Keir Mierle8c352dc2020-02-02 13:58:19 -080079 // Track writable bytes in this sector. Updated after reading each entry.
Wyatt Hepler1c329ca2020-02-07 18:07:23 -080080 sectors_[sector_id].tail_free_bytes = sector_size_bytes;
Keir Mierle8c352dc2020-02-02 13:58:19 -080081
82 const Address sector_address = sector_id * sector_size_bytes;
83 Address entry_address = sector_address;
84
85 for (int num_entries_in_sector = 0;; num_entries_in_sector++) {
86 DBG("Load entry: sector=%zu, entry#=%d, address=%zu",
87 sector_id,
88 num_entries_in_sector,
89 size_t(entry_address));
90
Wyatt Hepler1c329ca2020-02-07 18:07:23 -080091 if (!AddressInSector(sectors_[sector_id], entry_address)) {
Keir Mierle8c352dc2020-02-02 13:58:19 -080092 DBG("Fell off end of sector; moving to the next sector");
93 break;
94 }
95
96 Address next_entry_address;
97 Status status = LoadEntry(entry_address, &next_entry_address);
98 if (status == Status::NOT_FOUND) {
99 DBG("Hit un-written data in sector; moving to the next sector");
100 break;
101 }
102 if (status == Status::DATA_LOSS) {
103 // It's not clear KVS can make a unilateral decision about what to do
104 // in corruption cases. It's an application decision, for which we
105 // should offer some configurability. For now, entirely bail out of
106 // loading and give up.
107 //
108 // Later, scan for remaining valid keys; since it's entirely possible
109 // that there is a duplicate of the key elsewhere and everything is
110 // fine. Later, we can wipe and maybe recover the sector.
111 //
112 // TODO: Implement rest-of-sector scanning for valid entries.
113 return Status::DATA_LOSS;
114 }
115 TRY(status);
116
117 // Entry loaded successfully; so get ready to load the next one.
118 entry_address = next_entry_address;
119
120 // Update of the number of writable bytes in this sector.
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800121 sectors_[sector_id].tail_free_bytes =
Keir Mierle8c352dc2020-02-02 13:58:19 -0800122 sector_size_bytes - (entry_address - sector_address);
123 }
124 }
125
126 DBG("Second pass: Count valid bytes in each sector");
127 // Initialize the sector sizes.
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800128 for (SectorDescriptor& sector : sectors_) {
129 sector.valid_bytes = 0;
Keir Mierle8c352dc2020-02-02 13:58:19 -0800130 }
131 // For every valid key, increment the valid bytes for that sector.
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800132 for (KeyDescriptor& key_descriptor : key_descriptors_) {
133 uint32_t sector_id = key_descriptor.address / sector_size_bytes;
Wyatt Heplere541e072020-02-14 09:10:53 -0800134 Entry entry;
135 TRY(Entry::Read(partition_, key_descriptor.address, &entry));
136 sectors_[sector_id].valid_bytes += entry.size();
Keir Mierle8c352dc2020-02-02 13:58:19 -0800137 }
Wyatt Hepler729f28c2020-02-05 09:46:00 -0800138 initialized_ = true;
Keir Mierle8c352dc2020-02-02 13:58:19 -0800139 return Status::OK;
140}
141
142Status KeyValueStore::LoadEntry(Address entry_address,
143 Address* next_entry_address) {
Wyatt Heplere541e072020-02-14 09:10:53 -0800144 Entry entry;
145 TRY(Entry::Read(partition_, entry_address, &entry));
Keir Mierle8c352dc2020-02-02 13:58:19 -0800146
147 // TODO: Handle multiple magics for formats that have changed.
Wyatt Heplere541e072020-02-14 09:10:53 -0800148 if (entry.magic() != entry_header_format_.magic) {
Keir Mierle8c352dc2020-02-02 13:58:19 -0800149 // TODO: It may be cleaner to have some logging helpers for these cases.
Wyatt Heplere541e072020-02-14 09:10:53 -0800150 ERR("Found corrupt magic: %zx; expecting %zx; at address %zx",
151 size_t(entry.magic()),
Keir Mierle8c352dc2020-02-02 13:58:19 -0800152 size_t(entry_header_format_.magic),
153 size_t(entry_address));
154 return Status::DATA_LOSS;
155 }
156
157 // Read the key from flash & validate the entry (which reads the value).
Wyatt Heplera00d1ef2020-02-14 14:31:26 -0800158 Entry::KeyBuffer key_buffer;
Wyatt Heplere541e072020-02-14 09:10:53 -0800159 TRY_ASSIGN(size_t key_length, entry.ReadKey(key_buffer));
160 const string_view key(key_buffer.data(), key_length);
Wyatt Heplerbab0e202020-02-04 07:40:08 -0800161
Wyatt Heplere541e072020-02-14 09:10:53 -0800162 TRY(entry.VerifyChecksumInFlash(entry_header_format_.checksum));
Wyatt Hepler4d78cd62020-02-05 13:05:58 -0800163
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800164 KeyDescriptor key_descriptor(
165 key,
Wyatt Heplere541e072020-02-14 09:10:53 -0800166 entry.key_version(),
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800167 entry_address,
Wyatt Heplere541e072020-02-14 09:10:53 -0800168 entry.deleted() ? KeyDescriptor::kDeleted : KeyDescriptor::kValid);
Keir Mierle8c352dc2020-02-02 13:58:19 -0800169
170 DBG("Key hash: %zx (%zu)",
171 size_t(key_descriptor.key_hash),
172 size_t(key_descriptor.key_hash));
173
174 TRY(AppendNewOrOverwriteStaleExistingDescriptor(key_descriptor));
175
Wyatt Heplere541e072020-02-14 09:10:53 -0800176 *next_entry_address = entry.next_address();
Keir Mierle8c352dc2020-02-02 13:58:19 -0800177 return Status::OK;
178}
179
180// TODO: This method is the trigger of the O(valid_entries * all_entries) time
181// complexity for reading. At some cost to memory, this could be optimized by
182// using a hash table instead of scanning, but in practice this should be fine
183// for a small number of keys
184Status KeyValueStore::AppendNewOrOverwriteStaleExistingDescriptor(
185 const KeyDescriptor& key_descriptor) {
186 // With the new key descriptor, either add it to the descriptor table or
187 // overwrite an existing entry with an older version of the key.
188 KeyDescriptor* existing_descriptor = FindDescriptor(key_descriptor.key_hash);
189 if (existing_descriptor) {
190 if (existing_descriptor->key_version < key_descriptor.key_version) {
191 // Existing entry is old; replace the existing entry with the new one.
192 *existing_descriptor = key_descriptor;
193 } else {
194 // Otherwise, check for data integrity and leave the existing entry.
195 if (existing_descriptor->key_version == key_descriptor.key_version) {
196 ERR("Data loss: Duplicated old(=%zu) and new(=%zu) version",
197 size_t(existing_descriptor->key_version),
198 size_t(key_descriptor.key_version));
199 return Status::DATA_LOSS;
200 }
201 DBG("Found stale entry when appending; ignoring");
202 }
203 return Status::OK;
204 }
205 // Write new entry.
206 KeyDescriptor* newly_allocated_key_descriptor;
207 TRY(AppendEmptyDescriptor(&newly_allocated_key_descriptor));
208 *newly_allocated_key_descriptor = key_descriptor;
209 return Status::OK;
210}
211
212// TODO: Need a better name.
213Status KeyValueStore::AppendEmptyDescriptor(KeyDescriptor** new_descriptor) {
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800214 if (key_descriptors_.full()) {
Keir Mierle8c352dc2020-02-02 13:58:19 -0800215 return Status::RESOURCE_EXHAUSTED;
216 }
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800217 key_descriptors_.emplace_back();
218 *new_descriptor = &key_descriptors_.back();
Keir Mierle8c352dc2020-02-02 13:58:19 -0800219 return Status::OK;
220}
221
Keir Mierle8c352dc2020-02-02 13:58:19 -0800222KeyValueStore::KeyDescriptor* KeyValueStore::FindDescriptor(uint32_t hash) {
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800223 for (KeyDescriptor& key_descriptor : key_descriptors_) {
224 if (key_descriptor.key_hash == hash) {
225 return &key_descriptor;
Keir Mierle8c352dc2020-02-02 13:58:19 -0800226 }
227 }
228 return nullptr;
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800229}
230
231StatusWithSize KeyValueStore::Get(string_view key,
232 span<byte> value_buffer) const {
Wyatt Hepler50f70772020-02-13 11:25:10 -0800233 TRY_WITH_SIZE(CheckOperation(key));
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800234
David Rogers2761aeb2020-01-31 17:09:00 -0800235 const KeyDescriptor* key_descriptor;
Wyatt Hepler2d401692020-02-13 16:01:23 -0800236 TRY_WITH_SIZE(FindExistingKeyDescriptor(key, &key_descriptor));
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800237
Wyatt Heplere541e072020-02-14 09:10:53 -0800238 Entry entry;
239 TRY_WITH_SIZE(Entry::Read(partition_, key_descriptor->address, &entry));
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800240
Wyatt Heplere541e072020-02-14 09:10:53 -0800241 StatusWithSize result = entry.ReadValue(value_buffer);
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800242 if (result.ok() && options_.verify_on_read) {
David Rogerscf680ab2020-02-12 23:28:32 -0800243 Status verify_result =
Wyatt Heplere541e072020-02-14 09:10:53 -0800244 entry.VerifyChecksum(entry_header_format_.checksum,
245 key,
246 value_buffer.subspan(0, result.size()));
David Rogerscf680ab2020-02-12 23:28:32 -0800247 if (!verify_result.ok()) {
Wyatt Hepler50f70772020-02-13 11:25:10 -0800248 std::memset(
249 value_buffer.subspan(0, result.size()).data(), 0, result.size());
250 return StatusWithSize(verify_result);
David Rogerscf680ab2020-02-12 23:28:32 -0800251 }
252
253 return StatusWithSize(verify_result, result.size());
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800254 }
255 return result;
256}
257
258Status KeyValueStore::Put(string_view key, span<const byte> value) {
Keir Mierle8c352dc2020-02-02 13:58:19 -0800259 DBG("Writing key/value; key length=%zu, value length=%zu",
260 key.size(),
261 value.size());
Wyatt Hepler729f28c2020-02-05 09:46:00 -0800262
263 TRY(CheckOperation(key));
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800264
265 if (value.size() > (1 << 24)) {
266 // TODO: Reject sizes that are larger than the maximum?
267 }
268
David Rogers2761aeb2020-01-31 17:09:00 -0800269 KeyDescriptor* key_descriptor;
Wyatt Hepler2d401692020-02-13 16:01:23 -0800270 Status status = FindKeyDescriptor(key, &key_descriptor);
271
272 if (status.ok()) {
David Rogers3464d0a2020-02-07 11:45:46 -0800273 DBG("Writing over existing entry for key 0x%08" PRIx32 " in sector %zu",
274 key_descriptor->key_hash,
275 SectorIndex(SectorFromAddress(key_descriptor->address)));
Wyatt Hepler5a33d8c2020-02-06 09:32:58 -0800276 return WriteEntryForExistingKey(
277 key_descriptor, KeyDescriptor::kValid, key, value);
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800278 }
David Rogers2761aeb2020-01-31 17:09:00 -0800279
Wyatt Hepler2d401692020-02-13 16:01:23 -0800280 if (status == Status::NOT_FOUND) {
281 return WriteEntryForNewKey(key, value);
282 }
283
284 return status;
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800285}
286
287Status KeyValueStore::Delete(string_view key) {
Wyatt Hepler729f28c2020-02-05 09:46:00 -0800288 TRY(CheckOperation(key));
289
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800290 KeyDescriptor* key_descriptor;
Wyatt Hepler2d401692020-02-13 16:01:23 -0800291 TRY(FindExistingKeyDescriptor(key, &key_descriptor));
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800292
David Rogers3464d0a2020-02-07 11:45:46 -0800293 DBG("Writing tombstone for existing key 0x%08" PRIx32 " in sector %zu",
294 key_descriptor->key_hash,
295 SectorIndex(SectorFromAddress(key_descriptor->address)));
Wyatt Hepler5a33d8c2020-02-06 09:32:58 -0800296 return WriteEntryForExistingKey(
297 key_descriptor, KeyDescriptor::kDeleted, key, {});
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800298}
299
300KeyValueStore::iterator& KeyValueStore::iterator::operator++() {
301 // Skip to the next entry that is valid (not deleted).
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800302 while (++index_ < item_.kvs_.key_descriptors_.size() &&
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800303 descriptor().deleted()) {
304 }
305 return *this;
306}
307
308const KeyValueStore::Item& KeyValueStore::iterator::operator*() {
309 std::memset(item_.key_buffer_.data(), 0, item_.key_buffer_.size());
310
Wyatt Heplere541e072020-02-14 09:10:53 -0800311 Entry entry;
312 if (Entry::Read(item_.kvs_.partition_, descriptor().address, &entry).ok()) {
313 entry.ReadKey(item_.key_buffer_);
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800314 }
315
316 return item_;
317}
318
319KeyValueStore::iterator KeyValueStore::begin() const {
320 size_t i = 0;
321 // Skip over any deleted entries at the start of the descriptor list.
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800322 while (i < key_descriptors_.size() && key_descriptors_[i].deleted()) {
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800323 i += 1;
324 }
325 return iterator(*this, i);
326}
327
328// TODO(hepler): The valid entry count could be tracked in the KVS to avoid the
329// need for this for-loop.
330size_t KeyValueStore::size() const {
331 size_t valid_entries = 0;
332
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800333 for (const KeyDescriptor& key_descriptor : key_descriptors_) {
334 if (!key_descriptor.deleted()) {
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800335 valid_entries += 1;
336 }
337 }
338
339 return valid_entries;
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800340}
341
Wyatt Heplered163b02020-02-03 17:49:32 -0800342StatusWithSize KeyValueStore::ValueSize(std::string_view key) const {
Wyatt Hepler50f70772020-02-13 11:25:10 -0800343 TRY_WITH_SIZE(CheckOperation(key));
Wyatt Heplered163b02020-02-03 17:49:32 -0800344
345 const KeyDescriptor* key_descriptor;
Wyatt Hepler2d401692020-02-13 16:01:23 -0800346 TRY_WITH_SIZE(FindExistingKeyDescriptor(key, &key_descriptor));
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800347
Wyatt Heplere541e072020-02-14 09:10:53 -0800348 Entry entry;
349 TRY_WITH_SIZE(Entry::Read(partition_, key_descriptor->address, &entry));
Wyatt Heplered163b02020-02-03 17:49:32 -0800350
Wyatt Heplere541e072020-02-14 09:10:53 -0800351 return StatusWithSize(entry.value_size());
Wyatt Heplered163b02020-02-03 17:49:32 -0800352}
353
Wyatt Hepler4d78cd62020-02-05 13:05:58 -0800354uint32_t KeyValueStore::HashKey(string_view string) {
355 uint32_t hash = 0;
356 uint32_t coefficient = 65599u;
357
358 for (char ch : string) {
359 hash += coefficient * unsigned(ch);
360 coefficient *= 65599u;
361 }
362
363 return hash;
364}
365
Wyatt Hepler6e3a83b2020-02-04 07:36:45 -0800366Status KeyValueStore::FixedSizeGet(std::string_view key,
367 byte* value,
368 size_t size_bytes) const {
369 // Ensure that the size of the stored value matches the size of the type.
370 // Otherwise, report error. This check avoids potential memory corruption.
371 StatusWithSize result = ValueSize(key);
372 if (!result.ok()) {
373 return result.status();
Keir Mierle8c352dc2020-02-02 13:58:19 -0800374 }
Wyatt Hepler6e3a83b2020-02-04 07:36:45 -0800375 if (result.size() != size_bytes) {
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800376 DBG("Requested %zu B read, but value is %zu B", size_bytes, result.size());
Wyatt Hepler6e3a83b2020-02-04 07:36:45 -0800377 return Status::INVALID_ARGUMENT;
Wyatt Heplerbab0e202020-02-04 07:40:08 -0800378 }
Wyatt Hepler6e3a83b2020-02-04 07:36:45 -0800379 return Get(key, span(value, size_bytes)).status();
Keir Mierle8c352dc2020-02-02 13:58:19 -0800380}
381
Wyatt Hepler729f28c2020-02-05 09:46:00 -0800382Status KeyValueStore::CheckOperation(string_view key) const {
Wyatt Hepleracaacf92020-01-24 10:58:30 -0800383 if (InvalidKey(key)) {
Wyatt Heplerb7609542020-01-24 10:29:54 -0800384 return Status::INVALID_ARGUMENT;
385 }
Wyatt Hepler729f28c2020-02-05 09:46:00 -0800386 if (!initialized_) {
Wyatt Heplerb7609542020-01-24 10:29:54 -0800387 return Status::FAILED_PRECONDITION;
388 }
Wyatt Heplerb7609542020-01-24 10:29:54 -0800389 return Status::OK;
390}
391
Wyatt Hepler2d401692020-02-13 16:01:23 -0800392// Searches for a KeyDescriptor that matches this key and sets *result to point
393// to it if one is found.
394//
395// OK: there is a matching descriptor and *result is set
396// NOT_FOUND: there is no descriptor that matches this key, but this key
397// has a unique hash (and could potentially be added to the KVS)
398// ALREADY_EXISTS: there is no descriptor that matches this key, but the
399// key's hash collides with the hash for an existing descriptor
400//
David Rogers2761aeb2020-01-31 17:09:00 -0800401Status KeyValueStore::FindKeyDescriptor(string_view key,
402 const KeyDescriptor** result) const {
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800403 const uint32_t hash = HashKey(key);
Wyatt Heplera00d1ef2020-02-14 14:31:26 -0800404 Entry::KeyBuffer key_buffer;
Wyatt Heplerb7609542020-01-24 10:29:54 -0800405
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800406 for (auto& descriptor : key_descriptors_) {
David Rogers2761aeb2020-01-31 17:09:00 -0800407 if (descriptor.key_hash == hash) {
Wyatt Heplere541e072020-02-14 09:10:53 -0800408 TRY(Entry::ReadKey(
Wyatt Heplera00d1ef2020-02-14 14:31:26 -0800409 partition_, descriptor.address, key.size(), key_buffer.data()));
Wyatt Heplerb7609542020-01-24 10:29:54 -0800410
Wyatt Heplere541e072020-02-14 09:10:53 -0800411 if (key == string_view(key_buffer.data(), key.size())) {
Wyatt Hepler5a33d8c2020-02-06 09:32:58 -0800412 DBG("Found match for key hash 0x%08" PRIx32, hash);
David Rogers2761aeb2020-01-31 17:09:00 -0800413 *result = &descriptor;
Wyatt Heplerb7609542020-01-24 10:29:54 -0800414 return Status::OK;
Wyatt Hepler2d401692020-02-13 16:01:23 -0800415 } else {
416 WRN("Found key hash collision for 0x%08" PRIx32, hash);
417 return Status::ALREADY_EXISTS;
Wyatt Heplerb7609542020-01-24 10:29:54 -0800418 }
Wyatt Heplerb7609542020-01-24 10:29:54 -0800419 }
420 }
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800421 return Status::NOT_FOUND;
422}
423
Wyatt Hepler2d401692020-02-13 16:01:23 -0800424// Searches for a KeyDescriptor that matches this key and sets *result to point
425// to it if one is found.
426//
427// OK: there is a matching descriptor and *result is set
428// NOT_FOUND: there is no descriptor that matches this key
429//
430Status KeyValueStore::FindExistingKeyDescriptor(
431 string_view key, const KeyDescriptor** result) const {
432 Status status = FindKeyDescriptor(key, result);
433
434 // If the key's hash collides with an existing key or if the key is deleted,
435 // treat it as if it is not in the KVS.
436 if (status == Status::ALREADY_EXISTS ||
437 (status.ok() && (*result)->deleted())) {
438 return Status::NOT_FOUND;
439 }
440 return status;
441}
442
David Rogers2761aeb2020-01-31 17:09:00 -0800443Status KeyValueStore::WriteEntryForExistingKey(KeyDescriptor* key_descriptor,
Wyatt Hepler5a33d8c2020-02-06 09:32:58 -0800444 KeyDescriptor::State new_state,
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800445 string_view key,
446 span<const byte> value) {
Wyatt Hepler5a33d8c2020-02-06 09:32:58 -0800447 // Find the original entry and sector to update the sector's valid_bytes.
Wyatt Hepler30a52152020-02-12 11:26:05 -0800448 Entry original_entry;
Wyatt Heplere541e072020-02-14 09:10:53 -0800449 TRY(Entry::Read(partition_, key_descriptor->address, &original_entry));
David Rogers3464d0a2020-02-07 11:45:46 -0800450 SectorDescriptor* old_sector = SectorFromAddress(key_descriptor->address);
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800451
David Rogers2761aeb2020-01-31 17:09:00 -0800452 SectorDescriptor* sector;
Wyatt Hepler97fc7942020-02-06 15:55:45 -0800453 TRY(FindOrRecoverSectorWithSpace(
Wyatt Hepler30a52152020-02-12 11:26:05 -0800454 &sector, Entry::size(partition_.alignment_bytes(), key, value)));
David Rogers8ce55cd2020-02-04 19:41:48 -0800455 DBG("Writing existing entry; found sector: %zu", SectorIndex(sector));
David Rogers3464d0a2020-02-07 11:45:46 -0800456
457 if (old_sector != SectorFromAddress(key_descriptor->address)) {
458 DBG("Sector for old entry (size %zu) was garbage collected. Old entry "
459 "relocated to sector %zu",
460 original_entry.size(),
461 SectorIndex(SectorFromAddress(key_descriptor->address)));
462
463 old_sector = SectorFromAddress(key_descriptor->address);
464 }
465
Wyatt Hepler5a33d8c2020-02-06 09:32:58 -0800466 TRY(AppendEntry(sector, key_descriptor, key, value, new_state));
467
David Rogers3464d0a2020-02-07 11:45:46 -0800468 old_sector->RemoveValidBytes(original_entry.size());
Wyatt Hepler5a33d8c2020-02-06 09:32:58 -0800469 return Status::OK;
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800470}
471
472Status KeyValueStore::WriteEntryForNewKey(string_view key,
473 span<const byte> value) {
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800474 if (key_descriptors_.full()) {
Keir Mierle8c352dc2020-02-02 13:58:19 -0800475 WRN("KVS full: trying to store a new entry, but can't. Have %zu entries",
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800476 key_descriptors_.size());
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800477 return Status::RESOURCE_EXHAUSTED;
478 }
479
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800480 // Create the KeyDescriptor that will be added to the list. The version and
481 // address will be set by AppendEntry.
482 KeyDescriptor key_descriptor(key, 0, 0);
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800483
David Rogers2761aeb2020-01-31 17:09:00 -0800484 SectorDescriptor* sector;
Wyatt Hepler97fc7942020-02-06 15:55:45 -0800485 TRY(FindOrRecoverSectorWithSpace(
Wyatt Hepler30a52152020-02-12 11:26:05 -0800486 &sector, Entry::size(partition_.alignment_bytes(), key, value)));
David Rogers8ce55cd2020-02-04 19:41:48 -0800487 DBG("Writing new entry; found sector: %zu", SectorIndex(sector));
Wyatt Hepler0af6ad92020-02-13 15:54:46 -0800488 TRY(AppendEntry(sector, &key_descriptor, key, value, KeyDescriptor::kValid));
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800489
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800490 // Only add the entry when we are certain the write succeeded.
491 key_descriptors_.push_back(key_descriptor);
Wyatt Heplerb7609542020-01-24 10:29:54 -0800492 return Status::OK;
493}
494
David Rogers2761aeb2020-01-31 17:09:00 -0800495Status KeyValueStore::RelocateEntry(KeyDescriptor& key_descriptor) {
David Rogersf0a35442020-02-04 12:16:38 -0800496 struct TempEntry {
Wyatt Heplere541e072020-02-14 09:10:53 -0800497 Entry::KeyBuffer key;
David Rogersf0a35442020-02-04 12:16:38 -0800498 std::array<char, sizeof(working_buffer_) - sizeof(key)> value;
499 };
Wyatt Heplere541e072020-02-14 09:10:53 -0800500 TempEntry* temp_entry = reinterpret_cast<TempEntry*>(working_buffer_.data());
David Rogersf0a35442020-02-04 12:16:38 -0800501
David Rogersdf025cd2020-02-06 17:05:34 -0800502 DBG("Relocating entry"); // TODO: add entry info to the log statement.
503
Wyatt Heplere541e072020-02-14 09:10:53 -0800504 // Read the entry to be relocated. Store the entry in a local variable and
David Rogersf0a35442020-02-04 12:16:38 -0800505 // store the key and value in the TempEntry stored in the static allocated
506 // working_buffer_.
Wyatt Heplere541e072020-02-14 09:10:53 -0800507 Entry entry;
508 TRY(Entry::Read(partition_, key_descriptor.address, &entry));
509 TRY_ASSIGN(size_t key_length, entry.ReadKey(temp_entry->key));
510 string_view key = string_view(temp_entry->key.data(), key_length);
511 auto result = entry.ReadValue(as_writable_bytes(span(temp_entry->value)));
David Rogersf0a35442020-02-04 12:16:38 -0800512 if (!result.status().ok()) {
513 return Status::INTERNAL;
514 }
515
Wyatt Heplere541e072020-02-14 09:10:53 -0800516 auto value = span(temp_entry->value.data(), result.size());
517 TRY(entry.VerifyChecksum(
David Rogersf0a35442020-02-04 12:16:38 -0800518 entry_header_format_.checksum, key, as_bytes(value)));
519
David Rogers3464d0a2020-02-07 11:45:46 -0800520 SectorDescriptor* old_sector = SectorFromAddress(key_descriptor.address);
David Rogersf0a35442020-02-04 12:16:38 -0800521
522 // Find a new sector for the entry and write it to the new location.
David Rogers8ce55cd2020-02-04 19:41:48 -0800523 SectorDescriptor* new_sector;
Wyatt Heplere541e072020-02-14 09:10:53 -0800524 TRY(FindSectorWithSpace(&new_sector, entry.size(), old_sector, true));
Wyatt Hepler0af6ad92020-02-13 15:54:46 -0800525 TRY(AppendEntry(
526 new_sector, &key_descriptor, key, as_bytes(value), key_descriptor.state));
David Rogersdf025cd2020-02-06 17:05:34 -0800527
528 // Do the valid bytes accounting for the sector the entry was relocated out
529 // of.
Wyatt Heplere541e072020-02-14 09:10:53 -0800530 old_sector->RemoveValidBytes(entry.size());
David Rogersdf025cd2020-02-06 17:05:34 -0800531
532 return Status::OK;
David Rogersa12786b2020-01-31 16:02:33 -0800533}
534
David Rogers8db5a722020-02-03 18:28:34 -0800535// Find either an existing sector with enough space that is not the sector to
536// skip, or an empty sector. Maintains the invariant that there is always at
537// least 1 empty sector unless set to bypass the rule.
Wyatt Hepler5a33d8c2020-02-06 09:32:58 -0800538Status KeyValueStore::FindSectorWithSpace(
539 SectorDescriptor** found_sector,
540 size_t size,
541 const SectorDescriptor* sector_to_skip,
542 bool bypass_empty_sector_rule) {
David Rogers8ce55cd2020-02-04 19:41:48 -0800543 // The last_new_sector_ is the sector that was last selected as the "new empty
544 // sector" to write to. This last new sector is used as the starting point for
545 // the next "find a new empty sector to write to" operation. By using the last
546 // new sector as the start point we will cycle which empty sector is selected
547 // next, spreading the wear across all the empty sectors and get a wear
548 // leveling benefit, rather than putting more wear on the lower number
549 // sectors.
550 //
551 // Locally use the sector index for ease of iterating through the sectors. For
552 // the persistent storage use SectorDescriptor* rather than sector index
553 // because SectorDescriptor* is the standard way to identify a sector.
554 size_t last_new_sector_index_ = SectorIndex(last_new_sector_);
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800555 size_t start = (last_new_sector_index_ + 1) % sectors_.size();
David Rogers2761aeb2020-01-31 17:09:00 -0800556 SectorDescriptor* first_empty_sector = nullptr;
David Rogers8db5a722020-02-03 18:28:34 -0800557 bool at_least_two_empty_sectors = bypass_empty_sector_rule;
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800558
David Rogers67f4b6c2020-02-06 16:17:09 -0800559 DBG("Find sector with %zu bytes available", size);
560 if (sector_to_skip != nullptr) {
561 DBG(" Skip sector %zu", SectorIndex(sector_to_skip));
562 }
563 if (bypass_empty_sector_rule) {
564 DBG(" Bypassing empty sector rule");
565 }
566
David Rogers8ce55cd2020-02-04 19:41:48 -0800567 // Look for a partial sector to use with enough space. Immediately use the
568 // first one of those that is found. While scanning for a partial sector, keep
569 // track of the first empty sector and if a second sector was seen.
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800570 for (size_t j = 0; j < sectors_.size(); j++) {
571 size_t i = (j + start) % sectors_.size();
572 SectorDescriptor& sector = sectors_[i];
Keir Mierle8c352dc2020-02-02 13:58:19 -0800573
David Rogers8db5a722020-02-03 18:28:34 -0800574 if (sector_to_skip == &sector) {
David Rogers67f4b6c2020-02-06 16:17:09 -0800575 DBG(" Skipping the skip sector %zu", i);
David Rogers8db5a722020-02-03 18:28:34 -0800576 continue;
577 }
578
David Rogers67f4b6c2020-02-06 16:17:09 -0800579 DBG(" Examining sector %zu with %hu bytes available",
580 i,
581 sector.tail_free_bytes);
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800582 if (!SectorEmpty(sector) && sector.HasSpace(size)) {
David Rogers67f4b6c2020-02-06 16:17:09 -0800583 DBG(" Partially occupied sector %zu with enough space; done!", i);
David Rogers8ce55cd2020-02-04 19:41:48 -0800584 *found_sector = &sector;
585 return Status::OK;
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800586 }
587
588 if (SectorEmpty(sector)) {
589 if (first_empty_sector == nullptr) {
590 first_empty_sector = &sector;
591 } else {
592 at_least_two_empty_sectors = true;
Wyatt Hepler2ad60672020-01-21 08:00:16 -0800593 }
Wyatt Heplerb7609542020-01-24 10:29:54 -0800594 }
595 }
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800596
David Rogers8ce55cd2020-02-04 19:41:48 -0800597 // If the scan for a partial sector does not find a suitable sector, use the
598 // first empty sector that was found. Normally it is required to keep 1 empty
599 // sector after the sector found here, but that rule can be bypassed in
600 // special circumstances (such as during garbage collection).
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800601 if (at_least_two_empty_sectors) {
David Rogers67f4b6c2020-02-06 16:17:09 -0800602 DBG(" Found a usable empty sector; returning the first found (%zu)",
David Rogers8ce55cd2020-02-04 19:41:48 -0800603 SectorIndex(first_empty_sector));
604 last_new_sector_ = first_empty_sector;
605 *found_sector = first_empty_sector;
606 return Status::OK;
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800607 }
David Rogers8ce55cd2020-02-04 19:41:48 -0800608
609 // No sector was found.
David Rogers67f4b6c2020-02-06 16:17:09 -0800610 DBG(" Unable to find a usable sector");
David Rogers8ce55cd2020-02-04 19:41:48 -0800611 *found_sector = nullptr;
612 return Status::RESOURCE_EXHAUSTED;
Wyatt Heplerb7609542020-01-24 10:29:54 -0800613}
614
David Rogers2761aeb2020-01-31 17:09:00 -0800615Status KeyValueStore::FindOrRecoverSectorWithSpace(SectorDescriptor** sector,
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800616 size_t size) {
David Rogers8ce55cd2020-02-04 19:41:48 -0800617 Status result = FindSectorWithSpace(sector, size);
Wyatt Hepler2d401692020-02-13 16:01:23 -0800618 if (result == Status::RESOURCE_EXHAUSTED && options_.partial_gc_on_write) {
David Rogers1541d612020-02-06 23:47:02 -0800619 // Garbage collect and then try again to find the best sector.
620 TRY(GarbageCollectOneSector());
621 return FindSectorWithSpace(sector, size);
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800622 }
David Rogers8ce55cd2020-02-04 19:41:48 -0800623 return result;
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800624}
625
David Rogers2761aeb2020-01-31 17:09:00 -0800626KeyValueStore::SectorDescriptor* KeyValueStore::FindSectorToGarbageCollect() {
627 SectorDescriptor* sector_candidate = nullptr;
David Rogersa12786b2020-01-31 16:02:33 -0800628 size_t candidate_bytes = 0;
629
630 // Step 1: Try to find a sectors with stale keys and no valid keys (no
631 // relocation needed). If any such sectors are found, use the sector with the
632 // most reclaimable bytes.
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800633 for (auto& sector : sectors_) {
David Rogersa12786b2020-01-31 16:02:33 -0800634 if ((sector.valid_bytes == 0) &&
635 (RecoverableBytes(sector) > candidate_bytes)) {
636 sector_candidate = &sector;
637 candidate_bytes = RecoverableBytes(sector);
638 }
639 }
640
641 // Step 2: If step 1 yields no sectors, just find the sector with the most
642 // reclaimable bytes.
643 if (sector_candidate == nullptr) {
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800644 for (auto& sector : sectors_) {
David Rogersa12786b2020-01-31 16:02:33 -0800645 if (RecoverableBytes(sector) > candidate_bytes) {
646 sector_candidate = &sector;
647 candidate_bytes = RecoverableBytes(sector);
648 }
649 }
650 }
651
David Rogers5981f312020-02-13 13:33:56 -0800652 if (sector_candidate != nullptr) {
653 DBG("Found sector %zu to Garbage Collect, %zu recoverable bytes",
654 SectorIndex(sector_candidate),
655 RecoverableBytes(*sector_candidate));
656 } else {
657 DBG("Unable to find sector to garbage collect!");
658 }
David Rogersa12786b2020-01-31 16:02:33 -0800659 return sector_candidate;
660}
661
David Rogers1541d612020-02-06 23:47:02 -0800662Status KeyValueStore::GarbageCollectOneSector() {
David Rogers67f4b6c2020-02-06 16:17:09 -0800663 DBG("Garbage Collect a single sector");
664
David Rogersa12786b2020-01-31 16:02:33 -0800665 // Step 1: Find the sector to garbage collect
David Rogers2761aeb2020-01-31 17:09:00 -0800666 SectorDescriptor* sector_to_gc = FindSectorToGarbageCollect();
David Rogers3464d0a2020-02-07 11:45:46 -0800667 LogSectors();
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800668
David Rogersa12786b2020-01-31 16:02:33 -0800669 if (sector_to_gc == nullptr) {
670 return Status::RESOURCE_EXHAUSTED;
671 }
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800672
David Rogersa12786b2020-01-31 16:02:33 -0800673 // Step 2: Move any valid entries in the GC sector to other sectors
674 if (sector_to_gc->valid_bytes != 0) {
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800675 for (auto& descriptor : key_descriptors_) {
David Rogers2761aeb2020-01-31 17:09:00 -0800676 if (AddressInSector(*sector_to_gc, descriptor.address)) {
David Rogers67f4b6c2020-02-06 16:17:09 -0800677 DBG(" Relocate entry");
David Rogers2761aeb2020-01-31 17:09:00 -0800678 TRY(RelocateEntry(descriptor));
David Rogersa12786b2020-01-31 16:02:33 -0800679 }
Wyatt Heplerb7609542020-01-24 10:29:54 -0800680 }
681 }
Wyatt Heplerb7609542020-01-24 10:29:54 -0800682
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800683 if (sector_to_gc->valid_bytes != 0) {
David Rogers67f4b6c2020-02-06 16:17:09 -0800684 ERR(" Failed to relocate valid entries from sector being garbage "
685 "collected, %hu valid bytes remain",
686 sector_to_gc->valid_bytes);
Wyatt Heplerb7609542020-01-24 10:29:54 -0800687 return Status::INTERNAL;
688 }
689
David Rogersa12786b2020-01-31 16:02:33 -0800690 // Step 3: Reinitialize the sector
691 sector_to_gc->tail_free_bytes = 0;
692 TRY(partition_.Erase(SectorBaseAddress(sector_to_gc), 1));
693 sector_to_gc->tail_free_bytes = partition_.sector_size_bytes();
Wyatt Heplerb7609542020-01-24 10:29:54 -0800694
David Rogers67f4b6c2020-02-06 16:17:09 -0800695 DBG(" Garbage Collect complete");
David Rogers50185ad2020-02-07 00:02:46 -0800696 LogSectors();
David Rogersa12786b2020-01-31 16:02:33 -0800697 return Status::OK;
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800698}
699
David Rogers2761aeb2020-01-31 17:09:00 -0800700Status KeyValueStore::AppendEntry(SectorDescriptor* sector,
701 KeyDescriptor* key_descriptor,
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800702 const string_view key,
Wyatt Hepler5a33d8c2020-02-06 09:32:58 -0800703 span<const byte> value,
704 KeyDescriptor::State new_state) {
Wyatt Heplere541e072020-02-14 09:10:53 -0800705 const Address address = NextWritableAddress(sector);
706 DBG("Appending to address: %#zx", size_t(address));
707
708 Entry entry;
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800709
Wyatt Hepler5a33d8c2020-02-06 09:32:58 -0800710 if (new_state == KeyDescriptor::kDeleted) {
Wyatt Heplere541e072020-02-14 09:10:53 -0800711 entry = Entry::Tombstone(partition_,
712 address,
713 entry_header_format_.magic,
714 entry_header_format_.checksum,
715 key,
716 partition_.alignment_bytes(),
717 key_descriptor->key_version + 1);
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800718 } else {
Wyatt Heplere541e072020-02-14 09:10:53 -0800719 entry = Entry::Valid(partition_,
720 address,
721 entry_header_format_.magic,
722 entry_header_format_.checksum,
723 key,
724 value,
725 partition_.alignment_bytes(),
726 key_descriptor->key_version + 1);
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800727 }
728
Wyatt Hepler97fc7942020-02-06 15:55:45 -0800729 DBG("Appending %zu B entry with key version: %x",
Wyatt Heplere541e072020-02-14 09:10:53 -0800730 entry.size(),
731 unsigned(entry.key_version()));
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800732
Wyatt Heplere541e072020-02-14 09:10:53 -0800733 TRY_ASSIGN(const size_t written, entry.Write(key, value));
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800734
735 if (options_.verify_on_write) {
Wyatt Heplere541e072020-02-14 09:10:53 -0800736 TRY(entry.VerifyChecksumInFlash(entry_header_format_.checksum));
Wyatt Heplerb7609542020-01-24 10:29:54 -0800737 }
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800738
David Rogers2761aeb2020-01-31 17:09:00 -0800739 key_descriptor->address = address;
Wyatt Heplere541e072020-02-14 09:10:53 -0800740 key_descriptor->key_version = entry.key_version();
Wyatt Hepler5a33d8c2020-02-06 09:32:58 -0800741 key_descriptor->state = new_state;
742
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800743 sector->valid_bytes += written;
David Rogers2be76b02020-02-06 17:33:05 -0800744 sector->RemoveFreeBytes(written);
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800745 return Status::OK;
Wyatt Heplerb7609542020-01-24 10:29:54 -0800746}
747
Keir Mierle8c352dc2020-02-02 13:58:19 -0800748void KeyValueStore::LogDebugInfo() {
Keir Mierle8c352dc2020-02-02 13:58:19 -0800749 const size_t sector_size_bytes = partition_.sector_size_bytes();
750 DBG("====================== KEY VALUE STORE DUMP =========================");
751 DBG(" ");
752 DBG("Flash partition:");
Wyatt Heplerad0a7932020-02-06 08:20:38 -0800753 DBG(" Sector count = %zu", partition_.sector_count());
754 DBG(" Sector max count = %zu", kMaxUsableSectors);
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800755 DBG(" Sectors in use = %zu", sectors_.size());
Keir Mierle8c352dc2020-02-02 13:58:19 -0800756 DBG(" Sector size = %zu", sector_size_bytes);
757 DBG(" Total size = %zu", partition_.size_bytes());
758 DBG(" Alignment = %zu", partition_.alignment_bytes());
759 DBG(" ");
760 DBG("Key descriptors:");
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800761 DBG(" Entry count = %zu", key_descriptors_.size());
Keir Mierle8c352dc2020-02-02 13:58:19 -0800762 DBG(" Max entry count = %zu", kMaxEntries);
763 DBG(" ");
764 DBG(" # hash version address address (hex)");
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800765 for (size_t i = 0; i < key_descriptors_.size(); ++i) {
766 const KeyDescriptor& kd = key_descriptors_[i];
Keir Mierle8c352dc2020-02-02 13:58:19 -0800767 DBG(" |%3zu: | %8zx |%8zu | %8zu | %8zx",
768 i,
769 size_t(kd.key_hash),
770 size_t(kd.key_version),
771 size_t(kd.address),
772 size_t(kd.address));
773 }
774 DBG(" ");
775
776 DBG("Sector descriptors:");
777 DBG(" # tail free valid has_space");
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800778 for (size_t sector_id = 0; sector_id < sectors_.size(); ++sector_id) {
779 const SectorDescriptor& sd = sectors_[sector_id];
Keir Mierle8c352dc2020-02-02 13:58:19 -0800780 DBG(" |%3zu: | %8zu |%8zu | %s",
781 sector_id,
782 size_t(sd.tail_free_bytes),
783 size_t(sd.valid_bytes),
784 sd.tail_free_bytes ? "YES" : "");
785 }
786 DBG(" ");
787
788 // TODO: This should stop logging after some threshold.
789 // size_t dumped_bytes = 0;
790 DBG("Sector raw data:");
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800791 for (size_t sector_id = 0; sector_id < sectors_.size(); ++sector_id) {
Keir Mierle8c352dc2020-02-02 13:58:19 -0800792 // Read sector data. Yes, this will blow the stack on embedded.
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800793 std::array<byte, 500> raw_sector_data; // TODO!!!
Keir Mierle8c352dc2020-02-02 13:58:19 -0800794 StatusWithSize sws =
795 partition_.Read(sector_id * sector_size_bytes, raw_sector_data);
796 DBG("Read: %zu bytes", sws.size());
797
798 DBG(" base addr offs 0 1 2 3 4 5 6 7");
799 for (size_t i = 0; i < sector_size_bytes; i += 8) {
800 DBG(" %3zu %8zx %5zu | %02x %02x %02x %02x %02x %02x %02x %02x",
801 sector_id,
802 (sector_id * sector_size_bytes) + i,
803 i,
804 static_cast<unsigned int>(raw_sector_data[i + 0]),
805 static_cast<unsigned int>(raw_sector_data[i + 1]),
806 static_cast<unsigned int>(raw_sector_data[i + 2]),
807 static_cast<unsigned int>(raw_sector_data[i + 3]),
808 static_cast<unsigned int>(raw_sector_data[i + 4]),
809 static_cast<unsigned int>(raw_sector_data[i + 5]),
810 static_cast<unsigned int>(raw_sector_data[i + 6]),
811 static_cast<unsigned int>(raw_sector_data[i + 7]));
812
813 // TODO: Fix exit condition.
814 if (i > 128) {
815 break;
816 }
817 }
818 DBG(" ");
819 }
820
821 DBG("////////////////////// KEY VALUE STORE DUMP END /////////////////////");
822}
823
David Rogerscf680ab2020-02-12 23:28:32 -0800824void KeyValueStore::LogSectors() const {
825 DBG("Sector descriptors: count %zu", sectors_.size());
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800826 for (auto& sector : sectors_) {
David Rogers50185ad2020-02-07 00:02:46 -0800827 DBG(" - Sector %zu: valid %hu, recoverable %zu, free %hu",
828 SectorIndex(&sector),
829 sector.valid_bytes,
830 RecoverableBytes(sector),
831 sector.tail_free_bytes);
832 }
833}
834
David Rogerscf680ab2020-02-12 23:28:32 -0800835void KeyValueStore::LogKeyDescriptor() const {
836 DBG("Key descriptors: count %zu", key_descriptors_.size());
837 for (auto& key : key_descriptors_) {
838 DBG(" - Key: %s, hash %#zx, version %zu, address %#zx",
839 key.deleted() ? "Deleted" : "Valid",
840 static_cast<size_t>(key.key_hash),
841 static_cast<size_t>(key.key_version),
842 static_cast<size_t>(key.address));
843 }
844}
845
David Rogers3464d0a2020-02-07 11:45:46 -0800846void KeyValueStore::SectorDescriptor::RemoveValidBytes(size_t size) {
847 // TODO: add safety check for valid_bytes > size.
848 if (size > valid_bytes) {
849 CRT("!!!!!!!!!!!!!!!");
850 CRT("Remove too many valid bytes!!! remove %zu, only have %hu",
851 size,
852 valid_bytes);
853 valid_bytes = size;
854 }
855 valid_bytes -= size;
856}
857
Wyatt Hepler2ad60672020-01-21 08:00:16 -0800858} // namespace pw::kvs