blob: 9949b88b51f7233699b4791be1b0a7872dd8019f [file] [log] [blame]
Wyatt Heplerb7609542020-01-24 10:29:54 -08001// Copyright 2020 The Pigweed Authors
2//
3// Licensed under the Apache License, Version 2.0 (the "License"); you may not
4// use this file except in compliance with the License. You may obtain a copy of
5// the License at
6//
7// https://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
11// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12// License for the specific language governing permissions and limitations under
13// the License.
14
Wyatt Heplerb7609542020-01-24 10:29:54 -080015#include "pw_kvs/key_value_store.h"
16
Wyatt Heplerbab0e202020-02-04 07:40:08 -080017#include <algorithm>
Wyatt Hepler5a33d8c2020-02-06 09:32:58 -080018#include <cinttypes>
Wyatt Heplerb7609542020-01-24 10:29:54 -080019#include <cstring>
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -080020#include <type_traits>
Wyatt Heplerb7609542020-01-24 10:29:54 -080021
Keir Mierle8c352dc2020-02-02 13:58:19 -080022#define PW_LOG_USE_ULTRA_SHORT_NAMES 1
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -080023#include "pw_kvs_private/format.h"
24#include "pw_kvs_private/macros.h"
Keir Mierle8c352dc2020-02-02 13:58:19 -080025#include "pw_log/log.h"
Wyatt Heplerb7609542020-01-24 10:29:54 -080026
Wyatt Hepler2ad60672020-01-21 08:00:16 -080027namespace pw::kvs {
Wyatt Heplerb7609542020-01-24 10:29:54 -080028
Wyatt Hepleracaacf92020-01-24 10:58:30 -080029using std::byte;
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -080030using std::string_view;
Wyatt Hepleracaacf92020-01-24 10:58:30 -080031
Wyatt Heplerad0a7932020-02-06 08:20:38 -080032KeyValueStore::KeyValueStore(FlashPartition* partition,
33 const EntryHeaderFormat& format,
34 const Options& options)
35 : partition_(*partition),
36 entry_header_format_(format),
37 options_(options),
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) {
64 CRT("ERROR: working_buffer_ (%zu bytes) is smaller than sector "
65 "size (%zu bytes)",
66 working_buffer_.size(),
67 sector_size_bytes);
68 return Status::INVALID_ARGUMENT;
69 }
70
Keir Mierle8c352dc2020-02-02 13:58:19 -080071 DBG("First pass: Read all entries from all sectors");
Wyatt Hepler1c329ca2020-02-07 18:07:23 -080072 for (size_t sector_id = 0; sector_id < sectors_.size(); ++sector_id) {
Keir Mierle8c352dc2020-02-02 13:58:19 -080073 // Track writable bytes in this sector. Updated after reading each entry.
Wyatt Hepler1c329ca2020-02-07 18:07:23 -080074 sectors_[sector_id].tail_free_bytes = sector_size_bytes;
Keir Mierle8c352dc2020-02-02 13:58:19 -080075
76 const Address sector_address = sector_id * sector_size_bytes;
77 Address entry_address = sector_address;
78
79 for (int num_entries_in_sector = 0;; num_entries_in_sector++) {
80 DBG("Load entry: sector=%zu, entry#=%d, address=%zu",
81 sector_id,
82 num_entries_in_sector,
83 size_t(entry_address));
84
Wyatt Hepler1c329ca2020-02-07 18:07:23 -080085 if (!AddressInSector(sectors_[sector_id], entry_address)) {
Keir Mierle8c352dc2020-02-02 13:58:19 -080086 DBG("Fell off end of sector; moving to the next sector");
87 break;
88 }
89
90 Address next_entry_address;
91 Status status = LoadEntry(entry_address, &next_entry_address);
92 if (status == Status::NOT_FOUND) {
93 DBG("Hit un-written data in sector; moving to the next sector");
94 break;
95 }
96 if (status == Status::DATA_LOSS) {
97 // It's not clear KVS can make a unilateral decision about what to do
98 // in corruption cases. It's an application decision, for which we
99 // should offer some configurability. For now, entirely bail out of
100 // loading and give up.
101 //
102 // Later, scan for remaining valid keys; since it's entirely possible
103 // that there is a duplicate of the key elsewhere and everything is
104 // fine. Later, we can wipe and maybe recover the sector.
105 //
106 // TODO: Implement rest-of-sector scanning for valid entries.
107 return Status::DATA_LOSS;
108 }
109 TRY(status);
110
111 // Entry loaded successfully; so get ready to load the next one.
112 entry_address = next_entry_address;
113
114 // Update of the number of writable bytes in this sector.
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800115 sectors_[sector_id].tail_free_bytes =
Keir Mierle8c352dc2020-02-02 13:58:19 -0800116 sector_size_bytes - (entry_address - sector_address);
117 }
118 }
119
120 DBG("Second pass: Count valid bytes in each sector");
121 // Initialize the sector sizes.
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800122 for (SectorDescriptor& sector : sectors_) {
123 sector.valid_bytes = 0;
Keir Mierle8c352dc2020-02-02 13:58:19 -0800124 }
125 // For every valid key, increment the valid bytes for that sector.
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800126 for (KeyDescriptor& key_descriptor : key_descriptors_) {
127 uint32_t sector_id = key_descriptor.address / sector_size_bytes;
Wyatt Hepler30a52152020-02-12 11:26:05 -0800128 Entry header;
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800129 TRY(ReadEntryHeader(key_descriptor.address, &header));
130 sectors_[sector_id].valid_bytes += header.size();
Keir Mierle8c352dc2020-02-02 13:58:19 -0800131 }
Wyatt Hepler729f28c2020-02-05 09:46:00 -0800132 initialized_ = true;
Keir Mierle8c352dc2020-02-02 13:58:19 -0800133 return Status::OK;
134}
135
136Status KeyValueStore::LoadEntry(Address entry_address,
137 Address* next_entry_address) {
Wyatt Hepler30a52152020-02-12 11:26:05 -0800138 Entry header;
Wyatt Hepler4d78cd62020-02-05 13:05:58 -0800139 TRY(ReadEntryHeader(entry_address, &header));
Keir Mierle8c352dc2020-02-02 13:58:19 -0800140 // TODO: Should likely add a "LogHeader" method or similar.
141 DBG("Header: ");
142 DBG(" Address = 0x%zx", size_t(entry_address));
143 DBG(" Magic = 0x%zx", size_t(header.magic()));
Wyatt Hepler6e3a83b2020-02-04 07:36:45 -0800144 DBG(" Checksum = 0x%zx", size_t(header.checksum()));
Keir Mierle8c352dc2020-02-02 13:58:19 -0800145 DBG(" Key length = 0x%zx", size_t(header.key_length()));
146 DBG(" Value length = 0x%zx", size_t(header.value_length()));
Wyatt Hepler93b889d2020-02-05 09:01:18 -0800147 DBG(" Entry size = 0x%zx", size_t(header.size()));
Wyatt Hepler116d1162020-02-06 09:42:59 -0800148 DBG(" Alignment = 0x%zx", size_t(header.alignment_bytes()));
Keir Mierle8c352dc2020-02-02 13:58:19 -0800149
150 if (HeaderLooksLikeUnwrittenData(header)) {
151 return Status::NOT_FOUND;
152 }
Keir Mierle8c352dc2020-02-02 13:58:19 -0800153
154 // TODO: Handle multiple magics for formats that have changed.
155 if (header.magic() != entry_header_format_.magic) {
156 // TODO: It may be cleaner to have some logging helpers for these cases.
157 CRT("Found corrupt magic: %zx; expecting %zx; at address %zx",
158 size_t(header.magic()),
159 size_t(entry_header_format_.magic),
160 size_t(entry_address));
161 return Status::DATA_LOSS;
162 }
163
164 // Read the key from flash & validate the entry (which reads the value).
165 KeyBuffer key_buffer;
Wyatt Hepler4d78cd62020-02-05 13:05:58 -0800166 TRY(ReadEntryKey(entry_address, header.key_length(), key_buffer.data()));
Wyatt Heplerbab0e202020-02-04 07:40:08 -0800167 const string_view key(key_buffer.data(), header.key_length());
168
Wyatt Hepler6e3a83b2020-02-04 07:36:45 -0800169 TRY(header.VerifyChecksumInFlash(
Wyatt Hepler4d78cd62020-02-05 13:05:58 -0800170 &partition_, entry_address, entry_header_format_.checksum));
171
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800172 KeyDescriptor key_descriptor(
173 key,
174 header.key_version(),
175 entry_address,
176 header.deleted() ? KeyDescriptor::kDeleted : KeyDescriptor::kValid);
Keir Mierle8c352dc2020-02-02 13:58:19 -0800177
178 DBG("Key hash: %zx (%zu)",
179 size_t(key_descriptor.key_hash),
180 size_t(key_descriptor.key_hash));
181
182 TRY(AppendNewOrOverwriteStaleExistingDescriptor(key_descriptor));
183
184 // TODO: Extract this to something like "NextValidEntryAddress".
Wyatt Hepler97fc7942020-02-06 15:55:45 -0800185 *next_entry_address = key_descriptor.address + header.size();
Keir Mierle8c352dc2020-02-02 13:58:19 -0800186
187 return Status::OK;
188}
189
190// TODO: This method is the trigger of the O(valid_entries * all_entries) time
191// complexity for reading. At some cost to memory, this could be optimized by
192// using a hash table instead of scanning, but in practice this should be fine
193// for a small number of keys
194Status KeyValueStore::AppendNewOrOverwriteStaleExistingDescriptor(
195 const KeyDescriptor& key_descriptor) {
196 // With the new key descriptor, either add it to the descriptor table or
197 // overwrite an existing entry with an older version of the key.
198 KeyDescriptor* existing_descriptor = FindDescriptor(key_descriptor.key_hash);
199 if (existing_descriptor) {
200 if (existing_descriptor->key_version < key_descriptor.key_version) {
201 // Existing entry is old; replace the existing entry with the new one.
202 *existing_descriptor = key_descriptor;
203 } else {
204 // Otherwise, check for data integrity and leave the existing entry.
205 if (existing_descriptor->key_version == key_descriptor.key_version) {
206 ERR("Data loss: Duplicated old(=%zu) and new(=%zu) version",
207 size_t(existing_descriptor->key_version),
208 size_t(key_descriptor.key_version));
209 return Status::DATA_LOSS;
210 }
211 DBG("Found stale entry when appending; ignoring");
212 }
213 return Status::OK;
214 }
215 // Write new entry.
216 KeyDescriptor* newly_allocated_key_descriptor;
217 TRY(AppendEmptyDescriptor(&newly_allocated_key_descriptor));
218 *newly_allocated_key_descriptor = key_descriptor;
219 return Status::OK;
220}
221
222// TODO: Need a better name.
223Status KeyValueStore::AppendEmptyDescriptor(KeyDescriptor** new_descriptor) {
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800224 if (key_descriptors_.full()) {
Keir Mierle8c352dc2020-02-02 13:58:19 -0800225 // TODO: Is this the right return code?
226 return Status::RESOURCE_EXHAUSTED;
227 }
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800228 key_descriptors_.emplace_back();
229 *new_descriptor = &key_descriptors_.back();
Keir Mierle8c352dc2020-02-02 13:58:19 -0800230 return Status::OK;
231}
232
233// TODO: Finish.
Wyatt Hepler30a52152020-02-12 11:26:05 -0800234bool KeyValueStore::HeaderLooksLikeUnwrittenData(const Entry& header) const {
Keir Mierle8c352dc2020-02-02 13:58:19 -0800235 // TODO: This is not correct; it should call through to flash memory.
236 return header.magic() == 0xffffffff;
237}
238
239KeyValueStore::KeyDescriptor* KeyValueStore::FindDescriptor(uint32_t hash) {
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800240 for (KeyDescriptor& key_descriptor : key_descriptors_) {
241 if (key_descriptor.key_hash == hash) {
242 return &key_descriptor;
Keir Mierle8c352dc2020-02-02 13:58:19 -0800243 }
244 }
245 return nullptr;
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800246}
247
248StatusWithSize KeyValueStore::Get(string_view key,
249 span<byte> value_buffer) const {
Wyatt Hepler729f28c2020-02-05 09:46:00 -0800250 TRY(CheckOperation(key));
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800251
David Rogers2761aeb2020-01-31 17:09:00 -0800252 const KeyDescriptor* key_descriptor;
253 TRY(FindKeyDescriptor(key, &key_descriptor));
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800254
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800255 if (key_descriptor->deleted()) {
256 return Status::NOT_FOUND;
257 }
258
Wyatt Hepler30a52152020-02-12 11:26:05 -0800259 Entry header;
Wyatt Hepler4d78cd62020-02-05 13:05:58 -0800260 TRY(ReadEntryHeader(key_descriptor->address, &header));
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800261
Keir Mierle8c352dc2020-02-02 13:58:19 -0800262 StatusWithSize result = ReadEntryValue(*key_descriptor, header, value_buffer);
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800263 if (result.ok() && options_.verify_on_read) {
David Rogerscf680ab2020-02-12 23:28:32 -0800264 Status verify_result =
265 header.VerifyChecksum(entry_header_format_.checksum,
266 key,
267 value_buffer.subspan(0, result.size()));
268 if (!verify_result.ok()) {
269 memset(value_buffer.subspan(0, result.size()).data(), 0, result.size());
270 return verify_result;
271 }
272
273 return StatusWithSize(verify_result, result.size());
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800274 }
275 return result;
276}
277
278Status KeyValueStore::Put(string_view key, span<const byte> value) {
Keir Mierle8c352dc2020-02-02 13:58:19 -0800279 DBG("Writing key/value; key length=%zu, value length=%zu",
280 key.size(),
281 value.size());
Wyatt Hepler729f28c2020-02-05 09:46:00 -0800282
283 TRY(CheckOperation(key));
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800284
285 if (value.size() > (1 << 24)) {
286 // TODO: Reject sizes that are larger than the maximum?
287 }
288
David Rogers2761aeb2020-01-31 17:09:00 -0800289 KeyDescriptor* key_descriptor;
290 if (FindKeyDescriptor(key, &key_descriptor).ok()) {
David Rogers3464d0a2020-02-07 11:45:46 -0800291 DBG("Writing over existing entry for key 0x%08" PRIx32 " in sector %zu",
292 key_descriptor->key_hash,
293 SectorIndex(SectorFromAddress(key_descriptor->address)));
Wyatt Hepler5a33d8c2020-02-06 09:32:58 -0800294 return WriteEntryForExistingKey(
295 key_descriptor, KeyDescriptor::kValid, key, value);
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800296 }
David Rogers2761aeb2020-01-31 17:09:00 -0800297
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800298 return WriteEntryForNewKey(key, value);
299}
300
301Status KeyValueStore::Delete(string_view key) {
Wyatt Hepler729f28c2020-02-05 09:46:00 -0800302 TRY(CheckOperation(key));
303
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800304 KeyDescriptor* key_descriptor;
305 TRY(FindKeyDescriptor(key, &key_descriptor));
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800306
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800307 if (key_descriptor->deleted()) {
308 return Status::NOT_FOUND;
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800309 }
310
David Rogers3464d0a2020-02-07 11:45:46 -0800311 DBG("Writing tombstone for existing key 0x%08" PRIx32 " in sector %zu",
312 key_descriptor->key_hash,
313 SectorIndex(SectorFromAddress(key_descriptor->address)));
Wyatt Hepler5a33d8c2020-02-06 09:32:58 -0800314 return WriteEntryForExistingKey(
315 key_descriptor, KeyDescriptor::kDeleted, key, {});
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800316}
317
318KeyValueStore::iterator& KeyValueStore::iterator::operator++() {
319 // Skip to the next entry that is valid (not deleted).
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800320 while (++index_ < item_.kvs_.key_descriptors_.size() &&
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800321 descriptor().deleted()) {
322 }
323 return *this;
324}
325
326const KeyValueStore::Item& KeyValueStore::iterator::operator*() {
327 std::memset(item_.key_buffer_.data(), 0, item_.key_buffer_.size());
328
Wyatt Hepler30a52152020-02-12 11:26:05 -0800329 Entry header;
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800330 if (item_.kvs_.ReadEntryHeader(descriptor().address, &header).ok()) {
331 item_.kvs_.ReadEntryKey(
332 descriptor().address, header.key_length(), item_.key_buffer_.data());
333 }
334
335 return item_;
336}
337
338KeyValueStore::iterator KeyValueStore::begin() const {
339 size_t i = 0;
340 // Skip over any deleted entries at the start of the descriptor list.
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800341 while (i < key_descriptors_.size() && key_descriptors_[i].deleted()) {
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800342 i += 1;
343 }
344 return iterator(*this, i);
345}
346
347// TODO(hepler): The valid entry count could be tracked in the KVS to avoid the
348// need for this for-loop.
349size_t KeyValueStore::size() const {
350 size_t valid_entries = 0;
351
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800352 for (const KeyDescriptor& key_descriptor : key_descriptors_) {
353 if (!key_descriptor.deleted()) {
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800354 valid_entries += 1;
355 }
356 }
357
358 return valid_entries;
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800359}
360
Wyatt Heplered163b02020-02-03 17:49:32 -0800361StatusWithSize KeyValueStore::ValueSize(std::string_view key) const {
Wyatt Hepler729f28c2020-02-05 09:46:00 -0800362 TRY(CheckOperation(key));
Wyatt Heplered163b02020-02-03 17:49:32 -0800363
364 const KeyDescriptor* key_descriptor;
365 TRY(FindKeyDescriptor(key, &key_descriptor));
366
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800367 if (key_descriptor->deleted()) {
368 return Status::NOT_FOUND;
369 }
370
Wyatt Hepler30a52152020-02-12 11:26:05 -0800371 Entry header;
Wyatt Hepler4d78cd62020-02-05 13:05:58 -0800372 TRY(ReadEntryHeader(key_descriptor->address, &header));
Wyatt Heplered163b02020-02-03 17:49:32 -0800373
374 return StatusWithSize(header.value_length());
375}
376
Wyatt Hepler4d78cd62020-02-05 13:05:58 -0800377uint32_t KeyValueStore::HashKey(string_view string) {
378 uint32_t hash = 0;
379 uint32_t coefficient = 65599u;
380
381 for (char ch : string) {
382 hash += coefficient * unsigned(ch);
383 coefficient *= 65599u;
384 }
385
386 return hash;
387}
388
Wyatt Hepler6e3a83b2020-02-04 07:36:45 -0800389Status KeyValueStore::FixedSizeGet(std::string_view key,
390 byte* value,
391 size_t size_bytes) const {
392 // Ensure that the size of the stored value matches the size of the type.
393 // Otherwise, report error. This check avoids potential memory corruption.
394 StatusWithSize result = ValueSize(key);
395 if (!result.ok()) {
396 return result.status();
Keir Mierle8c352dc2020-02-02 13:58:19 -0800397 }
Wyatt Hepler6e3a83b2020-02-04 07:36:45 -0800398 if (result.size() != size_bytes) {
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800399 DBG("Requested %zu B read, but value is %zu B", size_bytes, result.size());
Wyatt Hepler6e3a83b2020-02-04 07:36:45 -0800400 return Status::INVALID_ARGUMENT;
Wyatt Heplerbab0e202020-02-04 07:40:08 -0800401 }
Wyatt Hepler6e3a83b2020-02-04 07:36:45 -0800402 return Get(key, span(value, size_bytes)).status();
Keir Mierle8c352dc2020-02-02 13:58:19 -0800403}
404
Wyatt Hepler729f28c2020-02-05 09:46:00 -0800405Status KeyValueStore::CheckOperation(string_view key) const {
Wyatt Hepleracaacf92020-01-24 10:58:30 -0800406 if (InvalidKey(key)) {
Wyatt Heplerb7609542020-01-24 10:29:54 -0800407 return Status::INVALID_ARGUMENT;
408 }
Wyatt Hepler729f28c2020-02-05 09:46:00 -0800409 if (!initialized_) {
Wyatt Heplerb7609542020-01-24 10:29:54 -0800410 return Status::FAILED_PRECONDITION;
411 }
Wyatt Heplerb7609542020-01-24 10:29:54 -0800412 return Status::OK;
413}
414
David Rogers2761aeb2020-01-31 17:09:00 -0800415Status KeyValueStore::FindKeyDescriptor(string_view key,
416 const KeyDescriptor** result) const {
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800417 char key_buffer[kMaxKeyLength];
418 const uint32_t hash = HashKey(key);
Wyatt Heplerb7609542020-01-24 10:29:54 -0800419
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800420 for (auto& descriptor : key_descriptors_) {
David Rogers2761aeb2020-01-31 17:09:00 -0800421 if (descriptor.key_hash == hash) {
Wyatt Hepler4d78cd62020-02-05 13:05:58 -0800422 TRY(ReadEntryKey(descriptor.address, key.size(), key_buffer));
Wyatt Heplerb7609542020-01-24 10:29:54 -0800423
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800424 if (key == string_view(key_buffer, key.size())) {
Wyatt Hepler5a33d8c2020-02-06 09:32:58 -0800425 DBG("Found match for key hash 0x%08" PRIx32, hash);
David Rogers2761aeb2020-01-31 17:09:00 -0800426 *result = &descriptor;
Wyatt Heplerb7609542020-01-24 10:29:54 -0800427 return Status::OK;
428 }
Wyatt Heplerb7609542020-01-24 10:29:54 -0800429 }
430 }
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800431 return Status::NOT_FOUND;
432}
433
Wyatt Hepler30a52152020-02-12 11:26:05 -0800434Status KeyValueStore::ReadEntryHeader(Address address, Entry* header) const {
Wyatt Hepler4d78cd62020-02-05 13:05:58 -0800435 return partition_.Read(address, sizeof(*header), header).status();
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800436}
437
Wyatt Hepler4d78cd62020-02-05 13:05:58 -0800438Status KeyValueStore::ReadEntryKey(Address address,
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800439 size_t key_length,
440 char* key) const {
441 // TODO: This check probably shouldn't be here; this is like
442 // checking that the Cortex M's RAM isn't corrupt. This should be
443 // done at boot time.
Wyatt Hepler30a52152020-02-12 11:26:05 -0800444 // ^^ This argument sometimes comes from Entry::key_value_len,
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800445 // which is read directly from flash. If it's corrupted, we shouldn't try
446 // to read a bunch of extra data.
447 if (key_length == 0u || key_length > kMaxKeyLength) {
448 return Status::DATA_LOSS;
449 }
450 // The key is immediately after the entry header.
Wyatt Hepler4d78cd62020-02-05 13:05:58 -0800451 return partition_.Read(address + sizeof(EntryHeader), key_length, key)
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800452 .status();
453}
454
David Rogers2761aeb2020-01-31 17:09:00 -0800455StatusWithSize KeyValueStore::ReadEntryValue(
456 const KeyDescriptor& key_descriptor,
Wyatt Hepler30a52152020-02-12 11:26:05 -0800457 const Entry& header,
David Rogers2761aeb2020-01-31 17:09:00 -0800458 span<byte> value) const {
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800459 const size_t read_size = std::min(header.value_length(), value.size());
David Rogers2761aeb2020-01-31 17:09:00 -0800460 StatusWithSize result = partition_.Read(
461 key_descriptor.address + sizeof(header) + header.key_length(),
Keir Mierle8c352dc2020-02-02 13:58:19 -0800462 value.subspan(0, read_size));
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800463 TRY(result);
464 if (read_size != header.value_length()) {
465 return StatusWithSize(Status::RESOURCE_EXHAUSTED, read_size);
466 }
467 return StatusWithSize(read_size);
468}
469
David Rogers2761aeb2020-01-31 17:09:00 -0800470Status KeyValueStore::WriteEntryForExistingKey(KeyDescriptor* key_descriptor,
Wyatt Hepler5a33d8c2020-02-06 09:32:58 -0800471 KeyDescriptor::State new_state,
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800472 string_view key,
473 span<const byte> value) {
Wyatt Hepler5a33d8c2020-02-06 09:32:58 -0800474 // Find the original entry and sector to update the sector's valid_bytes.
Wyatt Hepler30a52152020-02-12 11:26:05 -0800475 Entry original_entry;
Wyatt Hepler5a33d8c2020-02-06 09:32:58 -0800476 TRY(ReadEntryHeader(key_descriptor->address, &original_entry));
David Rogers3464d0a2020-02-07 11:45:46 -0800477 SectorDescriptor* old_sector = SectorFromAddress(key_descriptor->address);
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800478
David Rogers2761aeb2020-01-31 17:09:00 -0800479 SectorDescriptor* sector;
Wyatt Hepler97fc7942020-02-06 15:55:45 -0800480 TRY(FindOrRecoverSectorWithSpace(
Wyatt Hepler30a52152020-02-12 11:26:05 -0800481 &sector, Entry::size(partition_.alignment_bytes(), key, value)));
David Rogers8ce55cd2020-02-04 19:41:48 -0800482 DBG("Writing existing entry; found sector: %zu", SectorIndex(sector));
David Rogers3464d0a2020-02-07 11:45:46 -0800483
484 if (old_sector != SectorFromAddress(key_descriptor->address)) {
485 DBG("Sector for old entry (size %zu) was garbage collected. Old entry "
486 "relocated to sector %zu",
487 original_entry.size(),
488 SectorIndex(SectorFromAddress(key_descriptor->address)));
489
490 old_sector = SectorFromAddress(key_descriptor->address);
491 }
492
Wyatt Hepler5a33d8c2020-02-06 09:32:58 -0800493 TRY(AppendEntry(sector, key_descriptor, key, value, new_state));
494
David Rogers3464d0a2020-02-07 11:45:46 -0800495 old_sector->RemoveValidBytes(original_entry.size());
Wyatt Hepler5a33d8c2020-02-06 09:32:58 -0800496 return Status::OK;
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800497}
498
499Status KeyValueStore::WriteEntryForNewKey(string_view key,
500 span<const byte> value) {
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800501 if (key_descriptors_.full()) {
Keir Mierle8c352dc2020-02-02 13:58:19 -0800502 WRN("KVS full: trying to store a new entry, but can't. Have %zu entries",
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800503 key_descriptors_.size());
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800504 return Status::RESOURCE_EXHAUSTED;
505 }
506
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800507 // Create the KeyDescriptor that will be added to the list. The version and
508 // address will be set by AppendEntry.
509 KeyDescriptor key_descriptor(key, 0, 0);
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800510
David Rogers2761aeb2020-01-31 17:09:00 -0800511 SectorDescriptor* sector;
Wyatt Hepler97fc7942020-02-06 15:55:45 -0800512 TRY(FindOrRecoverSectorWithSpace(
Wyatt Hepler30a52152020-02-12 11:26:05 -0800513 &sector, Entry::size(partition_.alignment_bytes(), key, value)));
David Rogers8ce55cd2020-02-04 19:41:48 -0800514 DBG("Writing new entry; found sector: %zu", SectorIndex(sector));
David Rogers2761aeb2020-01-31 17:09:00 -0800515 TRY(AppendEntry(sector, &key_descriptor, key, value));
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800516
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800517 // Only add the entry when we are certain the write succeeded.
518 key_descriptors_.push_back(key_descriptor);
Wyatt Heplerb7609542020-01-24 10:29:54 -0800519 return Status::OK;
520}
521
David Rogers2761aeb2020-01-31 17:09:00 -0800522Status KeyValueStore::RelocateEntry(KeyDescriptor& key_descriptor) {
David Rogersf0a35442020-02-04 12:16:38 -0800523 struct TempEntry {
524 std::array<char, kMaxKeyLength + 1> key;
525 std::array<char, sizeof(working_buffer_) - sizeof(key)> value;
526 };
527 TempEntry* entry = reinterpret_cast<TempEntry*>(working_buffer_.data());
528
David Rogersdf025cd2020-02-06 17:05:34 -0800529 DBG("Relocating entry"); // TODO: add entry info to the log statement.
530
David Rogersf0a35442020-02-04 12:16:38 -0800531 // Read the entry to be relocated. Store the header in a local variable and
532 // store the key and value in the TempEntry stored in the static allocated
533 // working_buffer_.
Wyatt Hepler30a52152020-02-12 11:26:05 -0800534 Entry header;
Wyatt Hepler4d78cd62020-02-05 13:05:58 -0800535 TRY(ReadEntryHeader(key_descriptor.address, &header));
536 TRY(ReadEntryKey(
537 key_descriptor.address, header.key_length(), entry->key.data()));
David Rogersf0a35442020-02-04 12:16:38 -0800538 string_view key = string_view(entry->key.data(), header.key_length());
539 StatusWithSize result = ReadEntryValue(
540 key_descriptor, header, as_writable_bytes(span(entry->value)));
541 if (!result.status().ok()) {
542 return Status::INTERNAL;
543 }
544
545 auto value = span(entry->value.data(), result.size());
546
547 TRY(header.VerifyChecksum(
548 entry_header_format_.checksum, key, as_bytes(value)));
549
David Rogers3464d0a2020-02-07 11:45:46 -0800550 SectorDescriptor* old_sector = SectorFromAddress(key_descriptor.address);
David Rogersf0a35442020-02-04 12:16:38 -0800551
552 // Find a new sector for the entry and write it to the new location.
David Rogers8ce55cd2020-02-04 19:41:48 -0800553 SectorDescriptor* new_sector;
David Rogers3464d0a2020-02-07 11:45:46 -0800554 TRY(FindSectorWithSpace(&new_sector, header.size(), old_sector, true));
David Rogersdf025cd2020-02-06 17:05:34 -0800555 TRY(AppendEntry(new_sector, &key_descriptor, key, as_bytes(value)));
556
557 // Do the valid bytes accounting for the sector the entry was relocated out
558 // of.
David Rogers3464d0a2020-02-07 11:45:46 -0800559 old_sector->RemoveValidBytes(header.size());
David Rogersdf025cd2020-02-06 17:05:34 -0800560
561 return Status::OK;
David Rogersa12786b2020-01-31 16:02:33 -0800562}
563
David Rogers8db5a722020-02-03 18:28:34 -0800564// Find either an existing sector with enough space that is not the sector to
565// skip, or an empty sector. Maintains the invariant that there is always at
566// least 1 empty sector unless set to bypass the rule.
Wyatt Hepler5a33d8c2020-02-06 09:32:58 -0800567Status KeyValueStore::FindSectorWithSpace(
568 SectorDescriptor** found_sector,
569 size_t size,
570 const SectorDescriptor* sector_to_skip,
571 bool bypass_empty_sector_rule) {
David Rogers8ce55cd2020-02-04 19:41:48 -0800572 // The last_new_sector_ is the sector that was last selected as the "new empty
573 // sector" to write to. This last new sector is used as the starting point for
574 // the next "find a new empty sector to write to" operation. By using the last
575 // new sector as the start point we will cycle which empty sector is selected
576 // next, spreading the wear across all the empty sectors and get a wear
577 // leveling benefit, rather than putting more wear on the lower number
578 // sectors.
579 //
580 // Locally use the sector index for ease of iterating through the sectors. For
581 // the persistent storage use SectorDescriptor* rather than sector index
582 // because SectorDescriptor* is the standard way to identify a sector.
583 size_t last_new_sector_index_ = SectorIndex(last_new_sector_);
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800584 size_t start = (last_new_sector_index_ + 1) % sectors_.size();
David Rogers2761aeb2020-01-31 17:09:00 -0800585 SectorDescriptor* first_empty_sector = nullptr;
David Rogers8db5a722020-02-03 18:28:34 -0800586 bool at_least_two_empty_sectors = bypass_empty_sector_rule;
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800587
David Rogers67f4b6c2020-02-06 16:17:09 -0800588 DBG("Find sector with %zu bytes available", size);
589 if (sector_to_skip != nullptr) {
590 DBG(" Skip sector %zu", SectorIndex(sector_to_skip));
591 }
592 if (bypass_empty_sector_rule) {
593 DBG(" Bypassing empty sector rule");
594 }
595
David Rogers8ce55cd2020-02-04 19:41:48 -0800596 // Look for a partial sector to use with enough space. Immediately use the
597 // first one of those that is found. While scanning for a partial sector, keep
598 // track of the first empty sector and if a second sector was seen.
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800599 for (size_t j = 0; j < sectors_.size(); j++) {
600 size_t i = (j + start) % sectors_.size();
601 SectorDescriptor& sector = sectors_[i];
Keir Mierle8c352dc2020-02-02 13:58:19 -0800602
David Rogers8db5a722020-02-03 18:28:34 -0800603 if (sector_to_skip == &sector) {
David Rogers67f4b6c2020-02-06 16:17:09 -0800604 DBG(" Skipping the skip sector %zu", i);
David Rogers8db5a722020-02-03 18:28:34 -0800605 continue;
606 }
607
David Rogers67f4b6c2020-02-06 16:17:09 -0800608 DBG(" Examining sector %zu with %hu bytes available",
609 i,
610 sector.tail_free_bytes);
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800611 if (!SectorEmpty(sector) && sector.HasSpace(size)) {
David Rogers67f4b6c2020-02-06 16:17:09 -0800612 DBG(" Partially occupied sector %zu with enough space; done!", i);
David Rogers8ce55cd2020-02-04 19:41:48 -0800613 *found_sector = &sector;
614 return Status::OK;
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800615 }
616
617 if (SectorEmpty(sector)) {
618 if (first_empty_sector == nullptr) {
619 first_empty_sector = &sector;
620 } else {
621 at_least_two_empty_sectors = true;
Wyatt Hepler2ad60672020-01-21 08:00:16 -0800622 }
Wyatt Heplerb7609542020-01-24 10:29:54 -0800623 }
624 }
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800625
David Rogers8ce55cd2020-02-04 19:41:48 -0800626 // If the scan for a partial sector does not find a suitable sector, use the
627 // first empty sector that was found. Normally it is required to keep 1 empty
628 // sector after the sector found here, but that rule can be bypassed in
629 // special circumstances (such as during garbage collection).
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800630 if (at_least_two_empty_sectors) {
David Rogers67f4b6c2020-02-06 16:17:09 -0800631 DBG(" Found a usable empty sector; returning the first found (%zu)",
David Rogers8ce55cd2020-02-04 19:41:48 -0800632 SectorIndex(first_empty_sector));
633 last_new_sector_ = first_empty_sector;
634 *found_sector = first_empty_sector;
635 return Status::OK;
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800636 }
David Rogers8ce55cd2020-02-04 19:41:48 -0800637
638 // No sector was found.
David Rogers67f4b6c2020-02-06 16:17:09 -0800639 DBG(" Unable to find a usable sector");
David Rogers8ce55cd2020-02-04 19:41:48 -0800640 *found_sector = nullptr;
641 return Status::RESOURCE_EXHAUSTED;
Wyatt Heplerb7609542020-01-24 10:29:54 -0800642}
643
David Rogers2761aeb2020-01-31 17:09:00 -0800644Status KeyValueStore::FindOrRecoverSectorWithSpace(SectorDescriptor** sector,
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800645 size_t size) {
David Rogers8ce55cd2020-02-04 19:41:48 -0800646 Status result = FindSectorWithSpace(sector, size);
647 if (result.ok()) {
648 return result;
Wyatt Heplerb7609542020-01-24 10:29:54 -0800649 }
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800650 if (options_.partial_gc_on_write) {
David Rogers1541d612020-02-06 23:47:02 -0800651 // Garbage collect and then try again to find the best sector.
652 TRY(GarbageCollectOneSector());
653 return FindSectorWithSpace(sector, size);
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800654 }
David Rogers8ce55cd2020-02-04 19:41:48 -0800655 return result;
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800656}
657
David Rogers2761aeb2020-01-31 17:09:00 -0800658KeyValueStore::SectorDescriptor* KeyValueStore::FindSectorToGarbageCollect() {
659 SectorDescriptor* sector_candidate = nullptr;
David Rogersa12786b2020-01-31 16:02:33 -0800660 size_t candidate_bytes = 0;
661
662 // Step 1: Try to find a sectors with stale keys and no valid keys (no
663 // relocation needed). If any such sectors are found, use the sector with the
664 // most reclaimable bytes.
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800665 for (auto& sector : sectors_) {
David Rogersa12786b2020-01-31 16:02:33 -0800666 if ((sector.valid_bytes == 0) &&
667 (RecoverableBytes(sector) > candidate_bytes)) {
668 sector_candidate = &sector;
669 candidate_bytes = RecoverableBytes(sector);
670 }
671 }
672
673 // Step 2: If step 1 yields no sectors, just find the sector with the most
674 // reclaimable bytes.
675 if (sector_candidate == nullptr) {
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800676 for (auto& sector : sectors_) {
David Rogersa12786b2020-01-31 16:02:33 -0800677 if (RecoverableBytes(sector) > candidate_bytes) {
678 sector_candidate = &sector;
679 candidate_bytes = RecoverableBytes(sector);
680 }
681 }
682 }
683
David Rogers67f4b6c2020-02-06 16:17:09 -0800684 DBG("Found sector %zu to Garbage Collect, %zu recoverable bytes",
685 SectorIndex(sector_candidate),
686 RecoverableBytes(*sector_candidate));
David Rogersa12786b2020-01-31 16:02:33 -0800687 return sector_candidate;
688}
689
David Rogers1541d612020-02-06 23:47:02 -0800690Status KeyValueStore::GarbageCollectOneSector() {
David Rogers67f4b6c2020-02-06 16:17:09 -0800691 DBG("Garbage Collect a single sector");
692
David Rogersa12786b2020-01-31 16:02:33 -0800693 // Step 1: Find the sector to garbage collect
David Rogers2761aeb2020-01-31 17:09:00 -0800694 SectorDescriptor* sector_to_gc = FindSectorToGarbageCollect();
David Rogers3464d0a2020-02-07 11:45:46 -0800695 LogSectors();
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800696
David Rogersa12786b2020-01-31 16:02:33 -0800697 if (sector_to_gc == nullptr) {
698 return Status::RESOURCE_EXHAUSTED;
699 }
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800700
David Rogersa12786b2020-01-31 16:02:33 -0800701 // Step 2: Move any valid entries in the GC sector to other sectors
702 if (sector_to_gc->valid_bytes != 0) {
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800703 for (auto& descriptor : key_descriptors_) {
David Rogers2761aeb2020-01-31 17:09:00 -0800704 if (AddressInSector(*sector_to_gc, descriptor.address)) {
David Rogers67f4b6c2020-02-06 16:17:09 -0800705 DBG(" Relocate entry");
David Rogers2761aeb2020-01-31 17:09:00 -0800706 TRY(RelocateEntry(descriptor));
David Rogersa12786b2020-01-31 16:02:33 -0800707 }
Wyatt Heplerb7609542020-01-24 10:29:54 -0800708 }
709 }
Wyatt Heplerb7609542020-01-24 10:29:54 -0800710
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800711 if (sector_to_gc->valid_bytes != 0) {
David Rogers67f4b6c2020-02-06 16:17:09 -0800712 ERR(" Failed to relocate valid entries from sector being garbage "
713 "collected, %hu valid bytes remain",
714 sector_to_gc->valid_bytes);
Wyatt Heplerb7609542020-01-24 10:29:54 -0800715 return Status::INTERNAL;
716 }
717
David Rogersa12786b2020-01-31 16:02:33 -0800718 // Step 3: Reinitialize the sector
719 sector_to_gc->tail_free_bytes = 0;
720 TRY(partition_.Erase(SectorBaseAddress(sector_to_gc), 1));
721 sector_to_gc->tail_free_bytes = partition_.sector_size_bytes();
Wyatt Heplerb7609542020-01-24 10:29:54 -0800722
David Rogers67f4b6c2020-02-06 16:17:09 -0800723 DBG(" Garbage Collect complete");
David Rogers50185ad2020-02-07 00:02:46 -0800724 LogSectors();
David Rogersa12786b2020-01-31 16:02:33 -0800725 return Status::OK;
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800726}
727
David Rogers2761aeb2020-01-31 17:09:00 -0800728Status KeyValueStore::AppendEntry(SectorDescriptor* sector,
729 KeyDescriptor* key_descriptor,
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800730 const string_view key,
Wyatt Hepler5a33d8c2020-02-06 09:32:58 -0800731 span<const byte> value,
732 KeyDescriptor::State new_state) {
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800733 // write header, key, and value
Wyatt Hepler30a52152020-02-12 11:26:05 -0800734 Entry header;
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800735
Wyatt Hepler5a33d8c2020-02-06 09:32:58 -0800736 if (new_state == KeyDescriptor::kDeleted) {
Wyatt Hepler30a52152020-02-12 11:26:05 -0800737 header = Entry::Tombstone(entry_header_format_.magic,
738 entry_header_format_.checksum,
739 key,
740 partition_.alignment_bytes(),
741 key_descriptor->key_version + 1);
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800742 } else {
Wyatt Hepler30a52152020-02-12 11:26:05 -0800743 header = Entry::Valid(entry_header_format_.magic,
744 entry_header_format_.checksum,
745 key,
746 value,
747 partition_.alignment_bytes(),
748 key_descriptor->key_version + 1);
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800749 }
750
Wyatt Hepler97fc7942020-02-06 15:55:45 -0800751 DBG("Appending %zu B entry with key version: %x",
752 header.size(),
753 unsigned(header.key_version()));
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800754
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800755 Address address = NextWritableAddress(sector);
David Rogers3464d0a2020-02-07 11:45:46 -0800756 DBG("Appending to address: %#zx", size_t(address));
Wyatt Hepler5a33d8c2020-02-06 09:32:58 -0800757
Wyatt Hepler1927c282020-02-11 16:45:02 -0800758 // Write multiple concatenated buffers and pad the results.
759 FlashPartition::Output flash(partition_, address);
760 TRY_ASSIGN(const size_t written,
761 AlignedWrite<32>(
762 flash,
763 header.alignment_bytes(),
764 {as_bytes(span(&header, 1)), as_bytes(span(key)), value}));
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800765
766 if (options_.verify_on_write) {
Wyatt Hepler0a223582020-02-04 17:47:40 -0800767 TRY(header.VerifyChecksumInFlash(
768 &partition_, address, entry_header_format_.checksum));
Wyatt Heplerb7609542020-01-24 10:29:54 -0800769 }
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800770
David Rogers2761aeb2020-01-31 17:09:00 -0800771 key_descriptor->address = address;
772 key_descriptor->key_version = header.key_version();
Wyatt Hepler5a33d8c2020-02-06 09:32:58 -0800773 key_descriptor->state = new_state;
774
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800775 sector->valid_bytes += written;
David Rogers2be76b02020-02-06 17:33:05 -0800776 sector->RemoveFreeBytes(written);
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800777 return Status::OK;
Wyatt Heplerb7609542020-01-24 10:29:54 -0800778}
779
Keir Mierle8c352dc2020-02-02 13:58:19 -0800780void KeyValueStore::LogDebugInfo() {
Keir Mierle8c352dc2020-02-02 13:58:19 -0800781 const size_t sector_size_bytes = partition_.sector_size_bytes();
782 DBG("====================== KEY VALUE STORE DUMP =========================");
783 DBG(" ");
784 DBG("Flash partition:");
Wyatt Heplerad0a7932020-02-06 08:20:38 -0800785 DBG(" Sector count = %zu", partition_.sector_count());
786 DBG(" Sector max count = %zu", kMaxUsableSectors);
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800787 DBG(" Sectors in use = %zu", sectors_.size());
Keir Mierle8c352dc2020-02-02 13:58:19 -0800788 DBG(" Sector size = %zu", sector_size_bytes);
789 DBG(" Total size = %zu", partition_.size_bytes());
790 DBG(" Alignment = %zu", partition_.alignment_bytes());
791 DBG(" ");
792 DBG("Key descriptors:");
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800793 DBG(" Entry count = %zu", key_descriptors_.size());
Keir Mierle8c352dc2020-02-02 13:58:19 -0800794 DBG(" Max entry count = %zu", kMaxEntries);
795 DBG(" ");
796 DBG(" # hash version address address (hex)");
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800797 for (size_t i = 0; i < key_descriptors_.size(); ++i) {
798 const KeyDescriptor& kd = key_descriptors_[i];
Keir Mierle8c352dc2020-02-02 13:58:19 -0800799 DBG(" |%3zu: | %8zx |%8zu | %8zu | %8zx",
800 i,
801 size_t(kd.key_hash),
802 size_t(kd.key_version),
803 size_t(kd.address),
804 size_t(kd.address));
805 }
806 DBG(" ");
807
808 DBG("Sector descriptors:");
809 DBG(" # tail free valid has_space");
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800810 for (size_t sector_id = 0; sector_id < sectors_.size(); ++sector_id) {
811 const SectorDescriptor& sd = sectors_[sector_id];
Keir Mierle8c352dc2020-02-02 13:58:19 -0800812 DBG(" |%3zu: | %8zu |%8zu | %s",
813 sector_id,
814 size_t(sd.tail_free_bytes),
815 size_t(sd.valid_bytes),
816 sd.tail_free_bytes ? "YES" : "");
817 }
818 DBG(" ");
819
820 // TODO: This should stop logging after some threshold.
821 // size_t dumped_bytes = 0;
822 DBG("Sector raw data:");
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800823 for (size_t sector_id = 0; sector_id < sectors_.size(); ++sector_id) {
Keir Mierle8c352dc2020-02-02 13:58:19 -0800824 // Read sector data. Yes, this will blow the stack on embedded.
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800825 std::array<byte, 500> raw_sector_data; // TODO!!!
Keir Mierle8c352dc2020-02-02 13:58:19 -0800826 StatusWithSize sws =
827 partition_.Read(sector_id * sector_size_bytes, raw_sector_data);
828 DBG("Read: %zu bytes", sws.size());
829
830 DBG(" base addr offs 0 1 2 3 4 5 6 7");
831 for (size_t i = 0; i < sector_size_bytes; i += 8) {
832 DBG(" %3zu %8zx %5zu | %02x %02x %02x %02x %02x %02x %02x %02x",
833 sector_id,
834 (sector_id * sector_size_bytes) + i,
835 i,
836 static_cast<unsigned int>(raw_sector_data[i + 0]),
837 static_cast<unsigned int>(raw_sector_data[i + 1]),
838 static_cast<unsigned int>(raw_sector_data[i + 2]),
839 static_cast<unsigned int>(raw_sector_data[i + 3]),
840 static_cast<unsigned int>(raw_sector_data[i + 4]),
841 static_cast<unsigned int>(raw_sector_data[i + 5]),
842 static_cast<unsigned int>(raw_sector_data[i + 6]),
843 static_cast<unsigned int>(raw_sector_data[i + 7]));
844
845 // TODO: Fix exit condition.
846 if (i > 128) {
847 break;
848 }
849 }
850 DBG(" ");
851 }
852
853 DBG("////////////////////// KEY VALUE STORE DUMP END /////////////////////");
854}
855
David Rogerscf680ab2020-02-12 23:28:32 -0800856void KeyValueStore::LogSectors() const {
857 DBG("Sector descriptors: count %zu", sectors_.size());
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800858 for (auto& sector : sectors_) {
David Rogers50185ad2020-02-07 00:02:46 -0800859 DBG(" - Sector %zu: valid %hu, recoverable %zu, free %hu",
860 SectorIndex(&sector),
861 sector.valid_bytes,
862 RecoverableBytes(sector),
863 sector.tail_free_bytes);
864 }
865}
866
David Rogerscf680ab2020-02-12 23:28:32 -0800867void KeyValueStore::LogKeyDescriptor() const {
868 DBG("Key descriptors: count %zu", key_descriptors_.size());
869 for (auto& key : key_descriptors_) {
870 DBG(" - Key: %s, hash %#zx, version %zu, address %#zx",
871 key.deleted() ? "Deleted" : "Valid",
872 static_cast<size_t>(key.key_hash),
873 static_cast<size_t>(key.key_version),
874 static_cast<size_t>(key.address));
875 }
876}
877
David Rogers3464d0a2020-02-07 11:45:46 -0800878void KeyValueStore::SectorDescriptor::RemoveValidBytes(size_t size) {
879 // TODO: add safety check for valid_bytes > size.
880 if (size > valid_bytes) {
881 CRT("!!!!!!!!!!!!!!!");
882 CRT("Remove too many valid bytes!!! remove %zu, only have %hu",
883 size,
884 valid_bytes);
885 valid_bytes = size;
886 }
887 valid_bytes -= size;
888}
889
Wyatt Hepler2ad60672020-01-21 08:00:16 -0800890} // namespace pw::kvs