blob: b6b8e30c29b37b997f6f214dbfb7ee5419cfb9d2 [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;
Keir Mierle8c352dc2020-02-02 13:58:19 -0800128 EntryHeader 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) {
Keir Mierle8c352dc2020-02-02 13:58:19 -0800138 EntryHeader 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.
234bool KeyValueStore::HeaderLooksLikeUnwrittenData(
235 const EntryHeader& header) const {
236 // TODO: This is not correct; it should call through to flash memory.
237 return header.magic() == 0xffffffff;
238}
239
240KeyValueStore::KeyDescriptor* KeyValueStore::FindDescriptor(uint32_t hash) {
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800241 for (KeyDescriptor& key_descriptor : key_descriptors_) {
242 if (key_descriptor.key_hash == hash) {
243 return &key_descriptor;
Keir Mierle8c352dc2020-02-02 13:58:19 -0800244 }
245 }
246 return nullptr;
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800247}
248
249StatusWithSize KeyValueStore::Get(string_view key,
250 span<byte> value_buffer) const {
Wyatt Hepler729f28c2020-02-05 09:46:00 -0800251 TRY(CheckOperation(key));
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800252
David Rogers2761aeb2020-01-31 17:09:00 -0800253 const KeyDescriptor* key_descriptor;
254 TRY(FindKeyDescriptor(key, &key_descriptor));
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800255
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800256 if (key_descriptor->deleted()) {
257 return Status::NOT_FOUND;
258 }
259
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800260 EntryHeader header;
Wyatt Hepler4d78cd62020-02-05 13:05:58 -0800261 TRY(ReadEntryHeader(key_descriptor->address, &header));
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800262
Keir Mierle8c352dc2020-02-02 13:58:19 -0800263 StatusWithSize result = ReadEntryValue(*key_descriptor, header, value_buffer);
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800264 if (result.ok() && options_.verify_on_read) {
Wyatt Hepler6e3a83b2020-02-04 07:36:45 -0800265 return header.VerifyChecksum(entry_header_format_.checksum,
266 key,
267 value_buffer.subspan(0, result.size()));
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800268 }
269 return result;
270}
271
272Status KeyValueStore::Put(string_view key, span<const byte> value) {
Keir Mierle8c352dc2020-02-02 13:58:19 -0800273 DBG("Writing key/value; key length=%zu, value length=%zu",
274 key.size(),
275 value.size());
Wyatt Hepler729f28c2020-02-05 09:46:00 -0800276
277 TRY(CheckOperation(key));
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800278
279 if (value.size() > (1 << 24)) {
280 // TODO: Reject sizes that are larger than the maximum?
281 }
282
David Rogers2761aeb2020-01-31 17:09:00 -0800283 KeyDescriptor* key_descriptor;
284 if (FindKeyDescriptor(key, &key_descriptor).ok()) {
David Rogers3464d0a2020-02-07 11:45:46 -0800285 DBG("Writing over existing entry for 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::kValid, key, value);
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800290 }
David Rogers2761aeb2020-01-31 17:09:00 -0800291
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800292 return WriteEntryForNewKey(key, value);
293}
294
295Status KeyValueStore::Delete(string_view key) {
Wyatt Hepler729f28c2020-02-05 09:46:00 -0800296 TRY(CheckOperation(key));
297
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800298 KeyDescriptor* key_descriptor;
299 TRY(FindKeyDescriptor(key, &key_descriptor));
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800300
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800301 if (key_descriptor->deleted()) {
302 return Status::NOT_FOUND;
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800303 }
304
David Rogers3464d0a2020-02-07 11:45:46 -0800305 DBG("Writing tombstone for existing key 0x%08" PRIx32 " in sector %zu",
306 key_descriptor->key_hash,
307 SectorIndex(SectorFromAddress(key_descriptor->address)));
Wyatt Hepler5a33d8c2020-02-06 09:32:58 -0800308 return WriteEntryForExistingKey(
309 key_descriptor, KeyDescriptor::kDeleted, key, {});
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800310}
311
312KeyValueStore::iterator& KeyValueStore::iterator::operator++() {
313 // Skip to the next entry that is valid (not deleted).
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800314 while (++index_ < item_.kvs_.key_descriptors_.size() &&
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800315 descriptor().deleted()) {
316 }
317 return *this;
318}
319
320const KeyValueStore::Item& KeyValueStore::iterator::operator*() {
321 std::memset(item_.key_buffer_.data(), 0, item_.key_buffer_.size());
322
323 EntryHeader header;
324 if (item_.kvs_.ReadEntryHeader(descriptor().address, &header).ok()) {
325 item_.kvs_.ReadEntryKey(
326 descriptor().address, header.key_length(), item_.key_buffer_.data());
327 }
328
329 return item_;
330}
331
332KeyValueStore::iterator KeyValueStore::begin() const {
333 size_t i = 0;
334 // Skip over any deleted entries at the start of the descriptor list.
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800335 while (i < key_descriptors_.size() && key_descriptors_[i].deleted()) {
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800336 i += 1;
337 }
338 return iterator(*this, i);
339}
340
341// TODO(hepler): The valid entry count could be tracked in the KVS to avoid the
342// need for this for-loop.
343size_t KeyValueStore::size() const {
344 size_t valid_entries = 0;
345
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800346 for (const KeyDescriptor& key_descriptor : key_descriptors_) {
347 if (!key_descriptor.deleted()) {
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800348 valid_entries += 1;
349 }
350 }
351
352 return valid_entries;
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800353}
354
Wyatt Heplered163b02020-02-03 17:49:32 -0800355StatusWithSize KeyValueStore::ValueSize(std::string_view key) const {
Wyatt Hepler729f28c2020-02-05 09:46:00 -0800356 TRY(CheckOperation(key));
Wyatt Heplered163b02020-02-03 17:49:32 -0800357
358 const KeyDescriptor* key_descriptor;
359 TRY(FindKeyDescriptor(key, &key_descriptor));
360
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800361 if (key_descriptor->deleted()) {
362 return Status::NOT_FOUND;
363 }
364
Wyatt Heplered163b02020-02-03 17:49:32 -0800365 EntryHeader header;
Wyatt Hepler4d78cd62020-02-05 13:05:58 -0800366 TRY(ReadEntryHeader(key_descriptor->address, &header));
Wyatt Heplered163b02020-02-03 17:49:32 -0800367
368 return StatusWithSize(header.value_length());
369}
370
Wyatt Hepler4d78cd62020-02-05 13:05:58 -0800371uint32_t KeyValueStore::HashKey(string_view string) {
372 uint32_t hash = 0;
373 uint32_t coefficient = 65599u;
374
375 for (char ch : string) {
376 hash += coefficient * unsigned(ch);
377 coefficient *= 65599u;
378 }
379
380 return hash;
381}
382
Wyatt Hepler6e3a83b2020-02-04 07:36:45 -0800383Status KeyValueStore::FixedSizeGet(std::string_view key,
384 byte* value,
385 size_t size_bytes) const {
386 // Ensure that the size of the stored value matches the size of the type.
387 // Otherwise, report error. This check avoids potential memory corruption.
388 StatusWithSize result = ValueSize(key);
389 if (!result.ok()) {
390 return result.status();
Keir Mierle8c352dc2020-02-02 13:58:19 -0800391 }
Wyatt Hepler6e3a83b2020-02-04 07:36:45 -0800392 if (result.size() != size_bytes) {
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800393 DBG("Requested %zu B read, but value is %zu B", size_bytes, result.size());
Wyatt Hepler6e3a83b2020-02-04 07:36:45 -0800394 return Status::INVALID_ARGUMENT;
Wyatt Heplerbab0e202020-02-04 07:40:08 -0800395 }
Wyatt Hepler6e3a83b2020-02-04 07:36:45 -0800396 return Get(key, span(value, size_bytes)).status();
Keir Mierle8c352dc2020-02-02 13:58:19 -0800397}
398
Wyatt Hepler729f28c2020-02-05 09:46:00 -0800399Status KeyValueStore::CheckOperation(string_view key) const {
Wyatt Hepleracaacf92020-01-24 10:58:30 -0800400 if (InvalidKey(key)) {
Wyatt Heplerb7609542020-01-24 10:29:54 -0800401 return Status::INVALID_ARGUMENT;
402 }
Wyatt Hepler729f28c2020-02-05 09:46:00 -0800403 if (!initialized_) {
Wyatt Heplerb7609542020-01-24 10:29:54 -0800404 return Status::FAILED_PRECONDITION;
405 }
Wyatt Heplerb7609542020-01-24 10:29:54 -0800406 return Status::OK;
407}
408
David Rogers2761aeb2020-01-31 17:09:00 -0800409Status KeyValueStore::FindKeyDescriptor(string_view key,
410 const KeyDescriptor** result) const {
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800411 char key_buffer[kMaxKeyLength];
412 const uint32_t hash = HashKey(key);
Wyatt Heplerb7609542020-01-24 10:29:54 -0800413
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800414 for (auto& descriptor : key_descriptors_) {
David Rogers2761aeb2020-01-31 17:09:00 -0800415 if (descriptor.key_hash == hash) {
Wyatt Hepler4d78cd62020-02-05 13:05:58 -0800416 TRY(ReadEntryKey(descriptor.address, key.size(), key_buffer));
Wyatt Heplerb7609542020-01-24 10:29:54 -0800417
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800418 if (key == string_view(key_buffer, key.size())) {
Wyatt Hepler5a33d8c2020-02-06 09:32:58 -0800419 DBG("Found match for key hash 0x%08" PRIx32, hash);
David Rogers2761aeb2020-01-31 17:09:00 -0800420 *result = &descriptor;
Wyatt Heplerb7609542020-01-24 10:29:54 -0800421 return Status::OK;
422 }
Wyatt Heplerb7609542020-01-24 10:29:54 -0800423 }
424 }
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800425 return Status::NOT_FOUND;
426}
427
Wyatt Hepler4d78cd62020-02-05 13:05:58 -0800428Status KeyValueStore::ReadEntryHeader(Address address,
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800429 EntryHeader* header) const {
Wyatt Hepler4d78cd62020-02-05 13:05:58 -0800430 return partition_.Read(address, sizeof(*header), header).status();
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800431}
432
Wyatt Hepler4d78cd62020-02-05 13:05:58 -0800433Status KeyValueStore::ReadEntryKey(Address address,
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800434 size_t key_length,
435 char* key) const {
436 // TODO: This check probably shouldn't be here; this is like
437 // checking that the Cortex M's RAM isn't corrupt. This should be
438 // done at boot time.
439 // ^^ This argument sometimes comes from EntryHeader::key_value_len,
440 // which is read directly from flash. If it's corrupted, we shouldn't try
441 // to read a bunch of extra data.
442 if (key_length == 0u || key_length > kMaxKeyLength) {
443 return Status::DATA_LOSS;
444 }
445 // The key is immediately after the entry header.
Wyatt Hepler4d78cd62020-02-05 13:05:58 -0800446 return partition_.Read(address + sizeof(EntryHeader), key_length, key)
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800447 .status();
448}
449
David Rogers2761aeb2020-01-31 17:09:00 -0800450StatusWithSize KeyValueStore::ReadEntryValue(
451 const KeyDescriptor& key_descriptor,
452 const EntryHeader& header,
453 span<byte> value) const {
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800454 const size_t read_size = std::min(header.value_length(), value.size());
David Rogers2761aeb2020-01-31 17:09:00 -0800455 StatusWithSize result = partition_.Read(
456 key_descriptor.address + sizeof(header) + header.key_length(),
Keir Mierle8c352dc2020-02-02 13:58:19 -0800457 value.subspan(0, read_size));
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800458 TRY(result);
459 if (read_size != header.value_length()) {
460 return StatusWithSize(Status::RESOURCE_EXHAUSTED, read_size);
461 }
462 return StatusWithSize(read_size);
463}
464
David Rogers2761aeb2020-01-31 17:09:00 -0800465Status KeyValueStore::WriteEntryForExistingKey(KeyDescriptor* key_descriptor,
Wyatt Hepler5a33d8c2020-02-06 09:32:58 -0800466 KeyDescriptor::State new_state,
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800467 string_view key,
468 span<const byte> value) {
Wyatt Hepler5a33d8c2020-02-06 09:32:58 -0800469 // Find the original entry and sector to update the sector's valid_bytes.
470 EntryHeader original_entry;
471 TRY(ReadEntryHeader(key_descriptor->address, &original_entry));
David Rogers3464d0a2020-02-07 11:45:46 -0800472 SectorDescriptor* old_sector = SectorFromAddress(key_descriptor->address);
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800473
David Rogers2761aeb2020-01-31 17:09:00 -0800474 SectorDescriptor* sector;
Wyatt Hepler97fc7942020-02-06 15:55:45 -0800475 TRY(FindOrRecoverSectorWithSpace(
476 &sector, EntryHeader::size(partition_.alignment_bytes(), key, value)));
David Rogers8ce55cd2020-02-04 19:41:48 -0800477 DBG("Writing existing entry; found sector: %zu", SectorIndex(sector));
David Rogers3464d0a2020-02-07 11:45:46 -0800478
479 if (old_sector != SectorFromAddress(key_descriptor->address)) {
480 DBG("Sector for old entry (size %zu) was garbage collected. Old entry "
481 "relocated to sector %zu",
482 original_entry.size(),
483 SectorIndex(SectorFromAddress(key_descriptor->address)));
484
485 old_sector = SectorFromAddress(key_descriptor->address);
486 }
487
Wyatt Hepler5a33d8c2020-02-06 09:32:58 -0800488 TRY(AppendEntry(sector, key_descriptor, key, value, new_state));
489
David Rogers3464d0a2020-02-07 11:45:46 -0800490 old_sector->RemoveValidBytes(original_entry.size());
Wyatt Hepler5a33d8c2020-02-06 09:32:58 -0800491 return Status::OK;
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800492}
493
494Status KeyValueStore::WriteEntryForNewKey(string_view key,
495 span<const byte> value) {
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800496 if (key_descriptors_.full()) {
Keir Mierle8c352dc2020-02-02 13:58:19 -0800497 WRN("KVS full: trying to store a new entry, but can't. Have %zu entries",
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800498 key_descriptors_.size());
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800499 return Status::RESOURCE_EXHAUSTED;
500 }
501
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800502 // Create the KeyDescriptor that will be added to the list. The version and
503 // address will be set by AppendEntry.
504 KeyDescriptor key_descriptor(key, 0, 0);
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800505
David Rogers2761aeb2020-01-31 17:09:00 -0800506 SectorDescriptor* sector;
Wyatt Hepler97fc7942020-02-06 15:55:45 -0800507 TRY(FindOrRecoverSectorWithSpace(
508 &sector, EntryHeader::size(partition_.alignment_bytes(), key, value)));
David Rogers8ce55cd2020-02-04 19:41:48 -0800509 DBG("Writing new entry; found sector: %zu", SectorIndex(sector));
David Rogers2761aeb2020-01-31 17:09:00 -0800510 TRY(AppendEntry(sector, &key_descriptor, key, value));
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800511
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800512 // Only add the entry when we are certain the write succeeded.
513 key_descriptors_.push_back(key_descriptor);
Wyatt Heplerb7609542020-01-24 10:29:54 -0800514 return Status::OK;
515}
516
David Rogers2761aeb2020-01-31 17:09:00 -0800517Status KeyValueStore::RelocateEntry(KeyDescriptor& key_descriptor) {
David Rogersf0a35442020-02-04 12:16:38 -0800518 struct TempEntry {
519 std::array<char, kMaxKeyLength + 1> key;
520 std::array<char, sizeof(working_buffer_) - sizeof(key)> value;
521 };
522 TempEntry* entry = reinterpret_cast<TempEntry*>(working_buffer_.data());
523
David Rogersdf025cd2020-02-06 17:05:34 -0800524 DBG("Relocating entry"); // TODO: add entry info to the log statement.
525
David Rogersf0a35442020-02-04 12:16:38 -0800526 // Read the entry to be relocated. Store the header in a local variable and
527 // store the key and value in the TempEntry stored in the static allocated
528 // working_buffer_.
529 EntryHeader header;
Wyatt Hepler4d78cd62020-02-05 13:05:58 -0800530 TRY(ReadEntryHeader(key_descriptor.address, &header));
531 TRY(ReadEntryKey(
532 key_descriptor.address, header.key_length(), entry->key.data()));
David Rogersf0a35442020-02-04 12:16:38 -0800533 string_view key = string_view(entry->key.data(), header.key_length());
534 StatusWithSize result = ReadEntryValue(
535 key_descriptor, header, as_writable_bytes(span(entry->value)));
536 if (!result.status().ok()) {
537 return Status::INTERNAL;
538 }
539
540 auto value = span(entry->value.data(), result.size());
541
542 TRY(header.VerifyChecksum(
543 entry_header_format_.checksum, key, as_bytes(value)));
544
David Rogers3464d0a2020-02-07 11:45:46 -0800545 SectorDescriptor* old_sector = SectorFromAddress(key_descriptor.address);
David Rogersf0a35442020-02-04 12:16:38 -0800546
547 // Find a new sector for the entry and write it to the new location.
David Rogers8ce55cd2020-02-04 19:41:48 -0800548 SectorDescriptor* new_sector;
David Rogers3464d0a2020-02-07 11:45:46 -0800549 TRY(FindSectorWithSpace(&new_sector, header.size(), old_sector, true));
David Rogersdf025cd2020-02-06 17:05:34 -0800550 TRY(AppendEntry(new_sector, &key_descriptor, key, as_bytes(value)));
551
552 // Do the valid bytes accounting for the sector the entry was relocated out
553 // of.
David Rogers3464d0a2020-02-07 11:45:46 -0800554 old_sector->RemoveValidBytes(header.size());
David Rogersdf025cd2020-02-06 17:05:34 -0800555
556 return Status::OK;
David Rogersa12786b2020-01-31 16:02:33 -0800557}
558
David Rogers8db5a722020-02-03 18:28:34 -0800559// Find either an existing sector with enough space that is not the sector to
560// skip, or an empty sector. Maintains the invariant that there is always at
561// least 1 empty sector unless set to bypass the rule.
Wyatt Hepler5a33d8c2020-02-06 09:32:58 -0800562Status KeyValueStore::FindSectorWithSpace(
563 SectorDescriptor** found_sector,
564 size_t size,
565 const SectorDescriptor* sector_to_skip,
566 bool bypass_empty_sector_rule) {
David Rogers8ce55cd2020-02-04 19:41:48 -0800567 // The last_new_sector_ is the sector that was last selected as the "new empty
568 // sector" to write to. This last new sector is used as the starting point for
569 // the next "find a new empty sector to write to" operation. By using the last
570 // new sector as the start point we will cycle which empty sector is selected
571 // next, spreading the wear across all the empty sectors and get a wear
572 // leveling benefit, rather than putting more wear on the lower number
573 // sectors.
574 //
575 // Locally use the sector index for ease of iterating through the sectors. For
576 // the persistent storage use SectorDescriptor* rather than sector index
577 // because SectorDescriptor* is the standard way to identify a sector.
578 size_t last_new_sector_index_ = SectorIndex(last_new_sector_);
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800579 size_t start = (last_new_sector_index_ + 1) % sectors_.size();
David Rogers2761aeb2020-01-31 17:09:00 -0800580 SectorDescriptor* first_empty_sector = nullptr;
David Rogers8db5a722020-02-03 18:28:34 -0800581 bool at_least_two_empty_sectors = bypass_empty_sector_rule;
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800582
David Rogers67f4b6c2020-02-06 16:17:09 -0800583 DBG("Find sector with %zu bytes available", size);
584 if (sector_to_skip != nullptr) {
585 DBG(" Skip sector %zu", SectorIndex(sector_to_skip));
586 }
587 if (bypass_empty_sector_rule) {
588 DBG(" Bypassing empty sector rule");
589 }
590
David Rogers8ce55cd2020-02-04 19:41:48 -0800591 // Look for a partial sector to use with enough space. Immediately use the
592 // first one of those that is found. While scanning for a partial sector, keep
593 // track of the first empty sector and if a second sector was seen.
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800594 for (size_t j = 0; j < sectors_.size(); j++) {
595 size_t i = (j + start) % sectors_.size();
596 SectorDescriptor& sector = sectors_[i];
Keir Mierle8c352dc2020-02-02 13:58:19 -0800597
David Rogers8db5a722020-02-03 18:28:34 -0800598 if (sector_to_skip == &sector) {
David Rogers67f4b6c2020-02-06 16:17:09 -0800599 DBG(" Skipping the skip sector %zu", i);
David Rogers8db5a722020-02-03 18:28:34 -0800600 continue;
601 }
602
David Rogers67f4b6c2020-02-06 16:17:09 -0800603 DBG(" Examining sector %zu with %hu bytes available",
604 i,
605 sector.tail_free_bytes);
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800606 if (!SectorEmpty(sector) && sector.HasSpace(size)) {
David Rogers67f4b6c2020-02-06 16:17:09 -0800607 DBG(" Partially occupied sector %zu with enough space; done!", i);
David Rogers8ce55cd2020-02-04 19:41:48 -0800608 *found_sector = &sector;
609 return Status::OK;
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800610 }
611
612 if (SectorEmpty(sector)) {
613 if (first_empty_sector == nullptr) {
614 first_empty_sector = &sector;
615 } else {
616 at_least_two_empty_sectors = true;
Wyatt Hepler2ad60672020-01-21 08:00:16 -0800617 }
Wyatt Heplerb7609542020-01-24 10:29:54 -0800618 }
619 }
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800620
David Rogers8ce55cd2020-02-04 19:41:48 -0800621 // If the scan for a partial sector does not find a suitable sector, use the
622 // first empty sector that was found. Normally it is required to keep 1 empty
623 // sector after the sector found here, but that rule can be bypassed in
624 // special circumstances (such as during garbage collection).
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800625 if (at_least_two_empty_sectors) {
David Rogers67f4b6c2020-02-06 16:17:09 -0800626 DBG(" Found a usable empty sector; returning the first found (%zu)",
David Rogers8ce55cd2020-02-04 19:41:48 -0800627 SectorIndex(first_empty_sector));
628 last_new_sector_ = first_empty_sector;
629 *found_sector = first_empty_sector;
630 return Status::OK;
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800631 }
David Rogers8ce55cd2020-02-04 19:41:48 -0800632
633 // No sector was found.
David Rogers67f4b6c2020-02-06 16:17:09 -0800634 DBG(" Unable to find a usable sector");
David Rogers8ce55cd2020-02-04 19:41:48 -0800635 *found_sector = nullptr;
636 return Status::RESOURCE_EXHAUSTED;
Wyatt Heplerb7609542020-01-24 10:29:54 -0800637}
638
David Rogers2761aeb2020-01-31 17:09:00 -0800639Status KeyValueStore::FindOrRecoverSectorWithSpace(SectorDescriptor** sector,
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800640 size_t size) {
David Rogers8ce55cd2020-02-04 19:41:48 -0800641 Status result = FindSectorWithSpace(sector, size);
642 if (result.ok()) {
643 return result;
Wyatt Heplerb7609542020-01-24 10:29:54 -0800644 }
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800645 if (options_.partial_gc_on_write) {
David Rogers1541d612020-02-06 23:47:02 -0800646 // Garbage collect and then try again to find the best sector.
647 TRY(GarbageCollectOneSector());
648 return FindSectorWithSpace(sector, size);
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800649 }
David Rogers8ce55cd2020-02-04 19:41:48 -0800650 return result;
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800651}
652
David Rogers2761aeb2020-01-31 17:09:00 -0800653KeyValueStore::SectorDescriptor* KeyValueStore::FindSectorToGarbageCollect() {
654 SectorDescriptor* sector_candidate = nullptr;
David Rogersa12786b2020-01-31 16:02:33 -0800655 size_t candidate_bytes = 0;
656
657 // Step 1: Try to find a sectors with stale keys and no valid keys (no
658 // relocation needed). If any such sectors are found, use the sector with the
659 // most reclaimable bytes.
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800660 for (auto& sector : sectors_) {
David Rogersa12786b2020-01-31 16:02:33 -0800661 if ((sector.valid_bytes == 0) &&
662 (RecoverableBytes(sector) > candidate_bytes)) {
663 sector_candidate = &sector;
664 candidate_bytes = RecoverableBytes(sector);
665 }
666 }
667
668 // Step 2: If step 1 yields no sectors, just find the sector with the most
669 // reclaimable bytes.
670 if (sector_candidate == nullptr) {
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800671 for (auto& sector : sectors_) {
David Rogersa12786b2020-01-31 16:02:33 -0800672 if (RecoverableBytes(sector) > candidate_bytes) {
673 sector_candidate = &sector;
674 candidate_bytes = RecoverableBytes(sector);
675 }
676 }
677 }
678
David Rogers67f4b6c2020-02-06 16:17:09 -0800679 DBG("Found sector %zu to Garbage Collect, %zu recoverable bytes",
680 SectorIndex(sector_candidate),
681 RecoverableBytes(*sector_candidate));
David Rogersa12786b2020-01-31 16:02:33 -0800682 return sector_candidate;
683}
684
David Rogers1541d612020-02-06 23:47:02 -0800685Status KeyValueStore::GarbageCollectOneSector() {
David Rogers67f4b6c2020-02-06 16:17:09 -0800686 DBG("Garbage Collect a single sector");
687
David Rogersa12786b2020-01-31 16:02:33 -0800688 // Step 1: Find the sector to garbage collect
David Rogers2761aeb2020-01-31 17:09:00 -0800689 SectorDescriptor* sector_to_gc = FindSectorToGarbageCollect();
David Rogers3464d0a2020-02-07 11:45:46 -0800690 LogSectors();
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800691
David Rogersa12786b2020-01-31 16:02:33 -0800692 if (sector_to_gc == nullptr) {
693 return Status::RESOURCE_EXHAUSTED;
694 }
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800695
David Rogersa12786b2020-01-31 16:02:33 -0800696 // Step 2: Move any valid entries in the GC sector to other sectors
697 if (sector_to_gc->valid_bytes != 0) {
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800698 for (auto& descriptor : key_descriptors_) {
David Rogers2761aeb2020-01-31 17:09:00 -0800699 if (AddressInSector(*sector_to_gc, descriptor.address)) {
David Rogers67f4b6c2020-02-06 16:17:09 -0800700 DBG(" Relocate entry");
David Rogers2761aeb2020-01-31 17:09:00 -0800701 TRY(RelocateEntry(descriptor));
David Rogersa12786b2020-01-31 16:02:33 -0800702 }
Wyatt Heplerb7609542020-01-24 10:29:54 -0800703 }
704 }
Wyatt Heplerb7609542020-01-24 10:29:54 -0800705
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800706 if (sector_to_gc->valid_bytes != 0) {
David Rogers67f4b6c2020-02-06 16:17:09 -0800707 ERR(" Failed to relocate valid entries from sector being garbage "
708 "collected, %hu valid bytes remain",
709 sector_to_gc->valid_bytes);
Wyatt Heplerb7609542020-01-24 10:29:54 -0800710 return Status::INTERNAL;
711 }
712
David Rogersa12786b2020-01-31 16:02:33 -0800713 // Step 3: Reinitialize the sector
714 sector_to_gc->tail_free_bytes = 0;
715 TRY(partition_.Erase(SectorBaseAddress(sector_to_gc), 1));
716 sector_to_gc->tail_free_bytes = partition_.sector_size_bytes();
Wyatt Heplerb7609542020-01-24 10:29:54 -0800717
David Rogers67f4b6c2020-02-06 16:17:09 -0800718 DBG(" Garbage Collect complete");
David Rogers50185ad2020-02-07 00:02:46 -0800719 LogSectors();
David Rogersa12786b2020-01-31 16:02:33 -0800720 return Status::OK;
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800721}
722
David Rogers2761aeb2020-01-31 17:09:00 -0800723Status KeyValueStore::AppendEntry(SectorDescriptor* sector,
724 KeyDescriptor* key_descriptor,
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800725 const string_view key,
Wyatt Hepler5a33d8c2020-02-06 09:32:58 -0800726 span<const byte> value,
727 KeyDescriptor::State new_state) {
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800728 // write header, key, and value
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800729 EntryHeader header;
730
Wyatt Hepler5a33d8c2020-02-06 09:32:58 -0800731 if (new_state == KeyDescriptor::kDeleted) {
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800732 header = EntryHeader::Tombstone(entry_header_format_.magic,
733 entry_header_format_.checksum,
734 key,
Wyatt Hepler97fc7942020-02-06 15:55:45 -0800735 partition_.alignment_bytes(),
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800736 key_descriptor->key_version + 1);
737 } else {
738 header = EntryHeader::Valid(entry_header_format_.magic,
739 entry_header_format_.checksum,
740 key,
741 value,
Wyatt Hepler97fc7942020-02-06 15:55:45 -0800742 partition_.alignment_bytes(),
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800743 key_descriptor->key_version + 1);
744 }
745
Wyatt Hepler97fc7942020-02-06 15:55:45 -0800746 DBG("Appending %zu B entry with key version: %x",
747 header.size(),
748 unsigned(header.key_version()));
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800749
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800750 Address address = NextWritableAddress(sector);
David Rogers3464d0a2020-02-07 11:45:46 -0800751 DBG("Appending to address: %#zx", size_t(address));
Wyatt Hepler5a33d8c2020-02-06 09:32:58 -0800752
753 // Handles writing multiple concatenated buffers, while breaking up the writes
754 // into alignment-sized blocks.
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800755 TRY_ASSIGN(
Wyatt Hepler116d1162020-02-06 09:42:59 -0800756 const size_t written,
757 partition_.WriteAligned(
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800758 address, {as_bytes(span(&header, 1)), as_bytes(span(key)), value}));
759
760 if (options_.verify_on_write) {
Wyatt Hepler0a223582020-02-04 17:47:40 -0800761 TRY(header.VerifyChecksumInFlash(
762 &partition_, address, entry_header_format_.checksum));
Wyatt Heplerb7609542020-01-24 10:29:54 -0800763 }
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800764
David Rogers2761aeb2020-01-31 17:09:00 -0800765 key_descriptor->address = address;
766 key_descriptor->key_version = header.key_version();
Wyatt Hepler5a33d8c2020-02-06 09:32:58 -0800767 key_descriptor->state = new_state;
768
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800769 sector->valid_bytes += written;
David Rogers2be76b02020-02-06 17:33:05 -0800770 sector->RemoveFreeBytes(written);
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800771 return Status::OK;
Wyatt Heplerb7609542020-01-24 10:29:54 -0800772}
773
Keir Mierle8c352dc2020-02-02 13:58:19 -0800774void KeyValueStore::LogDebugInfo() {
Keir Mierle8c352dc2020-02-02 13:58:19 -0800775 const size_t sector_size_bytes = partition_.sector_size_bytes();
776 DBG("====================== KEY VALUE STORE DUMP =========================");
777 DBG(" ");
778 DBG("Flash partition:");
Wyatt Heplerad0a7932020-02-06 08:20:38 -0800779 DBG(" Sector count = %zu", partition_.sector_count());
780 DBG(" Sector max count = %zu", kMaxUsableSectors);
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800781 DBG(" Sectors in use = %zu", sectors_.size());
Keir Mierle8c352dc2020-02-02 13:58:19 -0800782 DBG(" Sector size = %zu", sector_size_bytes);
783 DBG(" Total size = %zu", partition_.size_bytes());
784 DBG(" Alignment = %zu", partition_.alignment_bytes());
785 DBG(" ");
786 DBG("Key descriptors:");
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800787 DBG(" Entry count = %zu", key_descriptors_.size());
Keir Mierle8c352dc2020-02-02 13:58:19 -0800788 DBG(" Max entry count = %zu", kMaxEntries);
789 DBG(" ");
790 DBG(" # hash version address address (hex)");
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800791 for (size_t i = 0; i < key_descriptors_.size(); ++i) {
792 const KeyDescriptor& kd = key_descriptors_[i];
Keir Mierle8c352dc2020-02-02 13:58:19 -0800793 DBG(" |%3zu: | %8zx |%8zu | %8zu | %8zx",
794 i,
795 size_t(kd.key_hash),
796 size_t(kd.key_version),
797 size_t(kd.address),
798 size_t(kd.address));
799 }
800 DBG(" ");
801
802 DBG("Sector descriptors:");
803 DBG(" # tail free valid has_space");
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800804 for (size_t sector_id = 0; sector_id < sectors_.size(); ++sector_id) {
805 const SectorDescriptor& sd = sectors_[sector_id];
Keir Mierle8c352dc2020-02-02 13:58:19 -0800806 DBG(" |%3zu: | %8zu |%8zu | %s",
807 sector_id,
808 size_t(sd.tail_free_bytes),
809 size_t(sd.valid_bytes),
810 sd.tail_free_bytes ? "YES" : "");
811 }
812 DBG(" ");
813
814 // TODO: This should stop logging after some threshold.
815 // size_t dumped_bytes = 0;
816 DBG("Sector raw data:");
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800817 for (size_t sector_id = 0; sector_id < sectors_.size(); ++sector_id) {
Keir Mierle8c352dc2020-02-02 13:58:19 -0800818 // Read sector data. Yes, this will blow the stack on embedded.
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800819 std::array<byte, 500> raw_sector_data; // TODO!!!
Keir Mierle8c352dc2020-02-02 13:58:19 -0800820 StatusWithSize sws =
821 partition_.Read(sector_id * sector_size_bytes, raw_sector_data);
822 DBG("Read: %zu bytes", sws.size());
823
824 DBG(" base addr offs 0 1 2 3 4 5 6 7");
825 for (size_t i = 0; i < sector_size_bytes; i += 8) {
826 DBG(" %3zu %8zx %5zu | %02x %02x %02x %02x %02x %02x %02x %02x",
827 sector_id,
828 (sector_id * sector_size_bytes) + i,
829 i,
830 static_cast<unsigned int>(raw_sector_data[i + 0]),
831 static_cast<unsigned int>(raw_sector_data[i + 1]),
832 static_cast<unsigned int>(raw_sector_data[i + 2]),
833 static_cast<unsigned int>(raw_sector_data[i + 3]),
834 static_cast<unsigned int>(raw_sector_data[i + 4]),
835 static_cast<unsigned int>(raw_sector_data[i + 5]),
836 static_cast<unsigned int>(raw_sector_data[i + 6]),
837 static_cast<unsigned int>(raw_sector_data[i + 7]));
838
839 // TODO: Fix exit condition.
840 if (i > 128) {
841 break;
842 }
843 }
844 DBG(" ");
845 }
846
847 DBG("////////////////////// KEY VALUE STORE DUMP END /////////////////////");
848}
849
David Rogers50185ad2020-02-07 00:02:46 -0800850void KeyValueStore::LogSectors(void) {
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800851 for (auto& sector : sectors_) {
David Rogers50185ad2020-02-07 00:02:46 -0800852 DBG(" - Sector %zu: valid %hu, recoverable %zu, free %hu",
853 SectorIndex(&sector),
854 sector.valid_bytes,
855 RecoverableBytes(sector),
856 sector.tail_free_bytes);
857 }
858}
859
David Rogers3464d0a2020-02-07 11:45:46 -0800860void KeyValueStore::SectorDescriptor::RemoveValidBytes(size_t size) {
861 // TODO: add safety check for valid_bytes > size.
862 if (size > valid_bytes) {
863 CRT("!!!!!!!!!!!!!!!");
864 CRT("Remove too many valid bytes!!! remove %zu, only have %hu",
865 size,
866 valid_bytes);
867 valid_bytes = size;
868 }
869 valid_bytes -= size;
870}
871
Wyatt Hepler2ad60672020-01-21 08:00:16 -0800872} // namespace pw::kvs