blob: 934b2964c16fd78133498cf519dfa2041e4e2468 [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),
47 options_(options),
Wyatt Hepler38ce30f2020-02-19 11:48:31 -080048 key_descriptors_(key_descriptor_list),
Wyatt Hepler1fc11042020-02-19 17:17:51 -080049 sectors_(sector_descriptor_list) {}
Wyatt Heplerad0a7932020-02-06 08:20:38 -080050
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -080051Status KeyValueStore::Init() {
David Rogers2e9e0c82020-02-13 15:06:06 -080052 INF("Initializing key value store");
Wyatt Hepler38ce30f2020-02-19 11:48:31 -080053 if (partition_.sector_count() > sectors_.max_size()) {
David Rogers2e9e0c82020-02-13 15:06:06 -080054 ERR("KVS init failed: kMaxUsableSectors (=%zu) must be at least as "
55 "large as the number of sectors in the flash partition (=%zu)",
Wyatt Hepler38ce30f2020-02-19 11:48:31 -080056 sectors_.max_size(),
David Rogers2e9e0c82020-02-13 15:06:06 -080057 partition_.sector_count());
Wyatt Heplerad0a7932020-02-06 08:20:38 -080058 return Status::FAILED_PRECONDITION;
59 }
60
Wyatt Hepler38ce30f2020-02-19 11:48:31 -080061 // Reset descriptor lists. Key descriptors will be filled later.
62 sectors_.resize(partition_.sector_count());
Wyatt Hepler1c329ca2020-02-07 18:07:23 -080063 key_descriptors_.clear();
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -080064
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 Hepler2c7eca02020-02-18 16:01:42 -080078 for (SectorDescriptor& sector : sectors_) {
79 // Reset the sector's valid and writable byte counts. These will be updated
80 // after reading each entry.
81 sector.Reset(sector_size_bytes);
Keir Mierle8c352dc2020-02-02 13:58:19 -080082 Address entry_address = sector_address;
83
Wyatt Hepler2c7eca02020-02-18 16:01:42 -080084 for (int num_entries_in_sector = 0; true; num_entries_in_sector++) {
85 DBG("Load entry: sector=%" PRIx32 ", entry#=%d, address=%" PRIx32,
86 sector_address,
Keir Mierle8c352dc2020-02-02 13:58:19 -080087 num_entries_in_sector,
Wyatt Hepler2c7eca02020-02-18 16:01:42 -080088 entry_address);
Keir Mierle8c352dc2020-02-02 13:58:19 -080089
Wyatt Hepler2c7eca02020-02-18 16:01:42 -080090 if (!AddressInSector(sector, entry_address)) {
Keir Mierle8c352dc2020-02-02 13:58:19 -080091 DBG("Fell off end of sector; moving to the next sector");
92 break;
93 }
94
95 Address next_entry_address;
96 Status status = LoadEntry(entry_address, &next_entry_address);
97 if (status == Status::NOT_FOUND) {
98 DBG("Hit un-written data in sector; moving to the next sector");
99 break;
100 }
101 if (status == Status::DATA_LOSS) {
102 // It's not clear KVS can make a unilateral decision about what to do
103 // in corruption cases. It's an application decision, for which we
104 // should offer some configurability. For now, entirely bail out of
105 // loading and give up.
106 //
107 // Later, scan for remaining valid keys; since it's entirely possible
108 // that there is a duplicate of the key elsewhere and everything is
109 // fine. Later, we can wipe and maybe recover the sector.
110 //
111 // TODO: Implement rest-of-sector scanning for valid entries.
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800112 ERR("KVS init failed: data loss detected in sector %u at address %zu",
113 SectorIndex(&sector),
114 size_t(entry_address));
Keir Mierle8c352dc2020-02-02 13:58:19 -0800115 return Status::DATA_LOSS;
116 }
117 TRY(status);
118
119 // Entry loaded successfully; so get ready to load the next one.
120 entry_address = next_entry_address;
121
122 // Update of the number of writable bytes in this sector.
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800123 sector.set_writable_bytes(sector_size_bytes -
124 (entry_address - sector_address));
Keir Mierle8c352dc2020-02-02 13:58:19 -0800125 }
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800126
127 sector_address += sector_size_bytes;
Keir Mierle8c352dc2020-02-02 13:58:19 -0800128 }
129
130 DBG("Second pass: Count valid bytes in each sector");
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800131 const KeyDescriptor* newest_key = nullptr;
132 last_transaction_id_ = 0;
133
Keir Mierle8c352dc2020-02-02 13:58:19 -0800134 // For every valid key, increment the valid bytes for that sector.
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800135 for (KeyDescriptor& key_descriptor : key_descriptors_) {
Wyatt Heplere541e072020-02-14 09:10:53 -0800136 Entry entry;
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800137 TRY(Entry::Read(partition_, key_descriptor.address(), &entry));
138 SectorFromKey(key_descriptor)->AddValidBytes(entry.size());
139
140 if (key_descriptor.IsNewerThan(last_transaction_id_)) {
141 last_transaction_id_ = key_descriptor.transaction_id();
142 newest_key = &key_descriptor;
143 }
Keir Mierle8c352dc2020-02-02 13:58:19 -0800144 }
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800145
146 if (newest_key == nullptr) {
147 last_new_sector_ = sectors_.begin();
148 } else {
149 last_new_sector_ = SectorFromKey(newest_key);
150 }
151
Wyatt Hepler729f28c2020-02-05 09:46:00 -0800152 initialized_ = true;
David Rogers2e9e0c82020-02-13 15:06:06 -0800153
Armando Montanez5464d5f2020-02-20 10:12:20 -0800154 INF("KeyValueStore init complete: active keys %zu, deleted keys %zu, sectors "
David Rogers2e9e0c82020-02-13 15:06:06 -0800155 "%zu, logical sector size %zu bytes",
156 size(),
157 (key_descriptors_.size() - size()),
158 sectors_.size(),
159 partition_.sector_size_bytes());
160
Keir Mierle8c352dc2020-02-02 13:58:19 -0800161 return Status::OK;
162}
163
164Status KeyValueStore::LoadEntry(Address entry_address,
165 Address* next_entry_address) {
Wyatt Heplere541e072020-02-14 09:10:53 -0800166 Entry entry;
167 TRY(Entry::Read(partition_, entry_address, &entry));
Keir Mierle8c352dc2020-02-02 13:58:19 -0800168
169 // TODO: Handle multiple magics for formats that have changed.
Wyatt Heplere541e072020-02-14 09:10:53 -0800170 if (entry.magic() != entry_header_format_.magic) {
Keir Mierle8c352dc2020-02-02 13:58:19 -0800171 // TODO: It may be cleaner to have some logging helpers for these cases.
Wyatt Heplere541e072020-02-14 09:10:53 -0800172 ERR("Found corrupt magic: %zx; expecting %zx; at address %zx",
173 size_t(entry.magic()),
Keir Mierle8c352dc2020-02-02 13:58:19 -0800174 size_t(entry_header_format_.magic),
175 size_t(entry_address));
176 return Status::DATA_LOSS;
177 }
178
179 // Read the key from flash & validate the entry (which reads the value).
Wyatt Heplera00d1ef2020-02-14 14:31:26 -0800180 Entry::KeyBuffer key_buffer;
Wyatt Heplere541e072020-02-14 09:10:53 -0800181 TRY_ASSIGN(size_t key_length, entry.ReadKey(key_buffer));
182 const string_view key(key_buffer.data(), key_length);
Wyatt Heplerbab0e202020-02-04 07:40:08 -0800183
Wyatt Heplere541e072020-02-14 09:10:53 -0800184 TRY(entry.VerifyChecksumInFlash(entry_header_format_.checksum));
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800185 TRY(AppendNewOrOverwriteStaleExistingDescriptor(entry.descriptor(key)));
Keir Mierle8c352dc2020-02-02 13:58:19 -0800186
Wyatt Heplere541e072020-02-14 09:10:53 -0800187 *next_entry_address = entry.next_address();
Keir Mierle8c352dc2020-02-02 13:58:19 -0800188 return Status::OK;
189}
190
191// TODO: This method is the trigger of the O(valid_entries * all_entries) time
192// complexity for reading. At some cost to memory, this could be optimized by
193// using a hash table instead of scanning, but in practice this should be fine
194// for a small number of keys
195Status KeyValueStore::AppendNewOrOverwriteStaleExistingDescriptor(
196 const KeyDescriptor& key_descriptor) {
197 // With the new key descriptor, either add it to the descriptor table or
198 // overwrite an existing entry with an older version of the key.
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800199 KeyDescriptor* existing_descriptor = FindDescriptor(key_descriptor.hash());
Keir Mierle8c352dc2020-02-02 13:58:19 -0800200
Wyatt Hepler5406a672020-02-18 15:42:38 -0800201 // Write a new entry.
202 if (existing_descriptor == nullptr) {
203 if (key_descriptors_.full()) {
204 return Status::RESOURCE_EXHAUSTED;
205 }
206 key_descriptors_.push_back(key_descriptor);
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800207 } else if (key_descriptor.IsNewerThan(
208 existing_descriptor->transaction_id())) {
Wyatt Hepler5406a672020-02-18 15:42:38 -0800209 // Existing entry is old; replace the existing entry with the new one.
210 *existing_descriptor = key_descriptor;
211 } else {
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800212 // Otherwise, check if the entries have a duplicate transaction ID, which is
213 // not valid.
214 if (existing_descriptor->transaction_id() ==
215 key_descriptor.transaction_id()) {
216 ERR("Data loss: Duplicated old(=%zu) and new(=%zu) transaction ID",
217 size_t(existing_descriptor->transaction_id()),
218 size_t(key_descriptor.transaction_id()));
Wyatt Hepler5406a672020-02-18 15:42:38 -0800219 return Status::DATA_LOSS;
220 }
221 DBG("Found stale entry when appending; ignoring");
Keir Mierle8c352dc2020-02-02 13:58:19 -0800222 }
Keir Mierle8c352dc2020-02-02 13:58:19 -0800223 return Status::OK;
224}
225
Keir Mierle8c352dc2020-02-02 13:58:19 -0800226KeyValueStore::KeyDescriptor* KeyValueStore::FindDescriptor(uint32_t hash) {
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800227 for (KeyDescriptor& key_descriptor : key_descriptors_) {
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800228 if (key_descriptor.hash() == hash) {
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800229 return &key_descriptor;
Keir Mierle8c352dc2020-02-02 13:58:19 -0800230 }
231 }
232 return nullptr;
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800233}
234
235StatusWithSize KeyValueStore::Get(string_view key,
Wyatt Hepler5f6efc02020-02-18 16:54:31 -0800236 span<byte> value_buffer,
237 size_t offset_bytes) const {
Wyatt Hepler50f70772020-02-13 11:25:10 -0800238 TRY_WITH_SIZE(CheckOperation(key));
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800239
David Rogers2761aeb2020-01-31 17:09:00 -0800240 const KeyDescriptor* key_descriptor;
Wyatt Hepler2d401692020-02-13 16:01:23 -0800241 TRY_WITH_SIZE(FindExistingKeyDescriptor(key, &key_descriptor));
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800242
Wyatt Heplere541e072020-02-14 09:10:53 -0800243 Entry entry;
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800244 TRY_WITH_SIZE(Entry::Read(partition_, key_descriptor->address(), &entry));
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800245
Wyatt Hepler5f6efc02020-02-18 16:54:31 -0800246 StatusWithSize result = entry.ReadValue(value_buffer, offset_bytes);
247 if (result.ok() && options_.verify_on_read && offset_bytes == 0u) {
David Rogerscf680ab2020-02-12 23:28:32 -0800248 Status verify_result =
Wyatt Heplere541e072020-02-14 09:10:53 -0800249 entry.VerifyChecksum(entry_header_format_.checksum,
250 key,
251 value_buffer.subspan(0, result.size()));
David Rogerscf680ab2020-02-12 23:28:32 -0800252 if (!verify_result.ok()) {
Wyatt Hepler50f70772020-02-13 11:25:10 -0800253 std::memset(
254 value_buffer.subspan(0, result.size()).data(), 0, result.size());
255 return StatusWithSize(verify_result);
David Rogerscf680ab2020-02-12 23:28:32 -0800256 }
257
258 return StatusWithSize(verify_result, result.size());
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800259 }
260 return result;
261}
262
263Status KeyValueStore::Put(string_view key, span<const byte> value) {
Keir Mierle8c352dc2020-02-02 13:58:19 -0800264 DBG("Writing key/value; key length=%zu, value length=%zu",
265 key.size(),
266 value.size());
Wyatt Hepler729f28c2020-02-05 09:46:00 -0800267
268 TRY(CheckOperation(key));
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800269
Wyatt Hepler5406a672020-02-18 15:42:38 -0800270 if (Entry::size(partition_, key, value) > partition_.sector_size_bytes()) {
271 DBG("%zu B value with %zu B key cannot fit in one sector",
272 value.size(),
273 key.size());
274 return Status::INVALID_ARGUMENT;
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800275 }
276
David Rogers2761aeb2020-01-31 17:09:00 -0800277 KeyDescriptor* key_descriptor;
Wyatt Hepler2d401692020-02-13 16:01:23 -0800278 Status status = FindKeyDescriptor(key, &key_descriptor);
279
280 if (status.ok()) {
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800281 DBG("Overwriting entry for key %#08" PRIx32 " in sector %u",
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800282 key_descriptor->hash(),
283 SectorIndex(SectorFromKey(key_descriptor)));
Wyatt Hepler5a33d8c2020-02-06 09:32:58 -0800284 return WriteEntryForExistingKey(
285 key_descriptor, KeyDescriptor::kValid, key, value);
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800286 }
David Rogers2761aeb2020-01-31 17:09:00 -0800287
Wyatt Hepler2d401692020-02-13 16:01:23 -0800288 if (status == Status::NOT_FOUND) {
289 return WriteEntryForNewKey(key, value);
290 }
291
292 return status;
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800293}
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;
Wyatt Hepler2d401692020-02-13 16:01:23 -0800299 TRY(FindExistingKeyDescriptor(key, &key_descriptor));
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800300
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800301 DBG("Writing tombstone for key %#08" PRIx32 " in sector %u",
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800302 key_descriptor->hash(),
303 SectorIndex(SectorFromKey(key_descriptor)));
Wyatt Hepler5a33d8c2020-02-06 09:32:58 -0800304 return WriteEntryForExistingKey(
305 key_descriptor, KeyDescriptor::kDeleted, key, {});
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800306}
307
308KeyValueStore::iterator& KeyValueStore::iterator::operator++() {
309 // Skip to the next entry that is valid (not deleted).
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800310 while (++index_ < item_.kvs_.key_descriptors_.size() &&
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800311 descriptor().deleted()) {
312 }
313 return *this;
314}
315
316const KeyValueStore::Item& KeyValueStore::iterator::operator*() {
317 std::memset(item_.key_buffer_.data(), 0, item_.key_buffer_.size());
318
Wyatt Heplere541e072020-02-14 09:10:53 -0800319 Entry entry;
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800320 if (Entry::Read(item_.kvs_.partition_, descriptor().address(), &entry).ok()) {
Wyatt Heplere541e072020-02-14 09:10:53 -0800321 entry.ReadKey(item_.key_buffer_);
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800322 }
323
324 return item_;
325}
326
327KeyValueStore::iterator KeyValueStore::begin() const {
328 size_t i = 0;
329 // Skip over any deleted entries at the start of the descriptor list.
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800330 while (i < key_descriptors_.size() && key_descriptors_[i].deleted()) {
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800331 i += 1;
332 }
333 return iterator(*this, i);
334}
335
336// TODO(hepler): The valid entry count could be tracked in the KVS to avoid the
337// need for this for-loop.
338size_t KeyValueStore::size() const {
339 size_t valid_entries = 0;
340
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800341 for (const KeyDescriptor& key_descriptor : key_descriptors_) {
342 if (!key_descriptor.deleted()) {
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800343 valid_entries += 1;
344 }
345 }
346
347 return valid_entries;
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800348}
349
Wyatt Heplered163b02020-02-03 17:49:32 -0800350StatusWithSize KeyValueStore::ValueSize(std::string_view key) const {
Wyatt Hepler50f70772020-02-13 11:25:10 -0800351 TRY_WITH_SIZE(CheckOperation(key));
Wyatt Heplered163b02020-02-03 17:49:32 -0800352
353 const KeyDescriptor* key_descriptor;
Wyatt Hepler2d401692020-02-13 16:01:23 -0800354 TRY_WITH_SIZE(FindExistingKeyDescriptor(key, &key_descriptor));
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800355
Wyatt Heplere541e072020-02-14 09:10:53 -0800356 Entry entry;
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800357 TRY_WITH_SIZE(Entry::Read(partition_, key_descriptor->address(), &entry));
Wyatt Heplered163b02020-02-03 17:49:32 -0800358
Wyatt Heplere541e072020-02-14 09:10:53 -0800359 return StatusWithSize(entry.value_size());
Wyatt Heplered163b02020-02-03 17:49:32 -0800360}
361
Wyatt Hepler6e3a83b2020-02-04 07:36:45 -0800362Status KeyValueStore::FixedSizeGet(std::string_view key,
363 byte* value,
364 size_t size_bytes) const {
365 // Ensure that the size of the stored value matches the size of the type.
366 // Otherwise, report error. This check avoids potential memory corruption.
367 StatusWithSize result = ValueSize(key);
368 if (!result.ok()) {
369 return result.status();
Keir Mierle8c352dc2020-02-02 13:58:19 -0800370 }
Wyatt Hepler6e3a83b2020-02-04 07:36:45 -0800371 if (result.size() != size_bytes) {
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800372 DBG("Requested %zu B read, but value is %zu B", size_bytes, result.size());
Wyatt Hepler6e3a83b2020-02-04 07:36:45 -0800373 return Status::INVALID_ARGUMENT;
Wyatt Heplerbab0e202020-02-04 07:40:08 -0800374 }
Wyatt Hepler6e3a83b2020-02-04 07:36:45 -0800375 return Get(key, span(value, size_bytes)).status();
Keir Mierle8c352dc2020-02-02 13:58:19 -0800376}
377
Wyatt Hepler729f28c2020-02-05 09:46:00 -0800378Status KeyValueStore::CheckOperation(string_view key) const {
Wyatt Hepleracaacf92020-01-24 10:58:30 -0800379 if (InvalidKey(key)) {
Wyatt Heplerb7609542020-01-24 10:29:54 -0800380 return Status::INVALID_ARGUMENT;
381 }
Wyatt Hepler729f28c2020-02-05 09:46:00 -0800382 if (!initialized_) {
Wyatt Heplerb7609542020-01-24 10:29:54 -0800383 return Status::FAILED_PRECONDITION;
384 }
Wyatt Heplerb7609542020-01-24 10:29:54 -0800385 return Status::OK;
386}
387
Wyatt Hepler2d401692020-02-13 16:01:23 -0800388// Searches for a KeyDescriptor that matches this key and sets *result to point
389// to it if one is found.
390//
391// OK: there is a matching descriptor and *result is set
392// NOT_FOUND: there is no descriptor that matches this key, but this key
393// has a unique hash (and could potentially be added to the KVS)
394// ALREADY_EXISTS: there is no descriptor that matches this key, but the
395// key's hash collides with the hash for an existing descriptor
396//
David Rogers2761aeb2020-01-31 17:09:00 -0800397Status KeyValueStore::FindKeyDescriptor(string_view key,
398 const KeyDescriptor** result) const {
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800399 const uint32_t hash = internal::Hash(key);
Wyatt Heplera00d1ef2020-02-14 14:31:26 -0800400 Entry::KeyBuffer key_buffer;
Wyatt Heplerb7609542020-01-24 10:29:54 -0800401
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800402 for (auto& descriptor : key_descriptors_) {
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800403 if (descriptor.hash() == hash) {
Wyatt Heplere541e072020-02-14 09:10:53 -0800404 TRY(Entry::ReadKey(
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800405 partition_, descriptor.address(), key.size(), key_buffer.data()));
Wyatt Heplerb7609542020-01-24 10:29:54 -0800406
Wyatt Heplere541e072020-02-14 09:10:53 -0800407 if (key == string_view(key_buffer.data(), key.size())) {
Wyatt Hepler5a33d8c2020-02-06 09:32:58 -0800408 DBG("Found match for key hash 0x%08" PRIx32, hash);
David Rogers2761aeb2020-01-31 17:09:00 -0800409 *result = &descriptor;
Wyatt Heplerb7609542020-01-24 10:29:54 -0800410 return Status::OK;
Wyatt Hepler2d401692020-02-13 16:01:23 -0800411 } else {
412 WRN("Found key hash collision for 0x%08" PRIx32, hash);
413 return Status::ALREADY_EXISTS;
Wyatt Heplerb7609542020-01-24 10:29:54 -0800414 }
Wyatt Heplerb7609542020-01-24 10:29:54 -0800415 }
416 }
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800417 return Status::NOT_FOUND;
418}
419
Wyatt Hepler2d401692020-02-13 16:01:23 -0800420// Searches for a KeyDescriptor that matches this key and sets *result to point
421// to it if one is found.
422//
423// OK: there is a matching descriptor and *result is set
424// NOT_FOUND: there is no descriptor that matches this key
425//
426Status KeyValueStore::FindExistingKeyDescriptor(
427 string_view key, const KeyDescriptor** result) const {
428 Status status = FindKeyDescriptor(key, result);
429
430 // If the key's hash collides with an existing key or if the key is deleted,
431 // treat it as if it is not in the KVS.
432 if (status == Status::ALREADY_EXISTS ||
433 (status.ok() && (*result)->deleted())) {
434 return Status::NOT_FOUND;
435 }
436 return status;
437}
438
David Rogers2761aeb2020-01-31 17:09:00 -0800439Status KeyValueStore::WriteEntryForExistingKey(KeyDescriptor* key_descriptor,
Wyatt Hepler5a33d8c2020-02-06 09:32:58 -0800440 KeyDescriptor::State new_state,
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800441 string_view key,
442 span<const byte> value) {
Wyatt Hepler5a33d8c2020-02-06 09:32:58 -0800443 // Find the original entry and sector to update the sector's valid_bytes.
Wyatt Hepler30a52152020-02-12 11:26:05 -0800444 Entry original_entry;
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800445 TRY(Entry::Read(partition_, key_descriptor->address(), &original_entry));
446 SectorDescriptor* old_sector = SectorFromKey(key_descriptor);
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800447
David Rogers2761aeb2020-01-31 17:09:00 -0800448 SectorDescriptor* sector;
Wyatt Hepler5406a672020-02-18 15:42:38 -0800449 TRY(FindOrRecoverSectorWithSpace(&sector,
450 Entry::size(partition_, key, value)));
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800451 DBG("Writing existing entry; found sector %u (%#" PRIx32 ")",
452 SectorIndex(sector),
453 SectorBaseAddress(sector));
David Rogers3464d0a2020-02-07 11:45:46 -0800454
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800455 if (old_sector != SectorFromKey(key_descriptor)) {
David Rogers3464d0a2020-02-07 11:45:46 -0800456 DBG("Sector for old entry (size %zu) was garbage collected. Old entry "
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800457 "relocated to sector %u",
David Rogers3464d0a2020-02-07 11:45:46 -0800458 original_entry.size(),
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800459 SectorIndex(SectorFromKey(key_descriptor)));
David Rogers3464d0a2020-02-07 11:45:46 -0800460
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800461 old_sector = SectorFromKey(key_descriptor);
David Rogers3464d0a2020-02-07 11:45:46 -0800462 }
463
Wyatt Hepler5a33d8c2020-02-06 09:32:58 -0800464 TRY(AppendEntry(sector, key_descriptor, key, value, new_state));
465
David Rogers3464d0a2020-02-07 11:45:46 -0800466 old_sector->RemoveValidBytes(original_entry.size());
Wyatt Hepler5a33d8c2020-02-06 09:32:58 -0800467 return Status::OK;
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800468}
469
470Status KeyValueStore::WriteEntryForNewKey(string_view key,
471 span<const byte> value) {
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800472 if (key_descriptors_.full()) {
Keir Mierle8c352dc2020-02-02 13:58:19 -0800473 WRN("KVS full: trying to store a new entry, but can't. Have %zu entries",
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800474 key_descriptors_.size());
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800475 return Status::RESOURCE_EXHAUSTED;
476 }
477
David Rogers2761aeb2020-01-31 17:09:00 -0800478 SectorDescriptor* sector;
Wyatt Hepler5406a672020-02-18 15:42:38 -0800479 TRY(FindOrRecoverSectorWithSpace(&sector,
480 Entry::size(partition_, key, value)));
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800481 DBG("Writing new entry; found sector: %u", SectorIndex(sector));
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800482
483 // Create the KeyDescriptor that will be added to the list. The transaction ID
484 // and address will be set by AppendEntry.
485 KeyDescriptor key_descriptor(key);
Wyatt Hepler0af6ad92020-02-13 15:54:46 -0800486 TRY(AppendEntry(sector, &key_descriptor, key, value, KeyDescriptor::kValid));
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800487
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800488 // Only add the entry when we are certain the write succeeded.
489 key_descriptors_.push_back(key_descriptor);
Wyatt Heplerb7609542020-01-24 10:29:54 -0800490 return Status::OK;
491}
492
David Rogers2761aeb2020-01-31 17:09:00 -0800493Status KeyValueStore::RelocateEntry(KeyDescriptor& key_descriptor) {
David Rogersf0a35442020-02-04 12:16:38 -0800494 struct TempEntry {
Wyatt Heplere541e072020-02-14 09:10:53 -0800495 Entry::KeyBuffer key;
David Rogersf0a35442020-02-04 12:16:38 -0800496 std::array<char, sizeof(working_buffer_) - sizeof(key)> value;
497 };
Wyatt Heplere541e072020-02-14 09:10:53 -0800498 TempEntry* temp_entry = reinterpret_cast<TempEntry*>(working_buffer_.data());
David Rogersf0a35442020-02-04 12:16:38 -0800499
David Rogersdf025cd2020-02-06 17:05:34 -0800500 DBG("Relocating entry"); // TODO: add entry info to the log statement.
501
Wyatt Heplere541e072020-02-14 09:10:53 -0800502 // Read the entry to be relocated. Store the entry in a local variable and
David Rogersf0a35442020-02-04 12:16:38 -0800503 // store the key and value in the TempEntry stored in the static allocated
504 // working_buffer_.
Wyatt Heplere541e072020-02-14 09:10:53 -0800505 Entry entry;
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800506 TRY(Entry::Read(partition_, key_descriptor.address(), &entry));
Wyatt Heplere541e072020-02-14 09:10:53 -0800507 TRY_ASSIGN(size_t key_length, entry.ReadKey(temp_entry->key));
508 string_view key = string_view(temp_entry->key.data(), key_length);
509 auto result = entry.ReadValue(as_writable_bytes(span(temp_entry->value)));
David Rogersf0a35442020-02-04 12:16:38 -0800510 if (!result.status().ok()) {
511 return Status::INTERNAL;
512 }
513
Wyatt Heplere541e072020-02-14 09:10:53 -0800514 auto value = span(temp_entry->value.data(), result.size());
515 TRY(entry.VerifyChecksum(
David Rogersf0a35442020-02-04 12:16:38 -0800516 entry_header_format_.checksum, key, as_bytes(value)));
517
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800518 SectorDescriptor* old_sector = SectorFromKey(key_descriptor);
David Rogersf0a35442020-02-04 12:16:38 -0800519
520 // Find a new sector for the entry and write it to the new location.
David Rogers8ce55cd2020-02-04 19:41:48 -0800521 SectorDescriptor* new_sector;
Wyatt Heplere541e072020-02-14 09:10:53 -0800522 TRY(FindSectorWithSpace(&new_sector, entry.size(), old_sector, true));
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800523 TRY(AppendEntry(new_sector,
524 &key_descriptor,
525 key,
526 as_bytes(value),
527 key_descriptor.state()));
David Rogersdf025cd2020-02-06 17:05:34 -0800528
529 // Do the valid bytes accounting for the sector the entry was relocated out
530 // of.
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
Wyatt Heplere541e072020-02-14 09:10:53 -0800711 TRY_ASSIGN(const size_t written, entry.Write(key, value));
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800712
713 if (options_.verify_on_write) {
Wyatt Heplere541e072020-02-14 09:10:53 -0800714 TRY(entry.VerifyChecksumInFlash(entry_header_format_.checksum));
Wyatt Heplerb7609542020-01-24 10:29:54 -0800715 }
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800716
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800717 entry.UpdateDescriptor(key_descriptor);
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800718 sector->MarkValidBytesWritten(written);
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800719 return Status::OK;
Wyatt Heplerb7609542020-01-24 10:29:54 -0800720}
721
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800722Entry KeyValueStore::CreateEntry(Address address,
723 std::string_view key,
724 span<const byte> value,
725 KeyDescriptor::State state) {
726 const uint32_t transaction_id = ++last_transaction_id_;
727
728 if (state == KeyDescriptor::kDeleted) {
729 return Entry::Tombstone(partition_,
730 address,
731 entry_header_format_.magic,
732 entry_header_format_.checksum,
733 key,
734 partition_.alignment_bytes(),
735 transaction_id);
736 }
737 return Entry::Valid(partition_,
738 address,
739 entry_header_format_.magic,
740 entry_header_format_.checksum,
741 key,
742 value,
743 partition_.alignment_bytes(),
744 transaction_id);
745}
746
Keir Mierle8c352dc2020-02-02 13:58:19 -0800747void KeyValueStore::LogDebugInfo() {
Keir Mierle8c352dc2020-02-02 13:58:19 -0800748 const size_t sector_size_bytes = partition_.sector_size_bytes();
749 DBG("====================== KEY VALUE STORE DUMP =========================");
750 DBG(" ");
751 DBG("Flash partition:");
Wyatt Heplerad0a7932020-02-06 08:20:38 -0800752 DBG(" Sector count = %zu", partition_.sector_count());
Wyatt Hepler38ce30f2020-02-19 11:48:31 -0800753 DBG(" Sector max count = %zu", sectors_.max_size());
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800754 DBG(" Sectors in use = %zu", sectors_.size());
Keir Mierle8c352dc2020-02-02 13:58:19 -0800755 DBG(" Sector size = %zu", sector_size_bytes);
756 DBG(" Total size = %zu", partition_.size_bytes());
757 DBG(" Alignment = %zu", partition_.alignment_bytes());
758 DBG(" ");
759 DBG("Key descriptors:");
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800760 DBG(" Entry count = %zu", key_descriptors_.size());
Wyatt Hepler38ce30f2020-02-19 11:48:31 -0800761 DBG(" Max entry count = %zu", key_descriptors_.max_size());
Keir Mierle8c352dc2020-02-02 13:58:19 -0800762 DBG(" ");
763 DBG(" # hash version address address (hex)");
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800764 for (size_t i = 0; i < key_descriptors_.size(); ++i) {
765 const KeyDescriptor& kd = key_descriptors_[i];
Keir Mierle8c352dc2020-02-02 13:58:19 -0800766 DBG(" |%3zu: | %8zx |%8zu | %8zu | %8zx",
767 i,
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800768 size_t(kd.hash()),
769 size_t(kd.transaction_id()),
770 size_t(kd.address()),
771 size_t(kd.address()));
Keir Mierle8c352dc2020-02-02 13:58:19 -0800772 }
773 DBG(" ");
774
775 DBG("Sector descriptors:");
776 DBG(" # tail free valid has_space");
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800777 for (size_t sector_id = 0; sector_id < sectors_.size(); ++sector_id) {
778 const SectorDescriptor& sd = sectors_[sector_id];
Keir Mierle8c352dc2020-02-02 13:58:19 -0800779 DBG(" |%3zu: | %8zu |%8zu | %s",
780 sector_id,
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800781 size_t(sd.writable_bytes()),
782 sd.valid_bytes(),
783 sd.writable_bytes() ? "YES" : "");
Keir Mierle8c352dc2020-02-02 13:58:19 -0800784 }
785 DBG(" ");
786
787 // TODO: This should stop logging after some threshold.
788 // size_t dumped_bytes = 0;
789 DBG("Sector raw data:");
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800790 for (size_t sector_id = 0; sector_id < sectors_.size(); ++sector_id) {
Keir Mierle8c352dc2020-02-02 13:58:19 -0800791 // Read sector data. Yes, this will blow the stack on embedded.
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800792 std::array<byte, 500> raw_sector_data; // TODO!!!
Keir Mierle8c352dc2020-02-02 13:58:19 -0800793 StatusWithSize sws =
794 partition_.Read(sector_id * sector_size_bytes, raw_sector_data);
795 DBG("Read: %zu bytes", sws.size());
796
797 DBG(" base addr offs 0 1 2 3 4 5 6 7");
798 for (size_t i = 0; i < sector_size_bytes; i += 8) {
799 DBG(" %3zu %8zx %5zu | %02x %02x %02x %02x %02x %02x %02x %02x",
800 sector_id,
801 (sector_id * sector_size_bytes) + i,
802 i,
803 static_cast<unsigned int>(raw_sector_data[i + 0]),
804 static_cast<unsigned int>(raw_sector_data[i + 1]),
805 static_cast<unsigned int>(raw_sector_data[i + 2]),
806 static_cast<unsigned int>(raw_sector_data[i + 3]),
807 static_cast<unsigned int>(raw_sector_data[i + 4]),
808 static_cast<unsigned int>(raw_sector_data[i + 5]),
809 static_cast<unsigned int>(raw_sector_data[i + 6]),
810 static_cast<unsigned int>(raw_sector_data[i + 7]));
811
812 // TODO: Fix exit condition.
813 if (i > 128) {
814 break;
815 }
816 }
817 DBG(" ");
818 }
819
820 DBG("////////////////////// KEY VALUE STORE DUMP END /////////////////////");
821}
822
David Rogerscf680ab2020-02-12 23:28:32 -0800823void KeyValueStore::LogSectors() const {
824 DBG("Sector descriptors: count %zu", sectors_.size());
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800825 for (auto& sector : sectors_) {
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800826 DBG(" - Sector %u: valid %zu, recoverable %zu, free %zu",
David Rogers50185ad2020-02-07 00:02:46 -0800827 SectorIndex(&sector),
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800828 sector.valid_bytes(),
829 sector.RecoverableBytes(partition_.sector_size_bytes()),
830 sector.writable_bytes());
David Rogers50185ad2020-02-07 00:02:46 -0800831 }
832}
833
David Rogerscf680ab2020-02-12 23:28:32 -0800834void KeyValueStore::LogKeyDescriptor() const {
835 DBG("Key descriptors: count %zu", key_descriptors_.size());
836 for (auto& key : key_descriptors_) {
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800837 DBG(" - Key: %s, hash %#zx, transaction ID %zu, address %#zx",
David Rogerscf680ab2020-02-12 23:28:32 -0800838 key.deleted() ? "Deleted" : "Valid",
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800839 static_cast<size_t>(key.hash()),
840 static_cast<size_t>(key.transaction_id()),
841 static_cast<size_t>(key.address()));
David Rogerscf680ab2020-02-12 23:28:32 -0800842 }
843}
844
Wyatt Hepler2ad60672020-01-21 08:00:16 -0800845} // namespace pw::kvs