blob: 98a31d115aa4a638d844c484bdeca28acfe152e0 [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()),
Wyatt Hepler5406a672020-02-18 15:42:38 -080046 last_new_sector_(sectors_.data()) {}
Wyatt Heplerad0a7932020-02-06 08:20:38 -080047
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -080048Status KeyValueStore::Init() {
Wyatt Hepler1c329ca2020-02-07 18:07:23 -080049 if (kMaxUsableSectors < sectors_.size()) {
Wyatt Heplerad0a7932020-02-06 08:20:38 -080050 CRT("KeyValueStore::kMaxUsableSectors must be at least as large as the "
51 "number of sectors in the flash partition");
52 return Status::FAILED_PRECONDITION;
53 }
54
Wyatt Hepler1c329ca2020-02-07 18:07:23 -080055 if (kMaxUsableSectors > sectors_.size()) {
Wyatt Heplerad0a7932020-02-06 08:20:38 -080056 DBG("KeyValueStore::kMaxUsableSectors is %zu sectors larger than needed",
Wyatt Hepler1c329ca2020-02-07 18:07:23 -080057 kMaxUsableSectors - sectors_.size());
Wyatt Heplerad0a7932020-02-06 08:20:38 -080058 }
59
Keir Mierle8c352dc2020-02-02 13:58:19 -080060 // Reset the number of occupied key descriptors; we will fill them later.
Wyatt Hepler1c329ca2020-02-07 18:07:23 -080061 key_descriptors_.clear();
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -080062
David Rogers8ce55cd2020-02-04 19:41:48 -080063 // TODO: init last_new_sector_ to a random sector. Since the on-flash stored
64 // information does not allow recovering the previous last_new_sector_ after
65 // clean start, random is a good second choice.
66
Keir Mierle8c352dc2020-02-02 13:58:19 -080067 const size_t sector_size_bytes = partition_.sector_size_bytes();
Keir Mierle8c352dc2020-02-02 13:58:19 -080068
David Rogersf0a35442020-02-04 12:16:38 -080069 if (working_buffer_.size() < sector_size_bytes) {
Wyatt Heplere541e072020-02-14 09:10:53 -080070 CRT("working_buffer_ (%zu bytes) is smaller than sector size (%zu bytes)",
David Rogersf0a35442020-02-04 12:16:38 -080071 working_buffer_.size(),
72 sector_size_bytes);
73 return Status::INVALID_ARGUMENT;
74 }
75
Keir Mierle8c352dc2020-02-02 13:58:19 -080076 DBG("First pass: Read all entries from all sectors");
Wyatt Hepler1c329ca2020-02-07 18:07:23 -080077 for (size_t sector_id = 0; sector_id < sectors_.size(); ++sector_id) {
Keir Mierle8c352dc2020-02-02 13:58:19 -080078 // Track writable bytes in this sector. Updated after reading each entry.
Wyatt Hepler1c329ca2020-02-07 18:07:23 -080079 sectors_[sector_id].tail_free_bytes = sector_size_bytes;
Keir Mierle8c352dc2020-02-02 13:58:19 -080080
81 const Address sector_address = sector_id * sector_size_bytes;
82 Address entry_address = sector_address;
83
84 for (int num_entries_in_sector = 0;; num_entries_in_sector++) {
85 DBG("Load entry: sector=%zu, entry#=%d, address=%zu",
86 sector_id,
87 num_entries_in_sector,
88 size_t(entry_address));
89
Wyatt Hepler1c329ca2020-02-07 18:07:23 -080090 if (!AddressInSector(sectors_[sector_id], entry_address)) {
Keir Mierle8c352dc2020-02-02 13:58:19 -080091 DBG("Fell off end of sector; moving to the next sector");
92 break;
93 }
94
95 Address next_entry_address;
96 Status status = LoadEntry(entry_address, &next_entry_address);
97 if (status == Status::NOT_FOUND) {
98 DBG("Hit un-written data in sector; moving to the next sector");
99 break;
100 }
101 if (status == Status::DATA_LOSS) {
102 // It's not clear KVS can make a unilateral decision about what to do
103 // in corruption cases. It's an application decision, for which we
104 // should offer some configurability. For now, entirely bail out of
105 // loading and give up.
106 //
107 // Later, scan for remaining valid keys; since it's entirely possible
108 // that there is a duplicate of the key elsewhere and everything is
109 // fine. Later, we can wipe and maybe recover the sector.
110 //
111 // TODO: Implement rest-of-sector scanning for valid entries.
112 return Status::DATA_LOSS;
113 }
114 TRY(status);
115
116 // Entry loaded successfully; so get ready to load the next one.
117 entry_address = next_entry_address;
118
119 // Update of the number of writable bytes in this sector.
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800120 sectors_[sector_id].tail_free_bytes =
Keir Mierle8c352dc2020-02-02 13:58:19 -0800121 sector_size_bytes - (entry_address - sector_address);
122 }
123 }
124
125 DBG("Second pass: Count valid bytes in each sector");
126 // Initialize the sector sizes.
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800127 for (SectorDescriptor& sector : sectors_) {
128 sector.valid_bytes = 0;
Keir Mierle8c352dc2020-02-02 13:58:19 -0800129 }
130 // For every valid key, increment the valid bytes for that sector.
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800131 for (KeyDescriptor& key_descriptor : key_descriptors_) {
132 uint32_t sector_id = key_descriptor.address / sector_size_bytes;
Wyatt Heplere541e072020-02-14 09:10:53 -0800133 Entry entry;
134 TRY(Entry::Read(partition_, key_descriptor.address, &entry));
135 sectors_[sector_id].valid_bytes += entry.size();
Keir Mierle8c352dc2020-02-02 13:58:19 -0800136 }
Wyatt Hepler729f28c2020-02-05 09:46:00 -0800137 initialized_ = true;
Keir Mierle8c352dc2020-02-02 13:58:19 -0800138 return Status::OK;
139}
140
141Status KeyValueStore::LoadEntry(Address entry_address,
142 Address* next_entry_address) {
Wyatt Heplere541e072020-02-14 09:10:53 -0800143 Entry entry;
144 TRY(Entry::Read(partition_, entry_address, &entry));
Keir Mierle8c352dc2020-02-02 13:58:19 -0800145
146 // TODO: Handle multiple magics for formats that have changed.
Wyatt Heplere541e072020-02-14 09:10:53 -0800147 if (entry.magic() != entry_header_format_.magic) {
Keir Mierle8c352dc2020-02-02 13:58:19 -0800148 // TODO: It may be cleaner to have some logging helpers for these cases.
Wyatt Heplere541e072020-02-14 09:10:53 -0800149 ERR("Found corrupt magic: %zx; expecting %zx; at address %zx",
150 size_t(entry.magic()),
Keir Mierle8c352dc2020-02-02 13:58:19 -0800151 size_t(entry_header_format_.magic),
152 size_t(entry_address));
153 return Status::DATA_LOSS;
154 }
155
156 // Read the key from flash & validate the entry (which reads the value).
Wyatt Heplera00d1ef2020-02-14 14:31:26 -0800157 Entry::KeyBuffer key_buffer;
Wyatt Heplere541e072020-02-14 09:10:53 -0800158 TRY_ASSIGN(size_t key_length, entry.ReadKey(key_buffer));
159 const string_view key(key_buffer.data(), key_length);
Wyatt Heplerbab0e202020-02-04 07:40:08 -0800160
Wyatt Heplere541e072020-02-14 09:10:53 -0800161 TRY(entry.VerifyChecksumInFlash(entry_header_format_.checksum));
Wyatt Hepler4d78cd62020-02-05 13:05:58 -0800162
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800163 KeyDescriptor key_descriptor(
164 key,
Wyatt Heplere541e072020-02-14 09:10:53 -0800165 entry.key_version(),
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800166 entry_address,
Wyatt Heplere541e072020-02-14 09:10:53 -0800167 entry.deleted() ? KeyDescriptor::kDeleted : KeyDescriptor::kValid);
Keir Mierle8c352dc2020-02-02 13:58:19 -0800168
169 DBG("Key hash: %zx (%zu)",
170 size_t(key_descriptor.key_hash),
171 size_t(key_descriptor.key_hash));
172
173 TRY(AppendNewOrOverwriteStaleExistingDescriptor(key_descriptor));
174
Wyatt Heplere541e072020-02-14 09:10:53 -0800175 *next_entry_address = entry.next_address();
Keir Mierle8c352dc2020-02-02 13:58:19 -0800176 return Status::OK;
177}
178
179// TODO: This method is the trigger of the O(valid_entries * all_entries) time
180// complexity for reading. At some cost to memory, this could be optimized by
181// using a hash table instead of scanning, but in practice this should be fine
182// for a small number of keys
183Status KeyValueStore::AppendNewOrOverwriteStaleExistingDescriptor(
184 const KeyDescriptor& key_descriptor) {
185 // With the new key descriptor, either add it to the descriptor table or
186 // overwrite an existing entry with an older version of the key.
187 KeyDescriptor* existing_descriptor = FindDescriptor(key_descriptor.key_hash);
Keir Mierle8c352dc2020-02-02 13:58:19 -0800188
Wyatt Hepler5406a672020-02-18 15:42:38 -0800189 // Write a new entry.
190 if (existing_descriptor == nullptr) {
191 if (key_descriptors_.full()) {
192 return Status::RESOURCE_EXHAUSTED;
193 }
194 key_descriptors_.push_back(key_descriptor);
195 } else if (existing_descriptor->key_version < key_descriptor.key_version) {
196 // Existing entry is old; replace the existing entry with the new one.
197 *existing_descriptor = key_descriptor;
198 } else {
199 // Otherwise, check for data integrity and leave the existing entry.
200 if (existing_descriptor->key_version == key_descriptor.key_version) {
201 ERR("Data loss: Duplicated old(=%zu) and new(=%zu) version",
202 size_t(existing_descriptor->key_version),
203 size_t(key_descriptor.key_version));
204 return Status::DATA_LOSS;
205 }
206 DBG("Found stale entry when appending; ignoring");
Keir Mierle8c352dc2020-02-02 13:58:19 -0800207 }
Keir Mierle8c352dc2020-02-02 13:58:19 -0800208 return Status::OK;
209}
210
Keir Mierle8c352dc2020-02-02 13:58:19 -0800211KeyValueStore::KeyDescriptor* KeyValueStore::FindDescriptor(uint32_t hash) {
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800212 for (KeyDescriptor& key_descriptor : key_descriptors_) {
213 if (key_descriptor.key_hash == hash) {
214 return &key_descriptor;
Keir Mierle8c352dc2020-02-02 13:58:19 -0800215 }
216 }
217 return nullptr;
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800218}
219
220StatusWithSize KeyValueStore::Get(string_view key,
221 span<byte> value_buffer) const {
Wyatt Hepler50f70772020-02-13 11:25:10 -0800222 TRY_WITH_SIZE(CheckOperation(key));
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800223
David Rogers2761aeb2020-01-31 17:09:00 -0800224 const KeyDescriptor* key_descriptor;
Wyatt Hepler2d401692020-02-13 16:01:23 -0800225 TRY_WITH_SIZE(FindExistingKeyDescriptor(key, &key_descriptor));
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800226
Wyatt Heplere541e072020-02-14 09:10:53 -0800227 Entry entry;
228 TRY_WITH_SIZE(Entry::Read(partition_, key_descriptor->address, &entry));
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800229
Wyatt Heplere541e072020-02-14 09:10:53 -0800230 StatusWithSize result = entry.ReadValue(value_buffer);
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800231 if (result.ok() && options_.verify_on_read) {
David Rogerscf680ab2020-02-12 23:28:32 -0800232 Status verify_result =
Wyatt Heplere541e072020-02-14 09:10:53 -0800233 entry.VerifyChecksum(entry_header_format_.checksum,
234 key,
235 value_buffer.subspan(0, result.size()));
David Rogerscf680ab2020-02-12 23:28:32 -0800236 if (!verify_result.ok()) {
Wyatt Hepler50f70772020-02-13 11:25:10 -0800237 std::memset(
238 value_buffer.subspan(0, result.size()).data(), 0, result.size());
239 return StatusWithSize(verify_result);
David Rogerscf680ab2020-02-12 23:28:32 -0800240 }
241
242 return StatusWithSize(verify_result, result.size());
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800243 }
244 return result;
245}
246
247Status KeyValueStore::Put(string_view key, span<const byte> value) {
Keir Mierle8c352dc2020-02-02 13:58:19 -0800248 DBG("Writing key/value; key length=%zu, value length=%zu",
249 key.size(),
250 value.size());
Wyatt Hepler729f28c2020-02-05 09:46:00 -0800251
252 TRY(CheckOperation(key));
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800253
Wyatt Hepler5406a672020-02-18 15:42:38 -0800254 if (Entry::size(partition_, key, value) > partition_.sector_size_bytes()) {
255 DBG("%zu B value with %zu B key cannot fit in one sector",
256 value.size(),
257 key.size());
258 return Status::INVALID_ARGUMENT;
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800259 }
260
David Rogers2761aeb2020-01-31 17:09:00 -0800261 KeyDescriptor* key_descriptor;
Wyatt Hepler2d401692020-02-13 16:01:23 -0800262 Status status = FindKeyDescriptor(key, &key_descriptor);
263
264 if (status.ok()) {
David Rogers3464d0a2020-02-07 11:45:46 -0800265 DBG("Writing over existing entry for key 0x%08" PRIx32 " in sector %zu",
266 key_descriptor->key_hash,
267 SectorIndex(SectorFromAddress(key_descriptor->address)));
Wyatt Hepler5a33d8c2020-02-06 09:32:58 -0800268 return WriteEntryForExistingKey(
269 key_descriptor, KeyDescriptor::kValid, key, value);
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800270 }
David Rogers2761aeb2020-01-31 17:09:00 -0800271
Wyatt Hepler2d401692020-02-13 16:01:23 -0800272 if (status == Status::NOT_FOUND) {
273 return WriteEntryForNewKey(key, value);
274 }
275
276 return status;
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800277}
278
279Status KeyValueStore::Delete(string_view key) {
Wyatt Hepler729f28c2020-02-05 09:46:00 -0800280 TRY(CheckOperation(key));
281
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800282 KeyDescriptor* key_descriptor;
Wyatt Hepler2d401692020-02-13 16:01:23 -0800283 TRY(FindExistingKeyDescriptor(key, &key_descriptor));
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800284
David Rogers3464d0a2020-02-07 11:45:46 -0800285 DBG("Writing tombstone for existing key 0x%08" PRIx32 " in sector %zu",
286 key_descriptor->key_hash,
287 SectorIndex(SectorFromAddress(key_descriptor->address)));
Wyatt Hepler5a33d8c2020-02-06 09:32:58 -0800288 return WriteEntryForExistingKey(
289 key_descriptor, KeyDescriptor::kDeleted, key, {});
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800290}
291
292KeyValueStore::iterator& KeyValueStore::iterator::operator++() {
293 // Skip to the next entry that is valid (not deleted).
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800294 while (++index_ < item_.kvs_.key_descriptors_.size() &&
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800295 descriptor().deleted()) {
296 }
297 return *this;
298}
299
300const KeyValueStore::Item& KeyValueStore::iterator::operator*() {
301 std::memset(item_.key_buffer_.data(), 0, item_.key_buffer_.size());
302
Wyatt Heplere541e072020-02-14 09:10:53 -0800303 Entry entry;
304 if (Entry::Read(item_.kvs_.partition_, descriptor().address, &entry).ok()) {
305 entry.ReadKey(item_.key_buffer_);
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800306 }
307
308 return item_;
309}
310
311KeyValueStore::iterator KeyValueStore::begin() const {
312 size_t i = 0;
313 // Skip over any deleted entries at the start of the descriptor list.
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800314 while (i < key_descriptors_.size() && key_descriptors_[i].deleted()) {
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800315 i += 1;
316 }
317 return iterator(*this, i);
318}
319
320// TODO(hepler): The valid entry count could be tracked in the KVS to avoid the
321// need for this for-loop.
322size_t KeyValueStore::size() const {
323 size_t valid_entries = 0;
324
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800325 for (const KeyDescriptor& key_descriptor : key_descriptors_) {
326 if (!key_descriptor.deleted()) {
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800327 valid_entries += 1;
328 }
329 }
330
331 return valid_entries;
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800332}
333
Wyatt Heplered163b02020-02-03 17:49:32 -0800334StatusWithSize KeyValueStore::ValueSize(std::string_view key) const {
Wyatt Hepler50f70772020-02-13 11:25:10 -0800335 TRY_WITH_SIZE(CheckOperation(key));
Wyatt Heplered163b02020-02-03 17:49:32 -0800336
337 const KeyDescriptor* key_descriptor;
Wyatt Hepler2d401692020-02-13 16:01:23 -0800338 TRY_WITH_SIZE(FindExistingKeyDescriptor(key, &key_descriptor));
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800339
Wyatt Heplere541e072020-02-14 09:10:53 -0800340 Entry entry;
341 TRY_WITH_SIZE(Entry::Read(partition_, key_descriptor->address, &entry));
Wyatt Heplered163b02020-02-03 17:49:32 -0800342
Wyatt Heplere541e072020-02-14 09:10:53 -0800343 return StatusWithSize(entry.value_size());
Wyatt Heplered163b02020-02-03 17:49:32 -0800344}
345
Wyatt Hepler4d78cd62020-02-05 13:05:58 -0800346uint32_t KeyValueStore::HashKey(string_view string) {
347 uint32_t hash = 0;
348 uint32_t coefficient = 65599u;
349
350 for (char ch : string) {
351 hash += coefficient * unsigned(ch);
352 coefficient *= 65599u;
353 }
354
355 return hash;
356}
357
Wyatt Hepler6e3a83b2020-02-04 07:36:45 -0800358Status KeyValueStore::FixedSizeGet(std::string_view key,
359 byte* value,
360 size_t size_bytes) const {
361 // Ensure that the size of the stored value matches the size of the type.
362 // Otherwise, report error. This check avoids potential memory corruption.
363 StatusWithSize result = ValueSize(key);
364 if (!result.ok()) {
365 return result.status();
Keir Mierle8c352dc2020-02-02 13:58:19 -0800366 }
Wyatt Hepler6e3a83b2020-02-04 07:36:45 -0800367 if (result.size() != size_bytes) {
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800368 DBG("Requested %zu B read, but value is %zu B", size_bytes, result.size());
Wyatt Hepler6e3a83b2020-02-04 07:36:45 -0800369 return Status::INVALID_ARGUMENT;
Wyatt Heplerbab0e202020-02-04 07:40:08 -0800370 }
Wyatt Hepler6e3a83b2020-02-04 07:36:45 -0800371 return Get(key, span(value, size_bytes)).status();
Keir Mierle8c352dc2020-02-02 13:58:19 -0800372}
373
Wyatt Hepler729f28c2020-02-05 09:46:00 -0800374Status KeyValueStore::CheckOperation(string_view key) const {
Wyatt Hepleracaacf92020-01-24 10:58:30 -0800375 if (InvalidKey(key)) {
Wyatt Heplerb7609542020-01-24 10:29:54 -0800376 return Status::INVALID_ARGUMENT;
377 }
Wyatt Hepler729f28c2020-02-05 09:46:00 -0800378 if (!initialized_) {
Wyatt Heplerb7609542020-01-24 10:29:54 -0800379 return Status::FAILED_PRECONDITION;
380 }
Wyatt Heplerb7609542020-01-24 10:29:54 -0800381 return Status::OK;
382}
383
Wyatt Hepler2d401692020-02-13 16:01:23 -0800384// Searches for a KeyDescriptor that matches this key and sets *result to point
385// to it if one is found.
386//
387// OK: there is a matching descriptor and *result is set
388// NOT_FOUND: there is no descriptor that matches this key, but this key
389// has a unique hash (and could potentially be added to the KVS)
390// ALREADY_EXISTS: there is no descriptor that matches this key, but the
391// key's hash collides with the hash for an existing descriptor
392//
David Rogers2761aeb2020-01-31 17:09:00 -0800393Status KeyValueStore::FindKeyDescriptor(string_view key,
394 const KeyDescriptor** result) const {
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800395 const uint32_t hash = HashKey(key);
Wyatt Heplera00d1ef2020-02-14 14:31:26 -0800396 Entry::KeyBuffer key_buffer;
Wyatt Heplerb7609542020-01-24 10:29:54 -0800397
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800398 for (auto& descriptor : key_descriptors_) {
David Rogers2761aeb2020-01-31 17:09:00 -0800399 if (descriptor.key_hash == hash) {
Wyatt Heplere541e072020-02-14 09:10:53 -0800400 TRY(Entry::ReadKey(
Wyatt Heplera00d1ef2020-02-14 14:31:26 -0800401 partition_, descriptor.address, key.size(), key_buffer.data()));
Wyatt Heplerb7609542020-01-24 10:29:54 -0800402
Wyatt Heplere541e072020-02-14 09:10:53 -0800403 if (key == string_view(key_buffer.data(), key.size())) {
Wyatt Hepler5a33d8c2020-02-06 09:32:58 -0800404 DBG("Found match for key hash 0x%08" PRIx32, hash);
David Rogers2761aeb2020-01-31 17:09:00 -0800405 *result = &descriptor;
Wyatt Heplerb7609542020-01-24 10:29:54 -0800406 return Status::OK;
Wyatt Hepler2d401692020-02-13 16:01:23 -0800407 } else {
408 WRN("Found key hash collision for 0x%08" PRIx32, hash);
409 return Status::ALREADY_EXISTS;
Wyatt Heplerb7609542020-01-24 10:29:54 -0800410 }
Wyatt Heplerb7609542020-01-24 10:29:54 -0800411 }
412 }
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800413 return Status::NOT_FOUND;
414}
415
Wyatt Hepler2d401692020-02-13 16:01:23 -0800416// Searches for a KeyDescriptor that matches this key and sets *result to point
417// to it if one is found.
418//
419// OK: there is a matching descriptor and *result is set
420// NOT_FOUND: there is no descriptor that matches this key
421//
422Status KeyValueStore::FindExistingKeyDescriptor(
423 string_view key, const KeyDescriptor** result) const {
424 Status status = FindKeyDescriptor(key, result);
425
426 // If the key's hash collides with an existing key or if the key is deleted,
427 // treat it as if it is not in the KVS.
428 if (status == Status::ALREADY_EXISTS ||
429 (status.ok() && (*result)->deleted())) {
430 return Status::NOT_FOUND;
431 }
432 return status;
433}
434
David Rogers2761aeb2020-01-31 17:09:00 -0800435Status KeyValueStore::WriteEntryForExistingKey(KeyDescriptor* key_descriptor,
Wyatt Hepler5a33d8c2020-02-06 09:32:58 -0800436 KeyDescriptor::State new_state,
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800437 string_view key,
438 span<const byte> value) {
Wyatt Hepler5a33d8c2020-02-06 09:32:58 -0800439 // Find the original entry and sector to update the sector's valid_bytes.
Wyatt Hepler30a52152020-02-12 11:26:05 -0800440 Entry original_entry;
Wyatt Heplere541e072020-02-14 09:10:53 -0800441 TRY(Entry::Read(partition_, key_descriptor->address, &original_entry));
David Rogers3464d0a2020-02-07 11:45:46 -0800442 SectorDescriptor* old_sector = SectorFromAddress(key_descriptor->address);
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800443
David Rogers2761aeb2020-01-31 17:09:00 -0800444 SectorDescriptor* sector;
Wyatt Hepler5406a672020-02-18 15:42:38 -0800445 TRY(FindOrRecoverSectorWithSpace(&sector,
446 Entry::size(partition_, key, value)));
David Rogers8ce55cd2020-02-04 19:41:48 -0800447 DBG("Writing existing entry; found sector: %zu", SectorIndex(sector));
David Rogers3464d0a2020-02-07 11:45:46 -0800448
449 if (old_sector != SectorFromAddress(key_descriptor->address)) {
450 DBG("Sector for old entry (size %zu) was garbage collected. Old entry "
451 "relocated to sector %zu",
452 original_entry.size(),
453 SectorIndex(SectorFromAddress(key_descriptor->address)));
454
455 old_sector = SectorFromAddress(key_descriptor->address);
456 }
457
Wyatt Hepler5a33d8c2020-02-06 09:32:58 -0800458 TRY(AppendEntry(sector, key_descriptor, key, value, new_state));
459
David Rogers3464d0a2020-02-07 11:45:46 -0800460 old_sector->RemoveValidBytes(original_entry.size());
Wyatt Hepler5a33d8c2020-02-06 09:32:58 -0800461 return Status::OK;
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800462}
463
464Status KeyValueStore::WriteEntryForNewKey(string_view key,
465 span<const byte> value) {
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800466 if (key_descriptors_.full()) {
Keir Mierle8c352dc2020-02-02 13:58:19 -0800467 WRN("KVS full: trying to store a new entry, but can't. Have %zu entries",
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800468 key_descriptors_.size());
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800469 return Status::RESOURCE_EXHAUSTED;
470 }
471
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800472 // Create the KeyDescriptor that will be added to the list. The version and
473 // address will be set by AppendEntry.
474 KeyDescriptor key_descriptor(key, 0, 0);
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800475
David Rogers2761aeb2020-01-31 17:09:00 -0800476 SectorDescriptor* sector;
Wyatt Hepler5406a672020-02-18 15:42:38 -0800477 TRY(FindOrRecoverSectorWithSpace(&sector,
478 Entry::size(partition_, key, value)));
David Rogers8ce55cd2020-02-04 19:41:48 -0800479 DBG("Writing new entry; found sector: %zu", SectorIndex(sector));
Wyatt Hepler0af6ad92020-02-13 15:54:46 -0800480 TRY(AppendEntry(sector, &key_descriptor, key, value, KeyDescriptor::kValid));
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800481
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800482 // Only add the entry when we are certain the write succeeded.
483 key_descriptors_.push_back(key_descriptor);
Wyatt Heplerb7609542020-01-24 10:29:54 -0800484 return Status::OK;
485}
486
David Rogers2761aeb2020-01-31 17:09:00 -0800487Status KeyValueStore::RelocateEntry(KeyDescriptor& key_descriptor) {
David Rogersf0a35442020-02-04 12:16:38 -0800488 struct TempEntry {
Wyatt Heplere541e072020-02-14 09:10:53 -0800489 Entry::KeyBuffer key;
David Rogersf0a35442020-02-04 12:16:38 -0800490 std::array<char, sizeof(working_buffer_) - sizeof(key)> value;
491 };
Wyatt Heplere541e072020-02-14 09:10:53 -0800492 TempEntry* temp_entry = reinterpret_cast<TempEntry*>(working_buffer_.data());
David Rogersf0a35442020-02-04 12:16:38 -0800493
David Rogersdf025cd2020-02-06 17:05:34 -0800494 DBG("Relocating entry"); // TODO: add entry info to the log statement.
495
Wyatt Heplere541e072020-02-14 09:10:53 -0800496 // Read the entry to be relocated. Store the entry in a local variable and
David Rogersf0a35442020-02-04 12:16:38 -0800497 // store the key and value in the TempEntry stored in the static allocated
498 // working_buffer_.
Wyatt Heplere541e072020-02-14 09:10:53 -0800499 Entry entry;
500 TRY(Entry::Read(partition_, key_descriptor.address, &entry));
501 TRY_ASSIGN(size_t key_length, entry.ReadKey(temp_entry->key));
502 string_view key = string_view(temp_entry->key.data(), key_length);
503 auto result = entry.ReadValue(as_writable_bytes(span(temp_entry->value)));
David Rogersf0a35442020-02-04 12:16:38 -0800504 if (!result.status().ok()) {
505 return Status::INTERNAL;
506 }
507
Wyatt Heplere541e072020-02-14 09:10:53 -0800508 auto value = span(temp_entry->value.data(), result.size());
509 TRY(entry.VerifyChecksum(
David Rogersf0a35442020-02-04 12:16:38 -0800510 entry_header_format_.checksum, key, as_bytes(value)));
511
David Rogers3464d0a2020-02-07 11:45:46 -0800512 SectorDescriptor* old_sector = SectorFromAddress(key_descriptor.address);
David Rogersf0a35442020-02-04 12:16:38 -0800513
514 // Find a new sector for the entry and write it to the new location.
David Rogers8ce55cd2020-02-04 19:41:48 -0800515 SectorDescriptor* new_sector;
Wyatt Heplere541e072020-02-14 09:10:53 -0800516 TRY(FindSectorWithSpace(&new_sector, entry.size(), old_sector, true));
Wyatt Hepler0af6ad92020-02-13 15:54:46 -0800517 TRY(AppendEntry(
518 new_sector, &key_descriptor, key, as_bytes(value), key_descriptor.state));
David Rogersdf025cd2020-02-06 17:05:34 -0800519
520 // Do the valid bytes accounting for the sector the entry was relocated out
521 // of.
Wyatt Heplere541e072020-02-14 09:10:53 -0800522 old_sector->RemoveValidBytes(entry.size());
David Rogersdf025cd2020-02-06 17:05:34 -0800523
524 return Status::OK;
David Rogersa12786b2020-01-31 16:02:33 -0800525}
526
David Rogers8db5a722020-02-03 18:28:34 -0800527// Find either an existing sector with enough space that is not the sector to
528// skip, or an empty sector. Maintains the invariant that there is always at
529// least 1 empty sector unless set to bypass the rule.
Wyatt Hepler5a33d8c2020-02-06 09:32:58 -0800530Status KeyValueStore::FindSectorWithSpace(
531 SectorDescriptor** found_sector,
532 size_t size,
533 const SectorDescriptor* sector_to_skip,
534 bool bypass_empty_sector_rule) {
David Rogers8ce55cd2020-02-04 19:41:48 -0800535 // The last_new_sector_ is the sector that was last selected as the "new empty
536 // sector" to write to. This last new sector is used as the starting point for
537 // the next "find a new empty sector to write to" operation. By using the last
538 // new sector as the start point we will cycle which empty sector is selected
539 // next, spreading the wear across all the empty sectors and get a wear
540 // leveling benefit, rather than putting more wear on the lower number
541 // sectors.
542 //
543 // Locally use the sector index for ease of iterating through the sectors. For
544 // the persistent storage use SectorDescriptor* rather than sector index
545 // because SectorDescriptor* is the standard way to identify a sector.
546 size_t last_new_sector_index_ = SectorIndex(last_new_sector_);
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800547 size_t start = (last_new_sector_index_ + 1) % sectors_.size();
David Rogers2761aeb2020-01-31 17:09:00 -0800548 SectorDescriptor* first_empty_sector = nullptr;
David Rogers8db5a722020-02-03 18:28:34 -0800549 bool at_least_two_empty_sectors = bypass_empty_sector_rule;
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800550
David Rogers67f4b6c2020-02-06 16:17:09 -0800551 DBG("Find sector with %zu bytes available", size);
552 if (sector_to_skip != nullptr) {
553 DBG(" Skip sector %zu", SectorIndex(sector_to_skip));
554 }
555 if (bypass_empty_sector_rule) {
556 DBG(" Bypassing empty sector rule");
557 }
558
David Rogers8ce55cd2020-02-04 19:41:48 -0800559 // Look for a partial sector to use with enough space. Immediately use the
560 // first one of those that is found. While scanning for a partial sector, keep
561 // track of the first empty sector and if a second sector was seen.
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800562 for (size_t j = 0; j < sectors_.size(); j++) {
563 size_t i = (j + start) % sectors_.size();
564 SectorDescriptor& sector = sectors_[i];
Keir Mierle8c352dc2020-02-02 13:58:19 -0800565
David Rogers8db5a722020-02-03 18:28:34 -0800566 if (sector_to_skip == &sector) {
David Rogers67f4b6c2020-02-06 16:17:09 -0800567 DBG(" Skipping the skip sector %zu", i);
David Rogers8db5a722020-02-03 18:28:34 -0800568 continue;
569 }
570
David Rogers67f4b6c2020-02-06 16:17:09 -0800571 DBG(" Examining sector %zu with %hu bytes available",
572 i,
573 sector.tail_free_bytes);
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800574 if (!SectorEmpty(sector) && sector.HasSpace(size)) {
David Rogers67f4b6c2020-02-06 16:17:09 -0800575 DBG(" Partially occupied sector %zu with enough space; done!", i);
David Rogers8ce55cd2020-02-04 19:41:48 -0800576 *found_sector = &sector;
577 return Status::OK;
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800578 }
579
580 if (SectorEmpty(sector)) {
581 if (first_empty_sector == nullptr) {
582 first_empty_sector = &sector;
583 } else {
584 at_least_two_empty_sectors = true;
Wyatt Hepler2ad60672020-01-21 08:00:16 -0800585 }
Wyatt Heplerb7609542020-01-24 10:29:54 -0800586 }
587 }
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800588
David Rogers8ce55cd2020-02-04 19:41:48 -0800589 // If the scan for a partial sector does not find a suitable sector, use the
590 // first empty sector that was found. Normally it is required to keep 1 empty
591 // sector after the sector found here, but that rule can be bypassed in
592 // special circumstances (such as during garbage collection).
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800593 if (at_least_two_empty_sectors) {
David Rogers67f4b6c2020-02-06 16:17:09 -0800594 DBG(" Found a usable empty sector; returning the first found (%zu)",
David Rogers8ce55cd2020-02-04 19:41:48 -0800595 SectorIndex(first_empty_sector));
596 last_new_sector_ = first_empty_sector;
597 *found_sector = first_empty_sector;
598 return Status::OK;
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800599 }
David Rogers8ce55cd2020-02-04 19:41:48 -0800600
601 // No sector was found.
David Rogers67f4b6c2020-02-06 16:17:09 -0800602 DBG(" Unable to find a usable sector");
David Rogers8ce55cd2020-02-04 19:41:48 -0800603 *found_sector = nullptr;
604 return Status::RESOURCE_EXHAUSTED;
Wyatt Heplerb7609542020-01-24 10:29:54 -0800605}
606
David Rogers2761aeb2020-01-31 17:09:00 -0800607Status KeyValueStore::FindOrRecoverSectorWithSpace(SectorDescriptor** sector,
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800608 size_t size) {
David Rogers8ce55cd2020-02-04 19:41:48 -0800609 Status result = FindSectorWithSpace(sector, size);
Wyatt Hepler2d401692020-02-13 16:01:23 -0800610 if (result == Status::RESOURCE_EXHAUSTED && options_.partial_gc_on_write) {
David Rogers1541d612020-02-06 23:47:02 -0800611 // Garbage collect and then try again to find the best sector.
612 TRY(GarbageCollectOneSector());
613 return FindSectorWithSpace(sector, size);
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800614 }
David Rogers8ce55cd2020-02-04 19:41:48 -0800615 return result;
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800616}
617
David Rogers2761aeb2020-01-31 17:09:00 -0800618KeyValueStore::SectorDescriptor* KeyValueStore::FindSectorToGarbageCollect() {
619 SectorDescriptor* sector_candidate = nullptr;
David Rogersa12786b2020-01-31 16:02:33 -0800620 size_t candidate_bytes = 0;
621
622 // Step 1: Try to find a sectors with stale keys and no valid keys (no
623 // relocation needed). If any such sectors are found, use the sector with the
624 // most reclaimable bytes.
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800625 for (auto& sector : sectors_) {
David Rogersa12786b2020-01-31 16:02:33 -0800626 if ((sector.valid_bytes == 0) &&
627 (RecoverableBytes(sector) > candidate_bytes)) {
628 sector_candidate = &sector;
629 candidate_bytes = RecoverableBytes(sector);
630 }
631 }
632
633 // Step 2: If step 1 yields no sectors, just find the sector with the most
634 // reclaimable bytes.
635 if (sector_candidate == nullptr) {
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800636 for (auto& sector : sectors_) {
David Rogersa12786b2020-01-31 16:02:33 -0800637 if (RecoverableBytes(sector) > candidate_bytes) {
638 sector_candidate = &sector;
639 candidate_bytes = RecoverableBytes(sector);
640 }
641 }
642 }
643
David Rogers5981f312020-02-13 13:33:56 -0800644 if (sector_candidate != nullptr) {
645 DBG("Found sector %zu to Garbage Collect, %zu recoverable bytes",
646 SectorIndex(sector_candidate),
647 RecoverableBytes(*sector_candidate));
648 } else {
649 DBG("Unable to find sector to garbage collect!");
650 }
David Rogersa12786b2020-01-31 16:02:33 -0800651 return sector_candidate;
652}
653
David Rogers1541d612020-02-06 23:47:02 -0800654Status KeyValueStore::GarbageCollectOneSector() {
David Rogers67f4b6c2020-02-06 16:17:09 -0800655 DBG("Garbage Collect a single sector");
656
David Rogersa12786b2020-01-31 16:02:33 -0800657 // Step 1: Find the sector to garbage collect
David Rogers2761aeb2020-01-31 17:09:00 -0800658 SectorDescriptor* sector_to_gc = FindSectorToGarbageCollect();
David Rogers3464d0a2020-02-07 11:45:46 -0800659 LogSectors();
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800660
David Rogersa12786b2020-01-31 16:02:33 -0800661 if (sector_to_gc == nullptr) {
662 return Status::RESOURCE_EXHAUSTED;
663 }
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800664
David Rogersa12786b2020-01-31 16:02:33 -0800665 // Step 2: Move any valid entries in the GC sector to other sectors
666 if (sector_to_gc->valid_bytes != 0) {
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800667 for (auto& descriptor : key_descriptors_) {
David Rogers2761aeb2020-01-31 17:09:00 -0800668 if (AddressInSector(*sector_to_gc, descriptor.address)) {
David Rogers67f4b6c2020-02-06 16:17:09 -0800669 DBG(" Relocate entry");
David Rogers2761aeb2020-01-31 17:09:00 -0800670 TRY(RelocateEntry(descriptor));
David Rogersa12786b2020-01-31 16:02:33 -0800671 }
Wyatt Heplerb7609542020-01-24 10:29:54 -0800672 }
673 }
Wyatt Heplerb7609542020-01-24 10:29:54 -0800674
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800675 if (sector_to_gc->valid_bytes != 0) {
David Rogers67f4b6c2020-02-06 16:17:09 -0800676 ERR(" Failed to relocate valid entries from sector being garbage "
677 "collected, %hu valid bytes remain",
678 sector_to_gc->valid_bytes);
Wyatt Heplerb7609542020-01-24 10:29:54 -0800679 return Status::INTERNAL;
680 }
681
David Rogersa12786b2020-01-31 16:02:33 -0800682 // Step 3: Reinitialize the sector
683 sector_to_gc->tail_free_bytes = 0;
684 TRY(partition_.Erase(SectorBaseAddress(sector_to_gc), 1));
685 sector_to_gc->tail_free_bytes = partition_.sector_size_bytes();
Wyatt Heplerb7609542020-01-24 10:29:54 -0800686
David Rogers67f4b6c2020-02-06 16:17:09 -0800687 DBG(" Garbage Collect complete");
David Rogers50185ad2020-02-07 00:02:46 -0800688 LogSectors();
David Rogersa12786b2020-01-31 16:02:33 -0800689 return Status::OK;
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800690}
691
David Rogers2761aeb2020-01-31 17:09:00 -0800692Status KeyValueStore::AppendEntry(SectorDescriptor* sector,
693 KeyDescriptor* key_descriptor,
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800694 const string_view key,
Wyatt Hepler5a33d8c2020-02-06 09:32:58 -0800695 span<const byte> value,
696 KeyDescriptor::State new_state) {
Wyatt Heplere541e072020-02-14 09:10:53 -0800697 const Address address = NextWritableAddress(sector);
698 DBG("Appending to address: %#zx", size_t(address));
699
700 Entry entry;
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800701
Wyatt Hepler5a33d8c2020-02-06 09:32:58 -0800702 if (new_state == KeyDescriptor::kDeleted) {
Wyatt Heplere541e072020-02-14 09:10:53 -0800703 entry = Entry::Tombstone(partition_,
704 address,
705 entry_header_format_.magic,
706 entry_header_format_.checksum,
707 key,
708 partition_.alignment_bytes(),
709 key_descriptor->key_version + 1);
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800710 } else {
Wyatt Heplere541e072020-02-14 09:10:53 -0800711 entry = Entry::Valid(partition_,
712 address,
713 entry_header_format_.magic,
714 entry_header_format_.checksum,
715 key,
716 value,
717 partition_.alignment_bytes(),
718 key_descriptor->key_version + 1);
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800719 }
720
Wyatt Hepler97fc7942020-02-06 15:55:45 -0800721 DBG("Appending %zu B entry with key version: %x",
Wyatt Heplere541e072020-02-14 09:10:53 -0800722 entry.size(),
723 unsigned(entry.key_version()));
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800724
Wyatt Heplere541e072020-02-14 09:10:53 -0800725 TRY_ASSIGN(const size_t written, entry.Write(key, value));
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800726
727 if (options_.verify_on_write) {
Wyatt Heplere541e072020-02-14 09:10:53 -0800728 TRY(entry.VerifyChecksumInFlash(entry_header_format_.checksum));
Wyatt Heplerb7609542020-01-24 10:29:54 -0800729 }
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800730
David Rogers2761aeb2020-01-31 17:09:00 -0800731 key_descriptor->address = address;
Wyatt Heplere541e072020-02-14 09:10:53 -0800732 key_descriptor->key_version = entry.key_version();
Wyatt Hepler5a33d8c2020-02-06 09:32:58 -0800733 key_descriptor->state = new_state;
734
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800735 sector->valid_bytes += written;
David Rogers2be76b02020-02-06 17:33:05 -0800736 sector->RemoveFreeBytes(written);
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800737 return Status::OK;
Wyatt Heplerb7609542020-01-24 10:29:54 -0800738}
739
Keir Mierle8c352dc2020-02-02 13:58:19 -0800740void KeyValueStore::LogDebugInfo() {
Keir Mierle8c352dc2020-02-02 13:58:19 -0800741 const size_t sector_size_bytes = partition_.sector_size_bytes();
742 DBG("====================== KEY VALUE STORE DUMP =========================");
743 DBG(" ");
744 DBG("Flash partition:");
Wyatt Heplerad0a7932020-02-06 08:20:38 -0800745 DBG(" Sector count = %zu", partition_.sector_count());
746 DBG(" Sector max count = %zu", kMaxUsableSectors);
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800747 DBG(" Sectors in use = %zu", sectors_.size());
Keir Mierle8c352dc2020-02-02 13:58:19 -0800748 DBG(" Sector size = %zu", sector_size_bytes);
749 DBG(" Total size = %zu", partition_.size_bytes());
750 DBG(" Alignment = %zu", partition_.alignment_bytes());
751 DBG(" ");
752 DBG("Key descriptors:");
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800753 DBG(" Entry count = %zu", key_descriptors_.size());
Keir Mierle8c352dc2020-02-02 13:58:19 -0800754 DBG(" Max entry count = %zu", kMaxEntries);
755 DBG(" ");
756 DBG(" # hash version address address (hex)");
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800757 for (size_t i = 0; i < key_descriptors_.size(); ++i) {
758 const KeyDescriptor& kd = key_descriptors_[i];
Keir Mierle8c352dc2020-02-02 13:58:19 -0800759 DBG(" |%3zu: | %8zx |%8zu | %8zu | %8zx",
760 i,
761 size_t(kd.key_hash),
762 size_t(kd.key_version),
763 size_t(kd.address),
764 size_t(kd.address));
765 }
766 DBG(" ");
767
768 DBG("Sector descriptors:");
769 DBG(" # tail free valid has_space");
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800770 for (size_t sector_id = 0; sector_id < sectors_.size(); ++sector_id) {
771 const SectorDescriptor& sd = sectors_[sector_id];
Keir Mierle8c352dc2020-02-02 13:58:19 -0800772 DBG(" |%3zu: | %8zu |%8zu | %s",
773 sector_id,
774 size_t(sd.tail_free_bytes),
775 size_t(sd.valid_bytes),
776 sd.tail_free_bytes ? "YES" : "");
777 }
778 DBG(" ");
779
780 // TODO: This should stop logging after some threshold.
781 // size_t dumped_bytes = 0;
782 DBG("Sector raw data:");
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800783 for (size_t sector_id = 0; sector_id < sectors_.size(); ++sector_id) {
Keir Mierle8c352dc2020-02-02 13:58:19 -0800784 // Read sector data. Yes, this will blow the stack on embedded.
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800785 std::array<byte, 500> raw_sector_data; // TODO!!!
Keir Mierle8c352dc2020-02-02 13:58:19 -0800786 StatusWithSize sws =
787 partition_.Read(sector_id * sector_size_bytes, raw_sector_data);
788 DBG("Read: %zu bytes", sws.size());
789
790 DBG(" base addr offs 0 1 2 3 4 5 6 7");
791 for (size_t i = 0; i < sector_size_bytes; i += 8) {
792 DBG(" %3zu %8zx %5zu | %02x %02x %02x %02x %02x %02x %02x %02x",
793 sector_id,
794 (sector_id * sector_size_bytes) + i,
795 i,
796 static_cast<unsigned int>(raw_sector_data[i + 0]),
797 static_cast<unsigned int>(raw_sector_data[i + 1]),
798 static_cast<unsigned int>(raw_sector_data[i + 2]),
799 static_cast<unsigned int>(raw_sector_data[i + 3]),
800 static_cast<unsigned int>(raw_sector_data[i + 4]),
801 static_cast<unsigned int>(raw_sector_data[i + 5]),
802 static_cast<unsigned int>(raw_sector_data[i + 6]),
803 static_cast<unsigned int>(raw_sector_data[i + 7]));
804
805 // TODO: Fix exit condition.
806 if (i > 128) {
807 break;
808 }
809 }
810 DBG(" ");
811 }
812
813 DBG("////////////////////// KEY VALUE STORE DUMP END /////////////////////");
814}
815
David Rogerscf680ab2020-02-12 23:28:32 -0800816void KeyValueStore::LogSectors() const {
817 DBG("Sector descriptors: count %zu", sectors_.size());
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800818 for (auto& sector : sectors_) {
David Rogers50185ad2020-02-07 00:02:46 -0800819 DBG(" - Sector %zu: valid %hu, recoverable %zu, free %hu",
820 SectorIndex(&sector),
821 sector.valid_bytes,
822 RecoverableBytes(sector),
823 sector.tail_free_bytes);
824 }
825}
826
David Rogerscf680ab2020-02-12 23:28:32 -0800827void KeyValueStore::LogKeyDescriptor() const {
828 DBG("Key descriptors: count %zu", key_descriptors_.size());
829 for (auto& key : key_descriptors_) {
830 DBG(" - Key: %s, hash %#zx, version %zu, address %#zx",
831 key.deleted() ? "Deleted" : "Valid",
832 static_cast<size_t>(key.key_hash),
833 static_cast<size_t>(key.key_version),
834 static_cast<size_t>(key.address));
835 }
836}
837
David Rogers3464d0a2020-02-07 11:45:46 -0800838void KeyValueStore::SectorDescriptor::RemoveValidBytes(size_t size) {
839 // TODO: add safety check for valid_bytes > size.
840 if (size > valid_bytes) {
841 CRT("!!!!!!!!!!!!!!!");
842 CRT("Remove too many valid bytes!!! remove %zu, only have %hu",
843 size,
844 valid_bytes);
845 valid_bytes = size;
846 }
847 valid_bytes -= size;
848}
849
Wyatt Hepler2ad60672020-01-21 08:00:16 -0800850} // namespace pw::kvs