blob: ca49b5c0ed77b492fef6541f5fa1f09690d93789 [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 Hepler1fc11042020-02-19 17:17:51 -080030using internal::Entry;
Wyatt Hepleracaacf92020-01-24 10:58:30 -080031using std::byte;
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -080032using std::string_view;
Wyatt Hepleracaacf92020-01-24 10:58:30 -080033
Wyatt Heplera00d1ef2020-02-14 14:31:26 -080034constexpr bool InvalidKey(std::string_view key) {
35 return key.empty() || (key.size() > Entry::kMaxKeyLength);
36}
37
38} // namespace
39
Wyatt Heplerad0a7932020-02-06 08:20:38 -080040KeyValueStore::KeyValueStore(FlashPartition* partition,
Wyatt Hepler38ce30f2020-02-19 11:48:31 -080041 Vector<KeyDescriptor>& key_descriptor_list,
42 Vector<SectorDescriptor>& sector_descriptor_list,
Wyatt Heplerad0a7932020-02-06 08:20:38 -080043 const EntryHeaderFormat& format,
44 const Options& options)
45 : partition_(*partition),
46 entry_header_format_(format),
Wyatt Hepler38ce30f2020-02-19 11:48:31 -080047 key_descriptors_(key_descriptor_list),
Wyatt Heplerd2298282020-02-20 17:12:45 -080048 sectors_(sector_descriptor_list),
49 options_(options) {
50 Reset();
51}
Wyatt Heplerad0a7932020-02-06 08:20:38 -080052
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -080053Status KeyValueStore::Init() {
Wyatt Heplerd2298282020-02-20 17:12:45 -080054 Reset();
55
David Rogers2e9e0c82020-02-13 15:06:06 -080056 INF("Initializing key value store");
Wyatt Hepler38ce30f2020-02-19 11:48:31 -080057 if (partition_.sector_count() > sectors_.max_size()) {
David Rogers2e9e0c82020-02-13 15:06:06 -080058 ERR("KVS init failed: kMaxUsableSectors (=%zu) must be at least as "
59 "large as the number of sectors in the flash partition (=%zu)",
Wyatt Hepler38ce30f2020-02-19 11:48:31 -080060 sectors_.max_size(),
David Rogers2e9e0c82020-02-13 15:06:06 -080061 partition_.sector_count());
Wyatt Heplerad0a7932020-02-06 08:20:38 -080062 return Status::FAILED_PRECONDITION;
63 }
64
Keir Mierle8c352dc2020-02-02 13:58:19 -080065 const size_t sector_size_bytes = partition_.sector_size_bytes();
Keir Mierle8c352dc2020-02-02 13:58:19 -080066
David Rogersf0a35442020-02-04 12:16:38 -080067 if (working_buffer_.size() < sector_size_bytes) {
David Rogers2e9e0c82020-02-13 15:06:06 -080068 ERR("KVS init failed: working_buffer_ (%zu bytes) is smaller than sector "
69 "size (%zu bytes)",
David Rogersf0a35442020-02-04 12:16:38 -080070 working_buffer_.size(),
71 sector_size_bytes);
72 return Status::INVALID_ARGUMENT;
73 }
74
Keir Mierle8c352dc2020-02-02 13:58:19 -080075 DBG("First pass: Read all entries from all sectors");
Wyatt Hepler2c7eca02020-02-18 16:01:42 -080076 Address sector_address = 0;
Keir Mierle8c352dc2020-02-02 13:58:19 -080077
Wyatt Heplerd2298282020-02-20 17:12:45 -080078 sectors_.assign(partition_.sector_count(),
79 SectorDescriptor(sector_size_bytes));
80
Wyatt Hepler2c7eca02020-02-18 16:01:42 -080081 for (SectorDescriptor& sector : sectors_) {
82 // Reset the sector's valid and writable byte counts. These will be updated
83 // after reading each entry.
Keir Mierle8c352dc2020-02-02 13:58:19 -080084 Address entry_address = sector_address;
85
Wyatt Hepler2c7eca02020-02-18 16:01:42 -080086 for (int num_entries_in_sector = 0; true; num_entries_in_sector++) {
87 DBG("Load entry: sector=%" PRIx32 ", entry#=%d, address=%" PRIx32,
88 sector_address,
Keir Mierle8c352dc2020-02-02 13:58:19 -080089 num_entries_in_sector,
Wyatt Hepler2c7eca02020-02-18 16:01:42 -080090 entry_address);
Keir Mierle8c352dc2020-02-02 13:58:19 -080091
Wyatt Hepler2c7eca02020-02-18 16:01:42 -080092 if (!AddressInSector(sector, entry_address)) {
Keir Mierle8c352dc2020-02-02 13:58:19 -080093 DBG("Fell off end of sector; moving to the next sector");
94 break;
95 }
96
97 Address next_entry_address;
98 Status status = LoadEntry(entry_address, &next_entry_address);
99 if (status == Status::NOT_FOUND) {
100 DBG("Hit un-written data in sector; moving to the next sector");
101 break;
102 }
103 if (status == Status::DATA_LOSS) {
104 // It's not clear KVS can make a unilateral decision about what to do
105 // in corruption cases. It's an application decision, for which we
106 // should offer some configurability. For now, entirely bail out of
107 // loading and give up.
108 //
109 // Later, scan for remaining valid keys; since it's entirely possible
110 // that there is a duplicate of the key elsewhere and everything is
111 // fine. Later, we can wipe and maybe recover the sector.
112 //
113 // TODO: Implement rest-of-sector scanning for valid entries.
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800114 ERR("KVS init failed: data loss detected in sector %u at address %zu",
115 SectorIndex(&sector),
116 size_t(entry_address));
Keir Mierle8c352dc2020-02-02 13:58:19 -0800117 return Status::DATA_LOSS;
118 }
119 TRY(status);
120
121 // Entry loaded successfully; so get ready to load the next one.
122 entry_address = next_entry_address;
123
124 // Update of the number of writable bytes in this sector.
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800125 sector.set_writable_bytes(sector_size_bytes -
126 (entry_address - sector_address));
Keir Mierle8c352dc2020-02-02 13:58:19 -0800127 }
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800128
129 sector_address += sector_size_bytes;
Keir Mierle8c352dc2020-02-02 13:58:19 -0800130 }
131
132 DBG("Second pass: Count valid bytes in each sector");
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800133 const KeyDescriptor* newest_key = nullptr;
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800134
Keir Mierle8c352dc2020-02-02 13:58:19 -0800135 // For every valid key, increment the valid bytes for that sector.
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800136 for (KeyDescriptor& key_descriptor : key_descriptors_) {
Wyatt Heplere541e072020-02-14 09:10:53 -0800137 Entry entry;
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800138 TRY(Entry::Read(partition_, key_descriptor.address(), &entry));
139 SectorFromKey(key_descriptor)->AddValidBytes(entry.size());
140
141 if (key_descriptor.IsNewerThan(last_transaction_id_)) {
142 last_transaction_id_ = key_descriptor.transaction_id();
143 newest_key = &key_descriptor;
144 }
Keir Mierle8c352dc2020-02-02 13:58:19 -0800145 }
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800146
147 if (newest_key == nullptr) {
148 last_new_sector_ = sectors_.begin();
149 } else {
150 last_new_sector_ = SectorFromKey(newest_key);
151 }
152
Wyatt Hepler729f28c2020-02-05 09:46:00 -0800153 initialized_ = true;
David Rogers2e9e0c82020-02-13 15:06:06 -0800154
Armando Montanez5464d5f2020-02-20 10:12:20 -0800155 INF("KeyValueStore init complete: active keys %zu, deleted keys %zu, sectors "
David Rogers2e9e0c82020-02-13 15:06:06 -0800156 "%zu, logical sector size %zu bytes",
157 size(),
158 (key_descriptors_.size() - size()),
159 sectors_.size(),
160 partition_.sector_size_bytes());
161
Keir Mierle8c352dc2020-02-02 13:58:19 -0800162 return Status::OK;
163}
164
165Status KeyValueStore::LoadEntry(Address entry_address,
166 Address* next_entry_address) {
Wyatt Heplere541e072020-02-14 09:10:53 -0800167 Entry entry;
168 TRY(Entry::Read(partition_, entry_address, &entry));
Keir Mierle8c352dc2020-02-02 13:58:19 -0800169
170 // TODO: Handle multiple magics for formats that have changed.
Wyatt Heplere541e072020-02-14 09:10:53 -0800171 if (entry.magic() != entry_header_format_.magic) {
Keir Mierle8c352dc2020-02-02 13:58:19 -0800172 // TODO: It may be cleaner to have some logging helpers for these cases.
Wyatt Heplere541e072020-02-14 09:10:53 -0800173 ERR("Found corrupt magic: %zx; expecting %zx; at address %zx",
174 size_t(entry.magic()),
Keir Mierle8c352dc2020-02-02 13:58:19 -0800175 size_t(entry_header_format_.magic),
176 size_t(entry_address));
177 return Status::DATA_LOSS;
178 }
179
180 // Read the key from flash & validate the entry (which reads the value).
Wyatt Heplera00d1ef2020-02-14 14:31:26 -0800181 Entry::KeyBuffer key_buffer;
Wyatt Heplere541e072020-02-14 09:10:53 -0800182 TRY_ASSIGN(size_t key_length, entry.ReadKey(key_buffer));
183 const string_view key(key_buffer.data(), key_length);
Wyatt Heplerbab0e202020-02-04 07:40:08 -0800184
Wyatt Heplere541e072020-02-14 09:10:53 -0800185 TRY(entry.VerifyChecksumInFlash(entry_header_format_.checksum));
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800186 TRY(AppendNewOrOverwriteStaleExistingDescriptor(entry.descriptor(key)));
Keir Mierle8c352dc2020-02-02 13:58:19 -0800187
Wyatt Heplere541e072020-02-14 09:10:53 -0800188 *next_entry_address = entry.next_address();
Keir Mierle8c352dc2020-02-02 13:58:19 -0800189 return Status::OK;
190}
191
192// TODO: This method is the trigger of the O(valid_entries * all_entries) time
193// complexity for reading. At some cost to memory, this could be optimized by
194// using a hash table instead of scanning, but in practice this should be fine
195// for a small number of keys
196Status KeyValueStore::AppendNewOrOverwriteStaleExistingDescriptor(
197 const KeyDescriptor& key_descriptor) {
198 // With the new key descriptor, either add it to the descriptor table or
199 // overwrite an existing entry with an older version of the key.
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800200 KeyDescriptor* existing_descriptor = FindDescriptor(key_descriptor.hash());
Keir Mierle8c352dc2020-02-02 13:58:19 -0800201
Wyatt Hepler5406a672020-02-18 15:42:38 -0800202 // Write a new entry.
203 if (existing_descriptor == nullptr) {
204 if (key_descriptors_.full()) {
205 return Status::RESOURCE_EXHAUSTED;
206 }
207 key_descriptors_.push_back(key_descriptor);
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800208 } else if (key_descriptor.IsNewerThan(
209 existing_descriptor->transaction_id())) {
Wyatt Hepler5406a672020-02-18 15:42:38 -0800210 // Existing entry is old; replace the existing entry with the new one.
211 *existing_descriptor = key_descriptor;
212 } else {
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800213 // Otherwise, check if the entries have a duplicate transaction ID, which is
214 // not valid.
215 if (existing_descriptor->transaction_id() ==
216 key_descriptor.transaction_id()) {
217 ERR("Data loss: Duplicated old(=%zu) and new(=%zu) transaction ID",
218 size_t(existing_descriptor->transaction_id()),
219 size_t(key_descriptor.transaction_id()));
Wyatt Hepler5406a672020-02-18 15:42:38 -0800220 return Status::DATA_LOSS;
221 }
222 DBG("Found stale entry when appending; ignoring");
Keir Mierle8c352dc2020-02-02 13:58:19 -0800223 }
Keir Mierle8c352dc2020-02-02 13:58:19 -0800224 return Status::OK;
225}
226
Keir Mierle8c352dc2020-02-02 13:58:19 -0800227KeyValueStore::KeyDescriptor* KeyValueStore::FindDescriptor(uint32_t hash) {
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800228 for (KeyDescriptor& key_descriptor : key_descriptors_) {
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800229 if (key_descriptor.hash() == hash) {
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800230 return &key_descriptor;
Keir Mierle8c352dc2020-02-02 13:58:19 -0800231 }
232 }
233 return nullptr;
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800234}
235
236StatusWithSize KeyValueStore::Get(string_view key,
Wyatt Hepler5f6efc02020-02-18 16:54:31 -0800237 span<byte> value_buffer,
238 size_t offset_bytes) const {
Wyatt Hepler50f70772020-02-13 11:25:10 -0800239 TRY_WITH_SIZE(CheckOperation(key));
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800240
David Rogers2761aeb2020-01-31 17:09:00 -0800241 const KeyDescriptor* key_descriptor;
Wyatt Hepler2d401692020-02-13 16:01:23 -0800242 TRY_WITH_SIZE(FindExistingKeyDescriptor(key, &key_descriptor));
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800243
Wyatt Heplere541e072020-02-14 09:10:53 -0800244 Entry entry;
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800245 TRY_WITH_SIZE(Entry::Read(partition_, key_descriptor->address(), &entry));
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800246
Wyatt Hepler5f6efc02020-02-18 16:54:31 -0800247 StatusWithSize result = entry.ReadValue(value_buffer, offset_bytes);
248 if (result.ok() && options_.verify_on_read && offset_bytes == 0u) {
David Rogerscf680ab2020-02-12 23:28:32 -0800249 Status verify_result =
Wyatt Heplere541e072020-02-14 09:10:53 -0800250 entry.VerifyChecksum(entry_header_format_.checksum,
251 key,
252 value_buffer.subspan(0, result.size()));
David Rogerscf680ab2020-02-12 23:28:32 -0800253 if (!verify_result.ok()) {
Wyatt Hepler50f70772020-02-13 11:25:10 -0800254 std::memset(
255 value_buffer.subspan(0, result.size()).data(), 0, result.size());
256 return StatusWithSize(verify_result);
David Rogerscf680ab2020-02-12 23:28:32 -0800257 }
258
259 return StatusWithSize(verify_result, result.size());
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800260 }
261 return result;
262}
263
264Status KeyValueStore::Put(string_view key, span<const byte> value) {
Keir Mierle8c352dc2020-02-02 13:58:19 -0800265 DBG("Writing key/value; key length=%zu, value length=%zu",
266 key.size(),
267 value.size());
Wyatt Hepler729f28c2020-02-05 09:46:00 -0800268
269 TRY(CheckOperation(key));
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800270
Wyatt Hepler5406a672020-02-18 15:42:38 -0800271 if (Entry::size(partition_, key, value) > partition_.sector_size_bytes()) {
272 DBG("%zu B value with %zu B key cannot fit in one sector",
273 value.size(),
274 key.size());
275 return Status::INVALID_ARGUMENT;
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800276 }
277
David Rogers2761aeb2020-01-31 17:09:00 -0800278 KeyDescriptor* key_descriptor;
Wyatt Hepler2d401692020-02-13 16:01:23 -0800279 Status status = FindKeyDescriptor(key, &key_descriptor);
280
281 if (status.ok()) {
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800282 DBG("Overwriting entry for key %#08" PRIx32 " in sector %u",
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800283 key_descriptor->hash(),
284 SectorIndex(SectorFromKey(key_descriptor)));
Wyatt Hepler5a33d8c2020-02-06 09:32:58 -0800285 return WriteEntryForExistingKey(
286 key_descriptor, KeyDescriptor::kValid, key, value);
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800287 }
David Rogers2761aeb2020-01-31 17:09:00 -0800288
Wyatt Hepler2d401692020-02-13 16:01:23 -0800289 if (status == Status::NOT_FOUND) {
290 return WriteEntryForNewKey(key, value);
291 }
292
293 return status;
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800294}
295
296Status KeyValueStore::Delete(string_view key) {
Wyatt Hepler729f28c2020-02-05 09:46:00 -0800297 TRY(CheckOperation(key));
298
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800299 KeyDescriptor* key_descriptor;
Wyatt Hepler2d401692020-02-13 16:01:23 -0800300 TRY(FindExistingKeyDescriptor(key, &key_descriptor));
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800301
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800302 DBG("Writing tombstone for key %#08" PRIx32 " in sector %u",
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800303 key_descriptor->hash(),
304 SectorIndex(SectorFromKey(key_descriptor)));
Wyatt Hepler5a33d8c2020-02-06 09:32:58 -0800305 return WriteEntryForExistingKey(
306 key_descriptor, KeyDescriptor::kDeleted, key, {});
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800307}
308
309KeyValueStore::iterator& KeyValueStore::iterator::operator++() {
310 // Skip to the next entry that is valid (not deleted).
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800311 while (++index_ < item_.kvs_.key_descriptors_.size() &&
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800312 descriptor().deleted()) {
313 }
314 return *this;
315}
316
317const KeyValueStore::Item& KeyValueStore::iterator::operator*() {
318 std::memset(item_.key_buffer_.data(), 0, item_.key_buffer_.size());
319
Wyatt Heplere541e072020-02-14 09:10:53 -0800320 Entry entry;
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800321 if (Entry::Read(item_.kvs_.partition_, descriptor().address(), &entry).ok()) {
Wyatt Heplere541e072020-02-14 09:10:53 -0800322 entry.ReadKey(item_.key_buffer_);
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800323 }
324
325 return item_;
326}
327
328KeyValueStore::iterator KeyValueStore::begin() const {
329 size_t i = 0;
330 // Skip over any deleted entries at the start of the descriptor list.
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800331 while (i < key_descriptors_.size() && key_descriptors_[i].deleted()) {
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800332 i += 1;
333 }
334 return iterator(*this, i);
335}
336
337// TODO(hepler): The valid entry count could be tracked in the KVS to avoid the
338// need for this for-loop.
339size_t KeyValueStore::size() const {
340 size_t valid_entries = 0;
341
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800342 for (const KeyDescriptor& key_descriptor : key_descriptors_) {
343 if (!key_descriptor.deleted()) {
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800344 valid_entries += 1;
345 }
346 }
347
348 return valid_entries;
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800349}
350
Wyatt Heplered163b02020-02-03 17:49:32 -0800351StatusWithSize KeyValueStore::ValueSize(std::string_view key) const {
Wyatt Hepler50f70772020-02-13 11:25:10 -0800352 TRY_WITH_SIZE(CheckOperation(key));
Wyatt Heplered163b02020-02-03 17:49:32 -0800353
354 const KeyDescriptor* key_descriptor;
Wyatt Hepler2d401692020-02-13 16:01:23 -0800355 TRY_WITH_SIZE(FindExistingKeyDescriptor(key, &key_descriptor));
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800356
Wyatt Heplere541e072020-02-14 09:10:53 -0800357 Entry entry;
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800358 TRY_WITH_SIZE(Entry::Read(partition_, key_descriptor->address(), &entry));
Wyatt Heplered163b02020-02-03 17:49:32 -0800359
Wyatt Heplere541e072020-02-14 09:10:53 -0800360 return StatusWithSize(entry.value_size());
Wyatt Heplered163b02020-02-03 17:49:32 -0800361}
362
Wyatt Hepler6e3a83b2020-02-04 07:36:45 -0800363Status KeyValueStore::FixedSizeGet(std::string_view key,
364 byte* value,
365 size_t size_bytes) const {
366 // Ensure that the size of the stored value matches the size of the type.
367 // Otherwise, report error. This check avoids potential memory corruption.
368 StatusWithSize result = ValueSize(key);
369 if (!result.ok()) {
370 return result.status();
Keir Mierle8c352dc2020-02-02 13:58:19 -0800371 }
Wyatt Hepler6e3a83b2020-02-04 07:36:45 -0800372 if (result.size() != size_bytes) {
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800373 DBG("Requested %zu B read, but value is %zu B", size_bytes, result.size());
Wyatt Hepler6e3a83b2020-02-04 07:36:45 -0800374 return Status::INVALID_ARGUMENT;
Wyatt Heplerbab0e202020-02-04 07:40:08 -0800375 }
Wyatt Hepler6e3a83b2020-02-04 07:36:45 -0800376 return Get(key, span(value, size_bytes)).status();
Keir Mierle8c352dc2020-02-02 13:58:19 -0800377}
378
Wyatt Hepler729f28c2020-02-05 09:46:00 -0800379Status KeyValueStore::CheckOperation(string_view key) const {
Wyatt Hepleracaacf92020-01-24 10:58:30 -0800380 if (InvalidKey(key)) {
Wyatt Heplerb7609542020-01-24 10:29:54 -0800381 return Status::INVALID_ARGUMENT;
382 }
Wyatt Heplerd2298282020-02-20 17:12:45 -0800383 if (!initialized()) {
Wyatt Heplerb7609542020-01-24 10:29:54 -0800384 return Status::FAILED_PRECONDITION;
385 }
Wyatt Heplerb7609542020-01-24 10:29:54 -0800386 return Status::OK;
387}
388
Wyatt Hepler2d401692020-02-13 16:01:23 -0800389// Searches for a KeyDescriptor that matches this key and sets *result to point
390// to it if one is found.
391//
392// OK: there is a matching descriptor and *result is set
393// NOT_FOUND: there is no descriptor that matches this key, but this key
394// has a unique hash (and could potentially be added to the KVS)
395// ALREADY_EXISTS: there is no descriptor that matches this key, but the
396// key's hash collides with the hash for an existing descriptor
397//
David Rogers2761aeb2020-01-31 17:09:00 -0800398Status KeyValueStore::FindKeyDescriptor(string_view key,
399 const KeyDescriptor** result) const {
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800400 const uint32_t hash = internal::Hash(key);
Wyatt Heplera00d1ef2020-02-14 14:31:26 -0800401 Entry::KeyBuffer key_buffer;
Wyatt Heplerb7609542020-01-24 10:29:54 -0800402
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800403 for (auto& descriptor : key_descriptors_) {
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800404 if (descriptor.hash() == hash) {
Wyatt Heplere541e072020-02-14 09:10:53 -0800405 TRY(Entry::ReadKey(
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800406 partition_, descriptor.address(), key.size(), key_buffer.data()));
Wyatt Heplerb7609542020-01-24 10:29:54 -0800407
Wyatt Heplere541e072020-02-14 09:10:53 -0800408 if (key == string_view(key_buffer.data(), key.size())) {
Wyatt Hepler5a33d8c2020-02-06 09:32:58 -0800409 DBG("Found match for key hash 0x%08" PRIx32, hash);
David Rogers2761aeb2020-01-31 17:09:00 -0800410 *result = &descriptor;
Wyatt Heplerb7609542020-01-24 10:29:54 -0800411 return Status::OK;
Wyatt Hepler2d401692020-02-13 16:01:23 -0800412 } else {
413 WRN("Found key hash collision for 0x%08" PRIx32, hash);
414 return Status::ALREADY_EXISTS;
Wyatt Heplerb7609542020-01-24 10:29:54 -0800415 }
Wyatt Heplerb7609542020-01-24 10:29:54 -0800416 }
417 }
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800418 return Status::NOT_FOUND;
419}
420
Wyatt Hepler2d401692020-02-13 16:01:23 -0800421// Searches for a KeyDescriptor that matches this key and sets *result to point
422// to it if one is found.
423//
424// OK: there is a matching descriptor and *result is set
425// NOT_FOUND: there is no descriptor that matches this key
426//
427Status KeyValueStore::FindExistingKeyDescriptor(
428 string_view key, const KeyDescriptor** result) const {
429 Status status = FindKeyDescriptor(key, result);
430
431 // If the key's hash collides with an existing key or if the key is deleted,
432 // treat it as if it is not in the KVS.
433 if (status == Status::ALREADY_EXISTS ||
434 (status.ok() && (*result)->deleted())) {
435 return Status::NOT_FOUND;
436 }
437 return status;
438}
439
David Rogers2761aeb2020-01-31 17:09:00 -0800440Status KeyValueStore::WriteEntryForExistingKey(KeyDescriptor* key_descriptor,
Wyatt Hepler5a33d8c2020-02-06 09:32:58 -0800441 KeyDescriptor::State new_state,
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800442 string_view key,
443 span<const byte> value) {
Wyatt Hepler5a33d8c2020-02-06 09:32:58 -0800444 // Find the original entry and sector to update the sector's valid_bytes.
Wyatt Hepler30a52152020-02-12 11:26:05 -0800445 Entry original_entry;
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800446 TRY(Entry::Read(partition_, key_descriptor->address(), &original_entry));
447 SectorDescriptor* old_sector = SectorFromKey(key_descriptor);
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800448
David Rogers2761aeb2020-01-31 17:09:00 -0800449 SectorDescriptor* sector;
Wyatt Hepler5406a672020-02-18 15:42:38 -0800450 TRY(FindOrRecoverSectorWithSpace(&sector,
451 Entry::size(partition_, key, value)));
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800452 DBG("Writing existing entry; found sector %u (%#" PRIx32 ")",
453 SectorIndex(sector),
454 SectorBaseAddress(sector));
David Rogers3464d0a2020-02-07 11:45:46 -0800455
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800456 if (old_sector != SectorFromKey(key_descriptor)) {
David Rogers3464d0a2020-02-07 11:45:46 -0800457 DBG("Sector for old entry (size %zu) was garbage collected. Old entry "
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800458 "relocated to sector %u",
David Rogers3464d0a2020-02-07 11:45:46 -0800459 original_entry.size(),
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800460 SectorIndex(SectorFromKey(key_descriptor)));
David Rogers3464d0a2020-02-07 11:45:46 -0800461
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800462 old_sector = SectorFromKey(key_descriptor);
David Rogers3464d0a2020-02-07 11:45:46 -0800463 }
464
Wyatt Hepler5a33d8c2020-02-06 09:32:58 -0800465 TRY(AppendEntry(sector, key_descriptor, key, value, new_state));
466
David Rogers3464d0a2020-02-07 11:45:46 -0800467 old_sector->RemoveValidBytes(original_entry.size());
Wyatt Hepler5a33d8c2020-02-06 09:32:58 -0800468 return Status::OK;
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800469}
470
471Status KeyValueStore::WriteEntryForNewKey(string_view key,
472 span<const byte> value) {
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800473 if (key_descriptors_.full()) {
Keir Mierle8c352dc2020-02-02 13:58:19 -0800474 WRN("KVS full: trying to store a new entry, but can't. Have %zu entries",
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800475 key_descriptors_.size());
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800476 return Status::RESOURCE_EXHAUSTED;
477 }
478
David Rogers2761aeb2020-01-31 17:09:00 -0800479 SectorDescriptor* sector;
Wyatt Hepler5406a672020-02-18 15:42:38 -0800480 TRY(FindOrRecoverSectorWithSpace(&sector,
481 Entry::size(partition_, key, value)));
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800482 DBG("Writing new entry; found sector: %u", SectorIndex(sector));
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800483
484 // Create the KeyDescriptor that will be added to the list. The transaction ID
485 // and address will be set by AppendEntry.
486 KeyDescriptor key_descriptor(key);
Wyatt Hepler0af6ad92020-02-13 15:54:46 -0800487 TRY(AppendEntry(sector, &key_descriptor, key, value, KeyDescriptor::kValid));
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800488
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800489 // Only add the entry when we are certain the write succeeded.
490 key_descriptors_.push_back(key_descriptor);
Wyatt Heplerb7609542020-01-24 10:29:54 -0800491 return Status::OK;
492}
493
David Rogers2761aeb2020-01-31 17:09:00 -0800494Status KeyValueStore::RelocateEntry(KeyDescriptor& key_descriptor) {
David Rogersf0a35442020-02-04 12:16:38 -0800495 struct TempEntry {
Wyatt Heplere541e072020-02-14 09:10:53 -0800496 Entry::KeyBuffer key;
David Rogersf0a35442020-02-04 12:16:38 -0800497 std::array<char, sizeof(working_buffer_) - sizeof(key)> value;
498 };
Wyatt Heplere541e072020-02-14 09:10:53 -0800499 TempEntry* temp_entry = reinterpret_cast<TempEntry*>(working_buffer_.data());
David Rogersf0a35442020-02-04 12:16:38 -0800500
David Rogersdf025cd2020-02-06 17:05:34 -0800501 DBG("Relocating entry"); // TODO: add entry info to the log statement.
502
Wyatt Heplere541e072020-02-14 09:10:53 -0800503 // Read the entry to be relocated. Store the entry in a local variable and
David Rogersf0a35442020-02-04 12:16:38 -0800504 // store the key and value in the TempEntry stored in the static allocated
505 // working_buffer_.
Wyatt Heplere541e072020-02-14 09:10:53 -0800506 Entry entry;
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800507 TRY(Entry::Read(partition_, key_descriptor.address(), &entry));
Wyatt Heplere541e072020-02-14 09:10:53 -0800508 TRY_ASSIGN(size_t key_length, entry.ReadKey(temp_entry->key));
509 string_view key = string_view(temp_entry->key.data(), key_length);
510 auto result = entry.ReadValue(as_writable_bytes(span(temp_entry->value)));
David Rogersf0a35442020-02-04 12:16:38 -0800511 if (!result.status().ok()) {
512 return Status::INTERNAL;
513 }
514
Wyatt Heplere541e072020-02-14 09:10:53 -0800515 auto value = span(temp_entry->value.data(), result.size());
516 TRY(entry.VerifyChecksum(
David Rogersf0a35442020-02-04 12:16:38 -0800517 entry_header_format_.checksum, key, as_bytes(value)));
518
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800519 SectorDescriptor* old_sector = SectorFromKey(key_descriptor);
David Rogersf0a35442020-02-04 12:16:38 -0800520
521 // Find a new sector for the entry and write it to the new location.
David Rogers8ce55cd2020-02-04 19:41:48 -0800522 SectorDescriptor* new_sector;
Wyatt Heplere541e072020-02-14 09:10:53 -0800523 TRY(FindSectorWithSpace(&new_sector, entry.size(), old_sector, true));
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800524 TRY(AppendEntry(new_sector,
525 &key_descriptor,
526 key,
527 as_bytes(value),
528 key_descriptor.state()));
David Rogersdf025cd2020-02-06 17:05:34 -0800529
Wyatt Heplerd2298282020-02-20 17:12:45 -0800530 // Do the valid bytes accounting for the sector the entry was relocated from.
Wyatt Heplere541e072020-02-14 09:10:53 -0800531 old_sector->RemoveValidBytes(entry.size());
David Rogersdf025cd2020-02-06 17:05:34 -0800532
533 return Status::OK;
David Rogersa12786b2020-01-31 16:02:33 -0800534}
535
David Rogers8db5a722020-02-03 18:28:34 -0800536// Find either an existing sector with enough space that is not the sector to
537// skip, or an empty sector. Maintains the invariant that there is always at
538// least 1 empty sector unless set to bypass the rule.
Wyatt Hepler5a33d8c2020-02-06 09:32:58 -0800539Status KeyValueStore::FindSectorWithSpace(
540 SectorDescriptor** found_sector,
541 size_t size,
542 const SectorDescriptor* sector_to_skip,
543 bool bypass_empty_sector_rule) {
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800544 SectorDescriptor* first_empty_sector = nullptr;
545 bool at_least_two_empty_sectors = bypass_empty_sector_rule;
546
547 DBG("Find sector with %zu bytes available, starting with sector %u",
548 size,
549 SectorIndex(last_new_sector_));
550 if (sector_to_skip != nullptr) {
551 DBG(" Skip sector %u", SectorIndex(sector_to_skip));
552 }
553 if (bypass_empty_sector_rule) {
554 DBG(" Bypassing empty sector rule");
555 }
556
David Rogers8ce55cd2020-02-04 19:41:48 -0800557 // The last_new_sector_ is the sector that was last selected as the "new empty
558 // sector" to write to. This last new sector is used as the starting point for
559 // the next "find a new empty sector to write to" operation. By using the last
560 // new sector as the start point we will cycle which empty sector is selected
561 // next, spreading the wear across all the empty sectors and get a wear
562 // leveling benefit, rather than putting more wear on the lower number
563 // sectors.
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800564 SectorDescriptor* sector = last_new_sector_;
David Rogers67f4b6c2020-02-06 16:17:09 -0800565
David Rogers8ce55cd2020-02-04 19:41:48 -0800566 // Look for a partial sector to use with enough space. Immediately use the
567 // first one of those that is found. While scanning for a partial sector, keep
568 // track of the first empty sector and if a second sector was seen.
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800569 for (size_t j = 0; j < sectors_.size(); j++) {
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800570 sector += 1;
571 if (sector == sectors_.end()) {
572 sector = sectors_.begin();
573 }
Keir Mierle8c352dc2020-02-02 13:58:19 -0800574
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800575 if (sector_to_skip == sector) {
David Rogers8db5a722020-02-03 18:28:34 -0800576 continue;
577 }
578
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800579 const size_t sector_size_bytes = partition_.sector_size_bytes();
580 if (!sector->Empty(sector_size_bytes) && sector->HasSpace(size)) {
581 *found_sector = sector;
David Rogers8ce55cd2020-02-04 19:41:48 -0800582 return Status::OK;
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800583 }
584
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800585 if (sector->Empty(sector_size_bytes)) {
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800586 if (first_empty_sector == nullptr) {
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800587 first_empty_sector = sector;
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800588 } else {
589 at_least_two_empty_sectors = true;
Wyatt Hepler2ad60672020-01-21 08:00:16 -0800590 }
Wyatt Heplerb7609542020-01-24 10:29:54 -0800591 }
592 }
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800593
David Rogers8ce55cd2020-02-04 19:41:48 -0800594 // If the scan for a partial sector does not find a suitable sector, use the
595 // first empty sector that was found. Normally it is required to keep 1 empty
596 // sector after the sector found here, but that rule can be bypassed in
597 // special circumstances (such as during garbage collection).
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800598 if (at_least_two_empty_sectors) {
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800599 DBG(" Found a usable empty sector; returning the first found (%u)",
David Rogers8ce55cd2020-02-04 19:41:48 -0800600 SectorIndex(first_empty_sector));
601 last_new_sector_ = first_empty_sector;
602 *found_sector = first_empty_sector;
603 return Status::OK;
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800604 }
David Rogers8ce55cd2020-02-04 19:41:48 -0800605
606 // No sector was found.
David Rogers67f4b6c2020-02-06 16:17:09 -0800607 DBG(" Unable to find a usable sector");
David Rogers8ce55cd2020-02-04 19:41:48 -0800608 *found_sector = nullptr;
609 return Status::RESOURCE_EXHAUSTED;
Wyatt Heplerb7609542020-01-24 10:29:54 -0800610}
611
David Rogers2761aeb2020-01-31 17:09:00 -0800612Status KeyValueStore::FindOrRecoverSectorWithSpace(SectorDescriptor** sector,
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800613 size_t size) {
David Rogers8ce55cd2020-02-04 19:41:48 -0800614 Status result = FindSectorWithSpace(sector, size);
Wyatt Hepler2d401692020-02-13 16:01:23 -0800615 if (result == Status::RESOURCE_EXHAUSTED && options_.partial_gc_on_write) {
David Rogers1541d612020-02-06 23:47:02 -0800616 // Garbage collect and then try again to find the best sector.
617 TRY(GarbageCollectOneSector());
618 return FindSectorWithSpace(sector, size);
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800619 }
David Rogers8ce55cd2020-02-04 19:41:48 -0800620 return result;
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800621}
622
David Rogers2761aeb2020-01-31 17:09:00 -0800623KeyValueStore::SectorDescriptor* KeyValueStore::FindSectorToGarbageCollect() {
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800624 const size_t sector_size_bytes = partition_.sector_size_bytes();
David Rogers2761aeb2020-01-31 17:09:00 -0800625 SectorDescriptor* sector_candidate = nullptr;
David Rogersa12786b2020-01-31 16:02:33 -0800626 size_t candidate_bytes = 0;
627
628 // Step 1: Try to find a sectors with stale keys and no valid keys (no
629 // relocation needed). If any such sectors are found, use the sector with the
630 // most reclaimable bytes.
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800631 for (auto& sector : sectors_) {
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800632 if ((sector.valid_bytes() == 0) &&
633 (sector.RecoverableBytes(sector_size_bytes) > candidate_bytes)) {
David Rogersa12786b2020-01-31 16:02:33 -0800634 sector_candidate = &sector;
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800635 candidate_bytes = sector.RecoverableBytes(sector_size_bytes);
David Rogersa12786b2020-01-31 16:02:33 -0800636 }
637 }
638
639 // Step 2: If step 1 yields no sectors, just find the sector with the most
640 // reclaimable bytes.
641 if (sector_candidate == nullptr) {
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800642 for (auto& sector : sectors_) {
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800643 if (sector.RecoverableBytes(sector_size_bytes) > candidate_bytes) {
David Rogersa12786b2020-01-31 16:02:33 -0800644 sector_candidate = &sector;
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800645 candidate_bytes = sector.RecoverableBytes(sector_size_bytes);
David Rogersa12786b2020-01-31 16:02:33 -0800646 }
647 }
648 }
649
David Rogers5981f312020-02-13 13:33:56 -0800650 if (sector_candidate != nullptr) {
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800651 DBG("Found sector %u to Garbage Collect, %zu recoverable bytes",
David Rogers5981f312020-02-13 13:33:56 -0800652 SectorIndex(sector_candidate),
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800653 sector_candidate->RecoverableBytes(sector_size_bytes));
David Rogers5981f312020-02-13 13:33:56 -0800654 } else {
655 DBG("Unable to find sector to garbage collect!");
656 }
David Rogersa12786b2020-01-31 16:02:33 -0800657 return sector_candidate;
658}
659
David Rogers1541d612020-02-06 23:47:02 -0800660Status KeyValueStore::GarbageCollectOneSector() {
David Rogers67f4b6c2020-02-06 16:17:09 -0800661 DBG("Garbage Collect a single sector");
662
David Rogersa12786b2020-01-31 16:02:33 -0800663 // Step 1: Find the sector to garbage collect
David Rogers2761aeb2020-01-31 17:09:00 -0800664 SectorDescriptor* sector_to_gc = FindSectorToGarbageCollect();
David Rogers3464d0a2020-02-07 11:45:46 -0800665 LogSectors();
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800666
David Rogersa12786b2020-01-31 16:02:33 -0800667 if (sector_to_gc == nullptr) {
668 return Status::RESOURCE_EXHAUSTED;
669 }
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800670
David Rogersa12786b2020-01-31 16:02:33 -0800671 // Step 2: Move any valid entries in the GC sector to other sectors
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800672 if (sector_to_gc->valid_bytes() != 0) {
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800673 for (auto& descriptor : key_descriptors_) {
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800674 if (AddressInSector(*sector_to_gc, descriptor.address())) {
David Rogers67f4b6c2020-02-06 16:17:09 -0800675 DBG(" Relocate entry");
David Rogers2761aeb2020-01-31 17:09:00 -0800676 TRY(RelocateEntry(descriptor));
David Rogersa12786b2020-01-31 16:02:33 -0800677 }
Wyatt Heplerb7609542020-01-24 10:29:54 -0800678 }
679 }
Wyatt Heplerb7609542020-01-24 10:29:54 -0800680
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800681 if (sector_to_gc->valid_bytes() != 0) {
David Rogers67f4b6c2020-02-06 16:17:09 -0800682 ERR(" Failed to relocate valid entries from sector being garbage "
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800683 "collected, %zu valid bytes remain",
684 sector_to_gc->valid_bytes());
Wyatt Heplerb7609542020-01-24 10:29:54 -0800685 return Status::INTERNAL;
686 }
687
David Rogersa12786b2020-01-31 16:02:33 -0800688 // Step 3: Reinitialize the sector
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800689 sector_to_gc->set_writable_bytes(0);
David Rogersa12786b2020-01-31 16:02:33 -0800690 TRY(partition_.Erase(SectorBaseAddress(sector_to_gc), 1));
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800691 sector_to_gc->set_writable_bytes(partition_.sector_size_bytes());
Wyatt Heplerb7609542020-01-24 10:29:54 -0800692
David Rogers67f4b6c2020-02-06 16:17:09 -0800693 DBG(" Garbage Collect complete");
David Rogers50185ad2020-02-07 00:02:46 -0800694 LogSectors();
David Rogersa12786b2020-01-31 16:02:33 -0800695 return Status::OK;
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800696}
697
David Rogers2761aeb2020-01-31 17:09:00 -0800698Status KeyValueStore::AppendEntry(SectorDescriptor* sector,
699 KeyDescriptor* key_descriptor,
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800700 string_view key,
Wyatt Hepler5a33d8c2020-02-06 09:32:58 -0800701 span<const byte> value,
702 KeyDescriptor::State new_state) {
Wyatt Heplere541e072020-02-14 09:10:53 -0800703 const Address address = NextWritableAddress(sector);
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800704 Entry entry = CreateEntry(address, key, value, new_state);
Wyatt Heplere541e072020-02-14 09:10:53 -0800705
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800706 DBG("Appending %zu B entry with transaction ID %" PRIu32 " to address %#zx",
Wyatt Heplere541e072020-02-14 09:10:53 -0800707 entry.size(),
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800708 entry.transaction_id(),
709 size_t(address));
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800710
David Rogers6592d292020-02-14 14:19:26 -0800711 StatusWithSize result = entry.Write(key, value);
712 // Remove any bytes that were written, even if the write was not successful.
713 sector->RemoveWritableBytes(result.size());
714
715 if (!result.ok()) {
716 // TODO: add testing coverage for this once flash errors are supported in
717 // tests.
718 ERR("Failed to write %zu bytes. %zu actually written",
719 entry.size(),
720 result.size());
721 return result.status();
722 }
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800723
724 if (options_.verify_on_write) {
Wyatt Heplere541e072020-02-14 09:10:53 -0800725 TRY(entry.VerifyChecksumInFlash(entry_header_format_.checksum));
Wyatt Heplerb7609542020-01-24 10:29:54 -0800726 }
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800727
David Rogers6592d292020-02-14 14:19:26 -0800728 // Entry was written successfully, update the key descriptor and the sector
729 // descriptor to reflect the new entry.
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800730 entry.UpdateDescriptor(key_descriptor);
David Rogers6592d292020-02-14 14:19:26 -0800731 sector->AddValidBytes(result.size());
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800732 return Status::OK;
Wyatt Heplerb7609542020-01-24 10:29:54 -0800733}
734
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800735Entry KeyValueStore::CreateEntry(Address address,
736 std::string_view key,
737 span<const byte> value,
738 KeyDescriptor::State state) {
Wyatt Heplerd2298282020-02-20 17:12:45 -0800739 last_transaction_id_ += 1;
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800740
741 if (state == KeyDescriptor::kDeleted) {
742 return Entry::Tombstone(partition_,
743 address,
744 entry_header_format_.magic,
745 entry_header_format_.checksum,
746 key,
747 partition_.alignment_bytes(),
Wyatt Heplerd2298282020-02-20 17:12:45 -0800748 last_transaction_id_);
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800749 }
750 return Entry::Valid(partition_,
751 address,
752 entry_header_format_.magic,
753 entry_header_format_.checksum,
754 key,
755 value,
756 partition_.alignment_bytes(),
Wyatt Heplerd2298282020-02-20 17:12:45 -0800757 last_transaction_id_);
758}
759
760void KeyValueStore::Reset() {
761 initialized_ = false;
762 key_descriptors_.clear();
763 last_new_sector_ = nullptr;
764 last_transaction_id_ = 0;
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800765}
766
Keir Mierle8c352dc2020-02-02 13:58:19 -0800767void KeyValueStore::LogDebugInfo() {
Keir Mierle8c352dc2020-02-02 13:58:19 -0800768 const size_t sector_size_bytes = partition_.sector_size_bytes();
769 DBG("====================== KEY VALUE STORE DUMP =========================");
770 DBG(" ");
771 DBG("Flash partition:");
Wyatt Heplerad0a7932020-02-06 08:20:38 -0800772 DBG(" Sector count = %zu", partition_.sector_count());
Wyatt Hepler38ce30f2020-02-19 11:48:31 -0800773 DBG(" Sector max count = %zu", sectors_.max_size());
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800774 DBG(" Sectors in use = %zu", sectors_.size());
Keir Mierle8c352dc2020-02-02 13:58:19 -0800775 DBG(" Sector size = %zu", sector_size_bytes);
776 DBG(" Total size = %zu", partition_.size_bytes());
777 DBG(" Alignment = %zu", partition_.alignment_bytes());
778 DBG(" ");
779 DBG("Key descriptors:");
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800780 DBG(" Entry count = %zu", key_descriptors_.size());
Wyatt Hepler38ce30f2020-02-19 11:48:31 -0800781 DBG(" Max entry count = %zu", key_descriptors_.max_size());
Keir Mierle8c352dc2020-02-02 13:58:19 -0800782 DBG(" ");
783 DBG(" # hash version address address (hex)");
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800784 for (size_t i = 0; i < key_descriptors_.size(); ++i) {
785 const KeyDescriptor& kd = key_descriptors_[i];
Keir Mierle8c352dc2020-02-02 13:58:19 -0800786 DBG(" |%3zu: | %8zx |%8zu | %8zu | %8zx",
787 i,
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800788 size_t(kd.hash()),
789 size_t(kd.transaction_id()),
790 size_t(kd.address()),
791 size_t(kd.address()));
Keir Mierle8c352dc2020-02-02 13:58:19 -0800792 }
793 DBG(" ");
794
795 DBG("Sector descriptors:");
796 DBG(" # tail free valid has_space");
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800797 for (size_t sector_id = 0; sector_id < sectors_.size(); ++sector_id) {
798 const SectorDescriptor& sd = sectors_[sector_id];
Keir Mierle8c352dc2020-02-02 13:58:19 -0800799 DBG(" |%3zu: | %8zu |%8zu | %s",
800 sector_id,
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800801 size_t(sd.writable_bytes()),
802 sd.valid_bytes(),
803 sd.writable_bytes() ? "YES" : "");
Keir Mierle8c352dc2020-02-02 13:58:19 -0800804 }
805 DBG(" ");
806
807 // TODO: This should stop logging after some threshold.
808 // size_t dumped_bytes = 0;
809 DBG("Sector raw data:");
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800810 for (size_t sector_id = 0; sector_id < sectors_.size(); ++sector_id) {
Keir Mierle8c352dc2020-02-02 13:58:19 -0800811 // Read sector data. Yes, this will blow the stack on embedded.
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800812 std::array<byte, 500> raw_sector_data; // TODO!!!
Keir Mierle8c352dc2020-02-02 13:58:19 -0800813 StatusWithSize sws =
814 partition_.Read(sector_id * sector_size_bytes, raw_sector_data);
815 DBG("Read: %zu bytes", sws.size());
816
817 DBG(" base addr offs 0 1 2 3 4 5 6 7");
818 for (size_t i = 0; i < sector_size_bytes; i += 8) {
819 DBG(" %3zu %8zx %5zu | %02x %02x %02x %02x %02x %02x %02x %02x",
820 sector_id,
821 (sector_id * sector_size_bytes) + i,
822 i,
823 static_cast<unsigned int>(raw_sector_data[i + 0]),
824 static_cast<unsigned int>(raw_sector_data[i + 1]),
825 static_cast<unsigned int>(raw_sector_data[i + 2]),
826 static_cast<unsigned int>(raw_sector_data[i + 3]),
827 static_cast<unsigned int>(raw_sector_data[i + 4]),
828 static_cast<unsigned int>(raw_sector_data[i + 5]),
829 static_cast<unsigned int>(raw_sector_data[i + 6]),
830 static_cast<unsigned int>(raw_sector_data[i + 7]));
831
832 // TODO: Fix exit condition.
833 if (i > 128) {
834 break;
835 }
836 }
837 DBG(" ");
838 }
839
840 DBG("////////////////////// KEY VALUE STORE DUMP END /////////////////////");
841}
842
David Rogerscf680ab2020-02-12 23:28:32 -0800843void KeyValueStore::LogSectors() const {
844 DBG("Sector descriptors: count %zu", sectors_.size());
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800845 for (auto& sector : sectors_) {
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800846 DBG(" - Sector %u: valid %zu, recoverable %zu, free %zu",
David Rogers50185ad2020-02-07 00:02:46 -0800847 SectorIndex(&sector),
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800848 sector.valid_bytes(),
849 sector.RecoverableBytes(partition_.sector_size_bytes()),
850 sector.writable_bytes());
David Rogers50185ad2020-02-07 00:02:46 -0800851 }
852}
853
David Rogerscf680ab2020-02-12 23:28:32 -0800854void KeyValueStore::LogKeyDescriptor() const {
855 DBG("Key descriptors: count %zu", key_descriptors_.size());
856 for (auto& key : key_descriptors_) {
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800857 DBG(" - Key: %s, hash %#zx, transaction ID %zu, address %#zx",
David Rogerscf680ab2020-02-12 23:28:32 -0800858 key.deleted() ? "Deleted" : "Valid",
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800859 static_cast<size_t>(key.hash()),
860 static_cast<size_t>(key.transaction_id()),
861 static_cast<size_t>(key.address()));
David Rogerscf680ab2020-02-12 23:28:32 -0800862 }
863}
864
Wyatt Hepler2ad60672020-01-21 08:00:16 -0800865} // namespace pw::kvs