blob: 2fe9504b87a3227a5c698c7578e3344a0b8c2079 [file] [log] [blame]
Wyatt Heplerb7609542020-01-24 10:29:54 -08001// Copyright 2020 The Pigweed Authors
2//
3// Licensed under the Apache License, Version 2.0 (the "License"); you may not
4// use this file except in compliance with the License. You may obtain a copy of
5// the License at
6//
7// https://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
11// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12// License for the specific language governing permissions and limitations under
13// the License.
14
Wyatt Heplerb7609542020-01-24 10:29:54 -080015#include "pw_kvs/key_value_store.h"
16
Wyatt Heplerbab0e202020-02-04 07:40:08 -080017#include <algorithm>
Wyatt Hepler5a33d8c2020-02-06 09:32:58 -080018#include <cinttypes>
Wyatt Heplerb7609542020-01-24 10:29:54 -080019#include <cstring>
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -080020#include <type_traits>
Wyatt Heplerb7609542020-01-24 10:29:54 -080021
Keir Mierle8c352dc2020-02-02 13:58:19 -080022#define PW_LOG_USE_ULTRA_SHORT_NAMES 1
Wyatt Heplerd31d9702020-02-14 08:46:36 -080023#include "pw_kvs_private/entry.h"
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -080024#include "pw_kvs_private/macros.h"
Keir Mierle8c352dc2020-02-02 13:58:19 -080025#include "pw_log/log.h"
Wyatt Heplerb7609542020-01-24 10:29:54 -080026
Wyatt Hepler2ad60672020-01-21 08:00:16 -080027namespace pw::kvs {
Wyatt Heplera00d1ef2020-02-14 14:31:26 -080028namespace {
Wyatt Heplerb7609542020-01-24 10:29:54 -080029
Wyatt Hepleracaacf92020-01-24 10:58:30 -080030using std::byte;
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -080031using std::string_view;
Wyatt Hepleracaacf92020-01-24 10:58:30 -080032
Wyatt Heplera00d1ef2020-02-14 14:31:26 -080033constexpr bool InvalidKey(std::string_view key) {
34 return key.empty() || (key.size() > Entry::kMaxKeyLength);
35}
36
37} // namespace
38
Wyatt Heplerad0a7932020-02-06 08:20:38 -080039KeyValueStore::KeyValueStore(FlashPartition* partition,
Wyatt Hepler38ce30f2020-02-19 11:48:31 -080040 Vector<KeyDescriptor>& key_descriptor_list,
41 Vector<SectorDescriptor>& sector_descriptor_list,
Wyatt Heplerad0a7932020-02-06 08:20:38 -080042 const EntryHeaderFormat& format,
43 const Options& options)
44 : partition_(*partition),
45 entry_header_format_(format),
46 options_(options),
Wyatt Hepler38ce30f2020-02-19 11:48:31 -080047 key_descriptors_(key_descriptor_list),
48 sectors_(sector_descriptor_list),
Wyatt Hepler5406a672020-02-18 15:42:38 -080049 last_new_sector_(sectors_.data()) {}
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
David Rogers8ce55cd2020-02-04 19:41:48 -080065 // TODO: init last_new_sector_ to a random sector. Since the on-flash stored
66 // information does not allow recovering the previous last_new_sector_ after
67 // clean start, random is a good second choice.
68
Keir Mierle8c352dc2020-02-02 13:58:19 -080069 const size_t sector_size_bytes = partition_.sector_size_bytes();
Keir Mierle8c352dc2020-02-02 13:58:19 -080070
David Rogersf0a35442020-02-04 12:16:38 -080071 if (working_buffer_.size() < sector_size_bytes) {
David Rogers2e9e0c82020-02-13 15:06:06 -080072 ERR("KVS init failed: working_buffer_ (%zu bytes) is smaller than sector "
73 "size (%zu bytes)",
David Rogersf0a35442020-02-04 12:16:38 -080074 working_buffer_.size(),
75 sector_size_bytes);
76 return Status::INVALID_ARGUMENT;
77 }
78
Keir Mierle8c352dc2020-02-02 13:58:19 -080079 DBG("First pass: Read all entries from all sectors");
Wyatt Hepler2c7eca02020-02-18 16:01:42 -080080 Address sector_address = 0;
Keir Mierle8c352dc2020-02-02 13:58:19 -080081
Wyatt Hepler2c7eca02020-02-18 16:01:42 -080082 for (SectorDescriptor& sector : sectors_) {
83 // Reset the sector's valid and writable byte counts. These will be updated
84 // after reading each entry.
85 sector.Reset(sector_size_bytes);
Keir Mierle8c352dc2020-02-02 13:58:19 -080086 Address entry_address = sector_address;
87
Wyatt Hepler2c7eca02020-02-18 16:01:42 -080088 for (int num_entries_in_sector = 0; true; num_entries_in_sector++) {
89 DBG("Load entry: sector=%" PRIx32 ", entry#=%d, address=%" PRIx32,
90 sector_address,
Keir Mierle8c352dc2020-02-02 13:58:19 -080091 num_entries_in_sector,
Wyatt Hepler2c7eca02020-02-18 16:01:42 -080092 entry_address);
Keir Mierle8c352dc2020-02-02 13:58:19 -080093
Wyatt Hepler2c7eca02020-02-18 16:01:42 -080094 if (!AddressInSector(sector, entry_address)) {
Keir Mierle8c352dc2020-02-02 13:58:19 -080095 DBG("Fell off end of sector; moving to the next sector");
96 break;
97 }
98
99 Address next_entry_address;
100 Status status = LoadEntry(entry_address, &next_entry_address);
101 if (status == Status::NOT_FOUND) {
102 DBG("Hit un-written data in sector; moving to the next sector");
103 break;
104 }
105 if (status == Status::DATA_LOSS) {
106 // It's not clear KVS can make a unilateral decision about what to do
107 // in corruption cases. It's an application decision, for which we
108 // should offer some configurability. For now, entirely bail out of
109 // loading and give up.
110 //
111 // Later, scan for remaining valid keys; since it's entirely possible
112 // that there is a duplicate of the key elsewhere and everything is
113 // fine. Later, we can wipe and maybe recover the sector.
114 //
115 // TODO: Implement rest-of-sector scanning for valid entries.
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800116 ERR("KVS init failed: data loss detected in sector %u at address %zu",
117 SectorIndex(&sector),
118 size_t(entry_address));
Keir Mierle8c352dc2020-02-02 13:58:19 -0800119 return Status::DATA_LOSS;
120 }
121 TRY(status);
122
123 // Entry loaded successfully; so get ready to load the next one.
124 entry_address = next_entry_address;
125
126 // Update of the number of writable bytes in this sector.
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800127 sector.set_writable_bytes(sector_size_bytes -
128 (entry_address - sector_address));
Keir Mierle8c352dc2020-02-02 13:58:19 -0800129 }
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800130
131 sector_address += sector_size_bytes;
Keir Mierle8c352dc2020-02-02 13:58:19 -0800132 }
133
134 DBG("Second pass: Count valid bytes in each sector");
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;
138 TRY(Entry::Read(partition_, key_descriptor.address, &entry));
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800139 SectorFromAddress(key_descriptor.address)->AddValidBytes(entry.size());
Keir Mierle8c352dc2020-02-02 13:58:19 -0800140 }
Wyatt Hepler729f28c2020-02-05 09:46:00 -0800141 initialized_ = true;
David Rogers2e9e0c82020-02-13 15:06:06 -0800142
Armando Montanez5464d5f2020-02-20 10:12:20 -0800143 INF("KeyValueStore init complete: active keys %zu, deleted keys %zu, sectors "
David Rogers2e9e0c82020-02-13 15:06:06 -0800144 "%zu, logical sector size %zu bytes",
145 size(),
146 (key_descriptors_.size() - size()),
147 sectors_.size(),
148 partition_.sector_size_bytes());
149
Keir Mierle8c352dc2020-02-02 13:58:19 -0800150 return Status::OK;
151}
152
153Status KeyValueStore::LoadEntry(Address entry_address,
154 Address* next_entry_address) {
Wyatt Heplere541e072020-02-14 09:10:53 -0800155 Entry entry;
156 TRY(Entry::Read(partition_, entry_address, &entry));
Keir Mierle8c352dc2020-02-02 13:58:19 -0800157
158 // TODO: Handle multiple magics for formats that have changed.
Wyatt Heplere541e072020-02-14 09:10:53 -0800159 if (entry.magic() != entry_header_format_.magic) {
Keir Mierle8c352dc2020-02-02 13:58:19 -0800160 // TODO: It may be cleaner to have some logging helpers for these cases.
Wyatt Heplere541e072020-02-14 09:10:53 -0800161 ERR("Found corrupt magic: %zx; expecting %zx; at address %zx",
162 size_t(entry.magic()),
Keir Mierle8c352dc2020-02-02 13:58:19 -0800163 size_t(entry_header_format_.magic),
164 size_t(entry_address));
165 return Status::DATA_LOSS;
166 }
167
168 // Read the key from flash & validate the entry (which reads the value).
Wyatt Heplera00d1ef2020-02-14 14:31:26 -0800169 Entry::KeyBuffer key_buffer;
Wyatt Heplere541e072020-02-14 09:10:53 -0800170 TRY_ASSIGN(size_t key_length, entry.ReadKey(key_buffer));
171 const string_view key(key_buffer.data(), key_length);
Wyatt Heplerbab0e202020-02-04 07:40:08 -0800172
Wyatt Heplere541e072020-02-14 09:10:53 -0800173 TRY(entry.VerifyChecksumInFlash(entry_header_format_.checksum));
Wyatt Hepler4d78cd62020-02-05 13:05:58 -0800174
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800175 KeyDescriptor key_descriptor(
176 key,
Wyatt Heplere541e072020-02-14 09:10:53 -0800177 entry.key_version(),
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800178 entry_address,
Wyatt Heplere541e072020-02-14 09:10:53 -0800179 entry.deleted() ? KeyDescriptor::kDeleted : KeyDescriptor::kValid);
Keir Mierle8c352dc2020-02-02 13:58:19 -0800180
181 DBG("Key hash: %zx (%zu)",
182 size_t(key_descriptor.key_hash),
183 size_t(key_descriptor.key_hash));
184
185 TRY(AppendNewOrOverwriteStaleExistingDescriptor(key_descriptor));
186
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.
199 KeyDescriptor* existing_descriptor = FindDescriptor(key_descriptor.key_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);
207 } else if (existing_descriptor->key_version < key_descriptor.key_version) {
208 // Existing entry is old; replace the existing entry with the new one.
209 *existing_descriptor = key_descriptor;
210 } else {
211 // Otherwise, check for data integrity and leave the existing entry.
212 if (existing_descriptor->key_version == key_descriptor.key_version) {
213 ERR("Data loss: Duplicated old(=%zu) and new(=%zu) version",
214 size_t(existing_descriptor->key_version),
215 size_t(key_descriptor.key_version));
216 return Status::DATA_LOSS;
217 }
218 DBG("Found stale entry when appending; ignoring");
Keir Mierle8c352dc2020-02-02 13:58:19 -0800219 }
Keir Mierle8c352dc2020-02-02 13:58:19 -0800220 return Status::OK;
221}
222
Keir Mierle8c352dc2020-02-02 13:58:19 -0800223KeyValueStore::KeyDescriptor* KeyValueStore::FindDescriptor(uint32_t hash) {
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800224 for (KeyDescriptor& key_descriptor : key_descriptors_) {
225 if (key_descriptor.key_hash == hash) {
226 return &key_descriptor;
Keir Mierle8c352dc2020-02-02 13:58:19 -0800227 }
228 }
229 return nullptr;
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800230}
231
232StatusWithSize KeyValueStore::Get(string_view key,
Wyatt Hepler5f6efc02020-02-18 16:54:31 -0800233 span<byte> value_buffer,
234 size_t offset_bytes) const {
Wyatt Hepler50f70772020-02-13 11:25:10 -0800235 TRY_WITH_SIZE(CheckOperation(key));
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800236
David Rogers2761aeb2020-01-31 17:09:00 -0800237 const KeyDescriptor* key_descriptor;
Wyatt Hepler2d401692020-02-13 16:01:23 -0800238 TRY_WITH_SIZE(FindExistingKeyDescriptor(key, &key_descriptor));
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800239
Wyatt Heplere541e072020-02-14 09:10:53 -0800240 Entry entry;
241 TRY_WITH_SIZE(Entry::Read(partition_, key_descriptor->address, &entry));
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800242
Wyatt Hepler5f6efc02020-02-18 16:54:31 -0800243 StatusWithSize result = entry.ReadValue(value_buffer, offset_bytes);
244 if (result.ok() && options_.verify_on_read && offset_bytes == 0u) {
David Rogerscf680ab2020-02-12 23:28:32 -0800245 Status verify_result =
Wyatt Heplere541e072020-02-14 09:10:53 -0800246 entry.VerifyChecksum(entry_header_format_.checksum,
247 key,
248 value_buffer.subspan(0, result.size()));
David Rogerscf680ab2020-02-12 23:28:32 -0800249 if (!verify_result.ok()) {
Wyatt Hepler50f70772020-02-13 11:25:10 -0800250 std::memset(
251 value_buffer.subspan(0, result.size()).data(), 0, result.size());
252 return StatusWithSize(verify_result);
David Rogerscf680ab2020-02-12 23:28:32 -0800253 }
254
255 return StatusWithSize(verify_result, result.size());
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800256 }
257 return result;
258}
259
260Status KeyValueStore::Put(string_view key, span<const byte> value) {
Keir Mierle8c352dc2020-02-02 13:58:19 -0800261 DBG("Writing key/value; key length=%zu, value length=%zu",
262 key.size(),
263 value.size());
Wyatt Hepler729f28c2020-02-05 09:46:00 -0800264
265 TRY(CheckOperation(key));
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800266
Wyatt Hepler5406a672020-02-18 15:42:38 -0800267 if (Entry::size(partition_, key, value) > partition_.sector_size_bytes()) {
268 DBG("%zu B value with %zu B key cannot fit in one sector",
269 value.size(),
270 key.size());
271 return Status::INVALID_ARGUMENT;
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800272 }
273
David Rogers2761aeb2020-01-31 17:09:00 -0800274 KeyDescriptor* key_descriptor;
Wyatt Hepler2d401692020-02-13 16:01:23 -0800275 Status status = FindKeyDescriptor(key, &key_descriptor);
276
277 if (status.ok()) {
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800278 DBG("Overwriting entry for key %#08" PRIx32 " in sector %u",
David Rogers3464d0a2020-02-07 11:45:46 -0800279 key_descriptor->key_hash,
280 SectorIndex(SectorFromAddress(key_descriptor->address)));
Wyatt Hepler5a33d8c2020-02-06 09:32:58 -0800281 return WriteEntryForExistingKey(
282 key_descriptor, KeyDescriptor::kValid, key, value);
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800283 }
David Rogers2761aeb2020-01-31 17:09:00 -0800284
Wyatt Hepler2d401692020-02-13 16:01:23 -0800285 if (status == Status::NOT_FOUND) {
286 return WriteEntryForNewKey(key, value);
287 }
288
289 return status;
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800290}
291
292Status KeyValueStore::Delete(string_view key) {
Wyatt Hepler729f28c2020-02-05 09:46:00 -0800293 TRY(CheckOperation(key));
294
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800295 KeyDescriptor* key_descriptor;
Wyatt Hepler2d401692020-02-13 16:01:23 -0800296 TRY(FindExistingKeyDescriptor(key, &key_descriptor));
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800297
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800298 DBG("Writing tombstone for key %#08" PRIx32 " in sector %u",
David Rogers3464d0a2020-02-07 11:45:46 -0800299 key_descriptor->key_hash,
300 SectorIndex(SectorFromAddress(key_descriptor->address)));
Wyatt Hepler5a33d8c2020-02-06 09:32:58 -0800301 return WriteEntryForExistingKey(
302 key_descriptor, KeyDescriptor::kDeleted, key, {});
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800303}
304
305KeyValueStore::iterator& KeyValueStore::iterator::operator++() {
306 // Skip to the next entry that is valid (not deleted).
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800307 while (++index_ < item_.kvs_.key_descriptors_.size() &&
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800308 descriptor().deleted()) {
309 }
310 return *this;
311}
312
313const KeyValueStore::Item& KeyValueStore::iterator::operator*() {
314 std::memset(item_.key_buffer_.data(), 0, item_.key_buffer_.size());
315
Wyatt Heplere541e072020-02-14 09:10:53 -0800316 Entry entry;
317 if (Entry::Read(item_.kvs_.partition_, descriptor().address, &entry).ok()) {
318 entry.ReadKey(item_.key_buffer_);
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800319 }
320
321 return item_;
322}
323
324KeyValueStore::iterator KeyValueStore::begin() const {
325 size_t i = 0;
326 // Skip over any deleted entries at the start of the descriptor list.
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800327 while (i < key_descriptors_.size() && key_descriptors_[i].deleted()) {
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800328 i += 1;
329 }
330 return iterator(*this, i);
331}
332
333// TODO(hepler): The valid entry count could be tracked in the KVS to avoid the
334// need for this for-loop.
335size_t KeyValueStore::size() const {
336 size_t valid_entries = 0;
337
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800338 for (const KeyDescriptor& key_descriptor : key_descriptors_) {
339 if (!key_descriptor.deleted()) {
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800340 valid_entries += 1;
341 }
342 }
343
344 return valid_entries;
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800345}
346
Wyatt Heplered163b02020-02-03 17:49:32 -0800347StatusWithSize KeyValueStore::ValueSize(std::string_view key) const {
Wyatt Hepler50f70772020-02-13 11:25:10 -0800348 TRY_WITH_SIZE(CheckOperation(key));
Wyatt Heplered163b02020-02-03 17:49:32 -0800349
350 const KeyDescriptor* key_descriptor;
Wyatt Hepler2d401692020-02-13 16:01:23 -0800351 TRY_WITH_SIZE(FindExistingKeyDescriptor(key, &key_descriptor));
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800352
Wyatt Heplere541e072020-02-14 09:10:53 -0800353 Entry entry;
354 TRY_WITH_SIZE(Entry::Read(partition_, key_descriptor->address, &entry));
Wyatt Heplered163b02020-02-03 17:49:32 -0800355
Wyatt Heplere541e072020-02-14 09:10:53 -0800356 return StatusWithSize(entry.value_size());
Wyatt Heplered163b02020-02-03 17:49:32 -0800357}
358
Wyatt Hepler4d78cd62020-02-05 13:05:58 -0800359uint32_t KeyValueStore::HashKey(string_view string) {
360 uint32_t hash = 0;
361 uint32_t coefficient = 65599u;
362
363 for (char ch : string) {
364 hash += coefficient * unsigned(ch);
365 coefficient *= 65599u;
366 }
367
368 return hash;
369}
370
Wyatt Hepler6e3a83b2020-02-04 07:36:45 -0800371Status KeyValueStore::FixedSizeGet(std::string_view key,
372 byte* value,
373 size_t size_bytes) const {
374 // Ensure that the size of the stored value matches the size of the type.
375 // Otherwise, report error. This check avoids potential memory corruption.
376 StatusWithSize result = ValueSize(key);
377 if (!result.ok()) {
378 return result.status();
Keir Mierle8c352dc2020-02-02 13:58:19 -0800379 }
Wyatt Hepler6e3a83b2020-02-04 07:36:45 -0800380 if (result.size() != size_bytes) {
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800381 DBG("Requested %zu B read, but value is %zu B", size_bytes, result.size());
Wyatt Hepler6e3a83b2020-02-04 07:36:45 -0800382 return Status::INVALID_ARGUMENT;
Wyatt Heplerbab0e202020-02-04 07:40:08 -0800383 }
Wyatt Hepler6e3a83b2020-02-04 07:36:45 -0800384 return Get(key, span(value, size_bytes)).status();
Keir Mierle8c352dc2020-02-02 13:58:19 -0800385}
386
Wyatt Hepler729f28c2020-02-05 09:46:00 -0800387Status KeyValueStore::CheckOperation(string_view key) const {
Wyatt Hepleracaacf92020-01-24 10:58:30 -0800388 if (InvalidKey(key)) {
Wyatt Heplerb7609542020-01-24 10:29:54 -0800389 return Status::INVALID_ARGUMENT;
390 }
Wyatt Hepler729f28c2020-02-05 09:46:00 -0800391 if (!initialized_) {
Wyatt Heplerb7609542020-01-24 10:29:54 -0800392 return Status::FAILED_PRECONDITION;
393 }
Wyatt Heplerb7609542020-01-24 10:29:54 -0800394 return Status::OK;
395}
396
Wyatt Hepler2d401692020-02-13 16:01:23 -0800397// Searches for a KeyDescriptor that matches this key and sets *result to point
398// to it if one is found.
399//
400// OK: there is a matching descriptor and *result is set
401// NOT_FOUND: there is no descriptor that matches this key, but this key
402// has a unique hash (and could potentially be added to the KVS)
403// ALREADY_EXISTS: there is no descriptor that matches this key, but the
404// key's hash collides with the hash for an existing descriptor
405//
David Rogers2761aeb2020-01-31 17:09:00 -0800406Status KeyValueStore::FindKeyDescriptor(string_view key,
407 const KeyDescriptor** result) const {
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800408 const uint32_t hash = HashKey(key);
Wyatt Heplera00d1ef2020-02-14 14:31:26 -0800409 Entry::KeyBuffer key_buffer;
Wyatt Heplerb7609542020-01-24 10:29:54 -0800410
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800411 for (auto& descriptor : key_descriptors_) {
David Rogers2761aeb2020-01-31 17:09:00 -0800412 if (descriptor.key_hash == hash) {
Wyatt Heplere541e072020-02-14 09:10:53 -0800413 TRY(Entry::ReadKey(
Wyatt Heplera00d1ef2020-02-14 14:31:26 -0800414 partition_, descriptor.address, key.size(), key_buffer.data()));
Wyatt Heplerb7609542020-01-24 10:29:54 -0800415
Wyatt Heplere541e072020-02-14 09:10:53 -0800416 if (key == string_view(key_buffer.data(), key.size())) {
Wyatt Hepler5a33d8c2020-02-06 09:32:58 -0800417 DBG("Found match for key hash 0x%08" PRIx32, hash);
David Rogers2761aeb2020-01-31 17:09:00 -0800418 *result = &descriptor;
Wyatt Heplerb7609542020-01-24 10:29:54 -0800419 return Status::OK;
Wyatt Hepler2d401692020-02-13 16:01:23 -0800420 } else {
421 WRN("Found key hash collision for 0x%08" PRIx32, hash);
422 return Status::ALREADY_EXISTS;
Wyatt Heplerb7609542020-01-24 10:29:54 -0800423 }
Wyatt Heplerb7609542020-01-24 10:29:54 -0800424 }
425 }
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800426 return Status::NOT_FOUND;
427}
428
Wyatt Hepler2d401692020-02-13 16:01:23 -0800429// Searches for a KeyDescriptor that matches this key and sets *result to point
430// to it if one is found.
431//
432// OK: there is a matching descriptor and *result is set
433// NOT_FOUND: there is no descriptor that matches this key
434//
435Status KeyValueStore::FindExistingKeyDescriptor(
436 string_view key, const KeyDescriptor** result) const {
437 Status status = FindKeyDescriptor(key, result);
438
439 // If the key's hash collides with an existing key or if the key is deleted,
440 // treat it as if it is not in the KVS.
441 if (status == Status::ALREADY_EXISTS ||
442 (status.ok() && (*result)->deleted())) {
443 return Status::NOT_FOUND;
444 }
445 return status;
446}
447
David Rogers2761aeb2020-01-31 17:09:00 -0800448Status KeyValueStore::WriteEntryForExistingKey(KeyDescriptor* key_descriptor,
Wyatt Hepler5a33d8c2020-02-06 09:32:58 -0800449 KeyDescriptor::State new_state,
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800450 string_view key,
451 span<const byte> value) {
Wyatt Hepler5a33d8c2020-02-06 09:32:58 -0800452 // Find the original entry and sector to update the sector's valid_bytes.
Wyatt Hepler30a52152020-02-12 11:26:05 -0800453 Entry original_entry;
Wyatt Heplere541e072020-02-14 09:10:53 -0800454 TRY(Entry::Read(partition_, key_descriptor->address, &original_entry));
David Rogers3464d0a2020-02-07 11:45:46 -0800455 SectorDescriptor* old_sector = SectorFromAddress(key_descriptor->address);
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800456
David Rogers2761aeb2020-01-31 17:09:00 -0800457 SectorDescriptor* sector;
Wyatt Hepler5406a672020-02-18 15:42:38 -0800458 TRY(FindOrRecoverSectorWithSpace(&sector,
459 Entry::size(partition_, key, value)));
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800460 DBG("Writing existing entry; found sector %u (%#" PRIx32 ")",
461 SectorIndex(sector),
462 SectorBaseAddress(sector));
David Rogers3464d0a2020-02-07 11:45:46 -0800463
464 if (old_sector != SectorFromAddress(key_descriptor->address)) {
465 DBG("Sector for old entry (size %zu) was garbage collected. Old entry "
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800466 "relocated to sector %u",
David Rogers3464d0a2020-02-07 11:45:46 -0800467 original_entry.size(),
468 SectorIndex(SectorFromAddress(key_descriptor->address)));
469
470 old_sector = SectorFromAddress(key_descriptor->address);
471 }
472
Wyatt Hepler5a33d8c2020-02-06 09:32:58 -0800473 TRY(AppendEntry(sector, key_descriptor, key, value, new_state));
474
David Rogers3464d0a2020-02-07 11:45:46 -0800475 old_sector->RemoveValidBytes(original_entry.size());
Wyatt Hepler5a33d8c2020-02-06 09:32:58 -0800476 return Status::OK;
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800477}
478
479Status KeyValueStore::WriteEntryForNewKey(string_view key,
480 span<const byte> value) {
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800481 if (key_descriptors_.full()) {
Keir Mierle8c352dc2020-02-02 13:58:19 -0800482 WRN("KVS full: trying to store a new entry, but can't. Have %zu entries",
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800483 key_descriptors_.size());
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800484 return Status::RESOURCE_EXHAUSTED;
485 }
486
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800487 // Create the KeyDescriptor that will be added to the list. The version and
488 // address will be set by AppendEntry.
489 KeyDescriptor key_descriptor(key, 0, 0);
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800490
David Rogers2761aeb2020-01-31 17:09:00 -0800491 SectorDescriptor* sector;
Wyatt Hepler5406a672020-02-18 15:42:38 -0800492 TRY(FindOrRecoverSectorWithSpace(&sector,
493 Entry::size(partition_, key, value)));
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800494 DBG("Writing new entry; found sector: %u", SectorIndex(sector));
Wyatt Hepler0af6ad92020-02-13 15:54:46 -0800495 TRY(AppendEntry(sector, &key_descriptor, key, value, KeyDescriptor::kValid));
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800496
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800497 // Only add the entry when we are certain the write succeeded.
498 key_descriptors_.push_back(key_descriptor);
Wyatt Heplerb7609542020-01-24 10:29:54 -0800499 return Status::OK;
500}
501
David Rogers2761aeb2020-01-31 17:09:00 -0800502Status KeyValueStore::RelocateEntry(KeyDescriptor& key_descriptor) {
David Rogersf0a35442020-02-04 12:16:38 -0800503 struct TempEntry {
Wyatt Heplere541e072020-02-14 09:10:53 -0800504 Entry::KeyBuffer key;
David Rogersf0a35442020-02-04 12:16:38 -0800505 std::array<char, sizeof(working_buffer_) - sizeof(key)> value;
506 };
Wyatt Heplere541e072020-02-14 09:10:53 -0800507 TempEntry* temp_entry = reinterpret_cast<TempEntry*>(working_buffer_.data());
David Rogersf0a35442020-02-04 12:16:38 -0800508
David Rogersdf025cd2020-02-06 17:05:34 -0800509 DBG("Relocating entry"); // TODO: add entry info to the log statement.
510
Wyatt Heplere541e072020-02-14 09:10:53 -0800511 // Read the entry to be relocated. Store the entry in a local variable and
David Rogersf0a35442020-02-04 12:16:38 -0800512 // store the key and value in the TempEntry stored in the static allocated
513 // working_buffer_.
Wyatt Heplere541e072020-02-14 09:10:53 -0800514 Entry entry;
515 TRY(Entry::Read(partition_, key_descriptor.address, &entry));
516 TRY_ASSIGN(size_t key_length, entry.ReadKey(temp_entry->key));
517 string_view key = string_view(temp_entry->key.data(), key_length);
518 auto result = entry.ReadValue(as_writable_bytes(span(temp_entry->value)));
David Rogersf0a35442020-02-04 12:16:38 -0800519 if (!result.status().ok()) {
520 return Status::INTERNAL;
521 }
522
Wyatt Heplere541e072020-02-14 09:10:53 -0800523 auto value = span(temp_entry->value.data(), result.size());
524 TRY(entry.VerifyChecksum(
David Rogersf0a35442020-02-04 12:16:38 -0800525 entry_header_format_.checksum, key, as_bytes(value)));
526
David Rogers3464d0a2020-02-07 11:45:46 -0800527 SectorDescriptor* old_sector = SectorFromAddress(key_descriptor.address);
David Rogersf0a35442020-02-04 12:16:38 -0800528
529 // Find a new sector for the entry and write it to the new location.
David Rogers8ce55cd2020-02-04 19:41:48 -0800530 SectorDescriptor* new_sector;
Wyatt Heplere541e072020-02-14 09:10:53 -0800531 TRY(FindSectorWithSpace(&new_sector, entry.size(), old_sector, true));
Wyatt Hepler0af6ad92020-02-13 15:54:46 -0800532 TRY(AppendEntry(
533 new_sector, &key_descriptor, key, as_bytes(value), key_descriptor.state));
David Rogersdf025cd2020-02-06 17:05:34 -0800534
535 // Do the valid bytes accounting for the sector the entry was relocated out
536 // of.
Wyatt Heplere541e072020-02-14 09:10:53 -0800537 old_sector->RemoveValidBytes(entry.size());
David Rogersdf025cd2020-02-06 17:05:34 -0800538
539 return Status::OK;
David Rogersa12786b2020-01-31 16:02:33 -0800540}
541
David Rogers8db5a722020-02-03 18:28:34 -0800542// Find either an existing sector with enough space that is not the sector to
543// skip, or an empty sector. Maintains the invariant that there is always at
544// least 1 empty sector unless set to bypass the rule.
Wyatt Hepler5a33d8c2020-02-06 09:32:58 -0800545Status KeyValueStore::FindSectorWithSpace(
546 SectorDescriptor** found_sector,
547 size_t size,
548 const SectorDescriptor* sector_to_skip,
549 bool bypass_empty_sector_rule) {
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800550 SectorDescriptor* first_empty_sector = nullptr;
551 bool at_least_two_empty_sectors = bypass_empty_sector_rule;
552
553 DBG("Find sector with %zu bytes available, starting with sector %u",
554 size,
555 SectorIndex(last_new_sector_));
556 if (sector_to_skip != nullptr) {
557 DBG(" Skip sector %u", SectorIndex(sector_to_skip));
558 }
559 if (bypass_empty_sector_rule) {
560 DBG(" Bypassing empty sector rule");
561 }
562
David Rogers8ce55cd2020-02-04 19:41:48 -0800563 // The last_new_sector_ is the sector that was last selected as the "new empty
564 // sector" to write to. This last new sector is used as the starting point for
565 // the next "find a new empty sector to write to" operation. By using the last
566 // new sector as the start point we will cycle which empty sector is selected
567 // next, spreading the wear across all the empty sectors and get a wear
568 // leveling benefit, rather than putting more wear on the lower number
569 // sectors.
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800570 SectorDescriptor* sector = last_new_sector_;
David Rogers67f4b6c2020-02-06 16:17:09 -0800571
David Rogers8ce55cd2020-02-04 19:41:48 -0800572 // Look for a partial sector to use with enough space. Immediately use the
573 // first one of those that is found. While scanning for a partial sector, keep
574 // track of the first empty sector and if a second sector was seen.
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800575 for (size_t j = 0; j < sectors_.size(); j++) {
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800576 sector += 1;
577 if (sector == sectors_.end()) {
578 sector = sectors_.begin();
579 }
Keir Mierle8c352dc2020-02-02 13:58:19 -0800580
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800581 if (sector_to_skip == sector) {
David Rogers8db5a722020-02-03 18:28:34 -0800582 continue;
583 }
584
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800585 const size_t sector_size_bytes = partition_.sector_size_bytes();
586 if (!sector->Empty(sector_size_bytes) && sector->HasSpace(size)) {
587 *found_sector = sector;
David Rogers8ce55cd2020-02-04 19:41:48 -0800588 return Status::OK;
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800589 }
590
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800591 if (sector->Empty(sector_size_bytes)) {
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800592 if (first_empty_sector == nullptr) {
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800593 first_empty_sector = sector;
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800594 } else {
595 at_least_two_empty_sectors = true;
Wyatt Hepler2ad60672020-01-21 08:00:16 -0800596 }
Wyatt Heplerb7609542020-01-24 10:29:54 -0800597 }
598 }
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800599
David Rogers8ce55cd2020-02-04 19:41:48 -0800600 // If the scan for a partial sector does not find a suitable sector, use the
601 // first empty sector that was found. Normally it is required to keep 1 empty
602 // sector after the sector found here, but that rule can be bypassed in
603 // special circumstances (such as during garbage collection).
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800604 if (at_least_two_empty_sectors) {
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800605 DBG(" Found a usable empty sector; returning the first found (%u)",
David Rogers8ce55cd2020-02-04 19:41:48 -0800606 SectorIndex(first_empty_sector));
607 last_new_sector_ = first_empty_sector;
608 *found_sector = first_empty_sector;
609 return Status::OK;
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800610 }
David Rogers8ce55cd2020-02-04 19:41:48 -0800611
612 // No sector was found.
David Rogers67f4b6c2020-02-06 16:17:09 -0800613 DBG(" Unable to find a usable sector");
David Rogers8ce55cd2020-02-04 19:41:48 -0800614 *found_sector = nullptr;
615 return Status::RESOURCE_EXHAUSTED;
Wyatt Heplerb7609542020-01-24 10:29:54 -0800616}
617
David Rogers2761aeb2020-01-31 17:09:00 -0800618Status KeyValueStore::FindOrRecoverSectorWithSpace(SectorDescriptor** sector,
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800619 size_t size) {
David Rogers8ce55cd2020-02-04 19:41:48 -0800620 Status result = FindSectorWithSpace(sector, size);
Wyatt Hepler2d401692020-02-13 16:01:23 -0800621 if (result == Status::RESOURCE_EXHAUSTED && options_.partial_gc_on_write) {
David Rogers1541d612020-02-06 23:47:02 -0800622 // Garbage collect and then try again to find the best sector.
623 TRY(GarbageCollectOneSector());
624 return FindSectorWithSpace(sector, size);
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800625 }
David Rogers8ce55cd2020-02-04 19:41:48 -0800626 return result;
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800627}
628
David Rogers2761aeb2020-01-31 17:09:00 -0800629KeyValueStore::SectorDescriptor* KeyValueStore::FindSectorToGarbageCollect() {
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800630 const size_t sector_size_bytes = partition_.sector_size_bytes();
David Rogers2761aeb2020-01-31 17:09:00 -0800631 SectorDescriptor* sector_candidate = nullptr;
David Rogersa12786b2020-01-31 16:02:33 -0800632 size_t candidate_bytes = 0;
633
634 // Step 1: Try to find a sectors with stale keys and no valid keys (no
635 // relocation needed). If any such sectors are found, use the sector with the
636 // most reclaimable bytes.
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800637 for (auto& sector : sectors_) {
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800638 if ((sector.valid_bytes() == 0) &&
639 (sector.RecoverableBytes(sector_size_bytes) > candidate_bytes)) {
David Rogersa12786b2020-01-31 16:02:33 -0800640 sector_candidate = &sector;
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800641 candidate_bytes = sector.RecoverableBytes(sector_size_bytes);
David Rogersa12786b2020-01-31 16:02:33 -0800642 }
643 }
644
645 // Step 2: If step 1 yields no sectors, just find the sector with the most
646 // reclaimable bytes.
647 if (sector_candidate == nullptr) {
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800648 for (auto& sector : sectors_) {
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800649 if (sector.RecoverableBytes(sector_size_bytes) > candidate_bytes) {
David Rogersa12786b2020-01-31 16:02:33 -0800650 sector_candidate = &sector;
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800651 candidate_bytes = sector.RecoverableBytes(sector_size_bytes);
David Rogersa12786b2020-01-31 16:02:33 -0800652 }
653 }
654 }
655
David Rogers5981f312020-02-13 13:33:56 -0800656 if (sector_candidate != nullptr) {
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800657 DBG("Found sector %u to Garbage Collect, %zu recoverable bytes",
David Rogers5981f312020-02-13 13:33:56 -0800658 SectorIndex(sector_candidate),
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800659 sector_candidate->RecoverableBytes(sector_size_bytes));
David Rogers5981f312020-02-13 13:33:56 -0800660 } else {
661 DBG("Unable to find sector to garbage collect!");
662 }
David Rogersa12786b2020-01-31 16:02:33 -0800663 return sector_candidate;
664}
665
David Rogers1541d612020-02-06 23:47:02 -0800666Status KeyValueStore::GarbageCollectOneSector() {
David Rogers67f4b6c2020-02-06 16:17:09 -0800667 DBG("Garbage Collect a single sector");
668
David Rogersa12786b2020-01-31 16:02:33 -0800669 // Step 1: Find the sector to garbage collect
David Rogers2761aeb2020-01-31 17:09:00 -0800670 SectorDescriptor* sector_to_gc = FindSectorToGarbageCollect();
David Rogers3464d0a2020-02-07 11:45:46 -0800671 LogSectors();
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800672
David Rogersa12786b2020-01-31 16:02:33 -0800673 if (sector_to_gc == nullptr) {
674 return Status::RESOURCE_EXHAUSTED;
675 }
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800676
David Rogersa12786b2020-01-31 16:02:33 -0800677 // Step 2: Move any valid entries in the GC sector to other sectors
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800678 if (sector_to_gc->valid_bytes() != 0) {
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800679 for (auto& descriptor : key_descriptors_) {
David Rogers2761aeb2020-01-31 17:09:00 -0800680 if (AddressInSector(*sector_to_gc, descriptor.address)) {
David Rogers67f4b6c2020-02-06 16:17:09 -0800681 DBG(" Relocate entry");
David Rogers2761aeb2020-01-31 17:09:00 -0800682 TRY(RelocateEntry(descriptor));
David Rogersa12786b2020-01-31 16:02:33 -0800683 }
Wyatt Heplerb7609542020-01-24 10:29:54 -0800684 }
685 }
Wyatt Heplerb7609542020-01-24 10:29:54 -0800686
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800687 if (sector_to_gc->valid_bytes() != 0) {
David Rogers67f4b6c2020-02-06 16:17:09 -0800688 ERR(" Failed to relocate valid entries from sector being garbage "
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800689 "collected, %zu valid bytes remain",
690 sector_to_gc->valid_bytes());
Wyatt Heplerb7609542020-01-24 10:29:54 -0800691 return Status::INTERNAL;
692 }
693
David Rogersa12786b2020-01-31 16:02:33 -0800694 // Step 3: Reinitialize the sector
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800695 sector_to_gc->set_writable_bytes(0);
David Rogersa12786b2020-01-31 16:02:33 -0800696 TRY(partition_.Erase(SectorBaseAddress(sector_to_gc), 1));
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800697 sector_to_gc->set_writable_bytes(partition_.sector_size_bytes());
Wyatt Heplerb7609542020-01-24 10:29:54 -0800698
David Rogers67f4b6c2020-02-06 16:17:09 -0800699 DBG(" Garbage Collect complete");
David Rogers50185ad2020-02-07 00:02:46 -0800700 LogSectors();
David Rogersa12786b2020-01-31 16:02:33 -0800701 return Status::OK;
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800702}
703
David Rogers2761aeb2020-01-31 17:09:00 -0800704Status KeyValueStore::AppendEntry(SectorDescriptor* sector,
705 KeyDescriptor* key_descriptor,
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800706 const string_view key,
Wyatt Hepler5a33d8c2020-02-06 09:32:58 -0800707 span<const byte> value,
708 KeyDescriptor::State new_state) {
Wyatt Heplere541e072020-02-14 09:10:53 -0800709 const Address address = NextWritableAddress(sector);
710 DBG("Appending to address: %#zx", size_t(address));
711
712 Entry entry;
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800713
Wyatt Hepler5a33d8c2020-02-06 09:32:58 -0800714 if (new_state == KeyDescriptor::kDeleted) {
Wyatt Heplere541e072020-02-14 09:10:53 -0800715 entry = Entry::Tombstone(partition_,
716 address,
717 entry_header_format_.magic,
718 entry_header_format_.checksum,
719 key,
720 partition_.alignment_bytes(),
721 key_descriptor->key_version + 1);
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800722 } else {
Wyatt Heplere541e072020-02-14 09:10:53 -0800723 entry = Entry::Valid(partition_,
724 address,
725 entry_header_format_.magic,
726 entry_header_format_.checksum,
727 key,
728 value,
729 partition_.alignment_bytes(),
730 key_descriptor->key_version + 1);
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800731 }
732
Wyatt Hepler97fc7942020-02-06 15:55:45 -0800733 DBG("Appending %zu B entry with key version: %x",
Wyatt Heplere541e072020-02-14 09:10:53 -0800734 entry.size(),
735 unsigned(entry.key_version()));
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800736
Wyatt Heplere541e072020-02-14 09:10:53 -0800737 TRY_ASSIGN(const size_t written, entry.Write(key, value));
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800738
739 if (options_.verify_on_write) {
Wyatt Heplere541e072020-02-14 09:10:53 -0800740 TRY(entry.VerifyChecksumInFlash(entry_header_format_.checksum));
Wyatt Heplerb7609542020-01-24 10:29:54 -0800741 }
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800742
David Rogers2761aeb2020-01-31 17:09:00 -0800743 key_descriptor->address = address;
Wyatt Heplere541e072020-02-14 09:10:53 -0800744 key_descriptor->key_version = entry.key_version();
Wyatt Hepler5a33d8c2020-02-06 09:32:58 -0800745 key_descriptor->state = new_state;
746
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800747 sector->MarkValidBytesWritten(written);
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800748 return Status::OK;
Wyatt Heplerb7609542020-01-24 10:29:54 -0800749}
750
Keir Mierle8c352dc2020-02-02 13:58:19 -0800751void KeyValueStore::LogDebugInfo() {
Keir Mierle8c352dc2020-02-02 13:58:19 -0800752 const size_t sector_size_bytes = partition_.sector_size_bytes();
753 DBG("====================== KEY VALUE STORE DUMP =========================");
754 DBG(" ");
755 DBG("Flash partition:");
Wyatt Heplerad0a7932020-02-06 08:20:38 -0800756 DBG(" Sector count = %zu", partition_.sector_count());
Wyatt Hepler38ce30f2020-02-19 11:48:31 -0800757 DBG(" Sector max count = %zu", sectors_.max_size());
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800758 DBG(" Sectors in use = %zu", sectors_.size());
Keir Mierle8c352dc2020-02-02 13:58:19 -0800759 DBG(" Sector size = %zu", sector_size_bytes);
760 DBG(" Total size = %zu", partition_.size_bytes());
761 DBG(" Alignment = %zu", partition_.alignment_bytes());
762 DBG(" ");
763 DBG("Key descriptors:");
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800764 DBG(" Entry count = %zu", key_descriptors_.size());
Wyatt Hepler38ce30f2020-02-19 11:48:31 -0800765 DBG(" Max entry count = %zu", key_descriptors_.max_size());
Keir Mierle8c352dc2020-02-02 13:58:19 -0800766 DBG(" ");
767 DBG(" # hash version address address (hex)");
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800768 for (size_t i = 0; i < key_descriptors_.size(); ++i) {
769 const KeyDescriptor& kd = key_descriptors_[i];
Keir Mierle8c352dc2020-02-02 13:58:19 -0800770 DBG(" |%3zu: | %8zx |%8zu | %8zu | %8zx",
771 i,
772 size_t(kd.key_hash),
773 size_t(kd.key_version),
774 size_t(kd.address),
775 size_t(kd.address));
776 }
777 DBG(" ");
778
779 DBG("Sector descriptors:");
780 DBG(" # tail free valid has_space");
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800781 for (size_t sector_id = 0; sector_id < sectors_.size(); ++sector_id) {
782 const SectorDescriptor& sd = sectors_[sector_id];
Keir Mierle8c352dc2020-02-02 13:58:19 -0800783 DBG(" |%3zu: | %8zu |%8zu | %s",
784 sector_id,
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800785 size_t(sd.writable_bytes()),
786 sd.valid_bytes(),
787 sd.writable_bytes() ? "YES" : "");
Keir Mierle8c352dc2020-02-02 13:58:19 -0800788 }
789 DBG(" ");
790
791 // TODO: This should stop logging after some threshold.
792 // size_t dumped_bytes = 0;
793 DBG("Sector raw data:");
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800794 for (size_t sector_id = 0; sector_id < sectors_.size(); ++sector_id) {
Keir Mierle8c352dc2020-02-02 13:58:19 -0800795 // Read sector data. Yes, this will blow the stack on embedded.
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800796 std::array<byte, 500> raw_sector_data; // TODO!!!
Keir Mierle8c352dc2020-02-02 13:58:19 -0800797 StatusWithSize sws =
798 partition_.Read(sector_id * sector_size_bytes, raw_sector_data);
799 DBG("Read: %zu bytes", sws.size());
800
801 DBG(" base addr offs 0 1 2 3 4 5 6 7");
802 for (size_t i = 0; i < sector_size_bytes; i += 8) {
803 DBG(" %3zu %8zx %5zu | %02x %02x %02x %02x %02x %02x %02x %02x",
804 sector_id,
805 (sector_id * sector_size_bytes) + i,
806 i,
807 static_cast<unsigned int>(raw_sector_data[i + 0]),
808 static_cast<unsigned int>(raw_sector_data[i + 1]),
809 static_cast<unsigned int>(raw_sector_data[i + 2]),
810 static_cast<unsigned int>(raw_sector_data[i + 3]),
811 static_cast<unsigned int>(raw_sector_data[i + 4]),
812 static_cast<unsigned int>(raw_sector_data[i + 5]),
813 static_cast<unsigned int>(raw_sector_data[i + 6]),
814 static_cast<unsigned int>(raw_sector_data[i + 7]));
815
816 // TODO: Fix exit condition.
817 if (i > 128) {
818 break;
819 }
820 }
821 DBG(" ");
822 }
823
824 DBG("////////////////////// KEY VALUE STORE DUMP END /////////////////////");
825}
826
David Rogerscf680ab2020-02-12 23:28:32 -0800827void KeyValueStore::LogSectors() const {
828 DBG("Sector descriptors: count %zu", sectors_.size());
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800829 for (auto& sector : sectors_) {
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800830 DBG(" - Sector %u: valid %zu, recoverable %zu, free %zu",
David Rogers50185ad2020-02-07 00:02:46 -0800831 SectorIndex(&sector),
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800832 sector.valid_bytes(),
833 sector.RecoverableBytes(partition_.sector_size_bytes()),
834 sector.writable_bytes());
David Rogers50185ad2020-02-07 00:02:46 -0800835 }
836}
837
David Rogerscf680ab2020-02-12 23:28:32 -0800838void KeyValueStore::LogKeyDescriptor() const {
839 DBG("Key descriptors: count %zu", key_descriptors_.size());
840 for (auto& key : key_descriptors_) {
841 DBG(" - Key: %s, hash %#zx, version %zu, address %#zx",
842 key.deleted() ? "Deleted" : "Valid",
843 static_cast<size_t>(key.key_hash),
844 static_cast<size_t>(key.key_version),
845 static_cast<size_t>(key.address));
846 }
847}
848
Wyatt Hepler2ad60672020-01-21 08:00:16 -0800849} // namespace pw::kvs