blob: b1b5148b1510f3129f756e08b09d0ed1f729bd09 [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 Heplerbdd8e5a2020-02-20 19:27:26 -080023#include "pw_kvs/internal/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) {
Wyatt Heplerbdd8e5a2020-02-20 19:27:26 -080034 return key.empty() || (key.size() > internal::Entry::kMaxKeyLength);
Wyatt Heplera00d1ef2020-02-14 14:31:26 -080035}
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),
Wyatt Hepler38ce30f2020-02-19 11:48:31 -080046 key_descriptors_(key_descriptor_list),
Wyatt Heplerd2298282020-02-20 17:12:45 -080047 sectors_(sector_descriptor_list),
48 options_(options) {
49 Reset();
50}
Wyatt Heplerad0a7932020-02-06 08:20:38 -080051
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -080052Status KeyValueStore::Init() {
Wyatt Heplerd2298282020-02-20 17:12:45 -080053 Reset();
54
David Rogers2e9e0c82020-02-13 15:06:06 -080055 INF("Initializing key value store");
Wyatt Hepler38ce30f2020-02-19 11:48:31 -080056 if (partition_.sector_count() > sectors_.max_size()) {
David Rogers2e9e0c82020-02-13 15:06:06 -080057 ERR("KVS init failed: kMaxUsableSectors (=%zu) must be at least as "
58 "large as the number of sectors in the flash partition (=%zu)",
Wyatt Hepler38ce30f2020-02-19 11:48:31 -080059 sectors_.max_size(),
David Rogers2e9e0c82020-02-13 15:06:06 -080060 partition_.sector_count());
Wyatt Heplerad0a7932020-02-06 08:20:38 -080061 return Status::FAILED_PRECONDITION;
62 }
63
Keir Mierle8c352dc2020-02-02 13:58:19 -080064 const size_t sector_size_bytes = partition_.sector_size_bytes();
Keir Mierle8c352dc2020-02-02 13:58:19 -080065
David Rogersf0a35442020-02-04 12:16:38 -080066 if (working_buffer_.size() < sector_size_bytes) {
David Rogers2e9e0c82020-02-13 15:06:06 -080067 ERR("KVS init failed: working_buffer_ (%zu bytes) is smaller than sector "
68 "size (%zu bytes)",
David Rogersf0a35442020-02-04 12:16:38 -080069 working_buffer_.size(),
70 sector_size_bytes);
71 return Status::INVALID_ARGUMENT;
72 }
73
Keir Mierle8c352dc2020-02-02 13:58:19 -080074 DBG("First pass: Read all entries from all sectors");
Wyatt Hepler2c7eca02020-02-18 16:01:42 -080075 Address sector_address = 0;
Keir Mierle8c352dc2020-02-02 13:58:19 -080076
Wyatt Heplerd2298282020-02-20 17:12:45 -080077 sectors_.assign(partition_.sector_count(),
78 SectorDescriptor(sector_size_bytes));
79
Wyatt Hepler2c7eca02020-02-18 16:01:42 -080080 for (SectorDescriptor& sector : sectors_) {
81 // Reset the sector's valid and writable byte counts. These will be updated
82 // after reading each entry.
Keir Mierle8c352dc2020-02-02 13:58:19 -080083 Address entry_address = sector_address;
84
Wyatt Hepler2c7eca02020-02-18 16:01:42 -080085 for (int num_entries_in_sector = 0; true; num_entries_in_sector++) {
86 DBG("Load entry: sector=%" PRIx32 ", entry#=%d, address=%" PRIx32,
87 sector_address,
Keir Mierle8c352dc2020-02-02 13:58:19 -080088 num_entries_in_sector,
Wyatt Hepler2c7eca02020-02-18 16:01:42 -080089 entry_address);
Keir Mierle8c352dc2020-02-02 13:58:19 -080090
Wyatt Hepler2c7eca02020-02-18 16:01:42 -080091 if (!AddressInSector(sector, entry_address)) {
Keir Mierle8c352dc2020-02-02 13:58:19 -080092 DBG("Fell off end of sector; moving to the next sector");
93 break;
94 }
95
96 Address next_entry_address;
97 Status status = LoadEntry(entry_address, &next_entry_address);
98 if (status == Status::NOT_FOUND) {
99 DBG("Hit un-written data in sector; moving to the next sector");
100 break;
101 }
102 if (status == Status::DATA_LOSS) {
103 // It's not clear KVS can make a unilateral decision about what to do
104 // in corruption cases. It's an application decision, for which we
105 // should offer some configurability. For now, entirely bail out of
106 // loading and give up.
107 //
108 // Later, scan for remaining valid keys; since it's entirely possible
109 // that there is a duplicate of the key elsewhere and everything is
110 // fine. Later, we can wipe and maybe recover the sector.
111 //
112 // TODO: Implement rest-of-sector scanning for valid entries.
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800113 ERR("KVS init failed: data loss detected in sector %u at address %zu",
114 SectorIndex(&sector),
115 size_t(entry_address));
Keir Mierle8c352dc2020-02-02 13:58:19 -0800116 return Status::DATA_LOSS;
117 }
118 TRY(status);
119
120 // Entry loaded successfully; so get ready to load the next one.
121 entry_address = next_entry_address;
122
123 // Update of the number of writable bytes in this sector.
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800124 sector.set_writable_bytes(sector_size_bytes -
125 (entry_address - sector_address));
Keir Mierle8c352dc2020-02-02 13:58:19 -0800126 }
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800127
128 sector_address += sector_size_bytes;
Keir Mierle8c352dc2020-02-02 13:58:19 -0800129 }
130
131 DBG("Second pass: Count valid bytes in each sector");
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800132 const KeyDescriptor* newest_key = nullptr;
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800133
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 Heplerd2298282020-02-20 17:12:45 -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
Wyatt Heplerd2298282020-02-20 17:12:45 -0800529 // Do the valid bytes accounting for the sector the entry was relocated from.
Wyatt Heplere541e072020-02-14 09:10:53 -0800530 old_sector->RemoveValidBytes(entry.size());
David Rogersdf025cd2020-02-06 17:05:34 -0800531
532 return Status::OK;
David Rogersa12786b2020-01-31 16:02:33 -0800533}
534
David Rogers8db5a722020-02-03 18:28:34 -0800535// Find either an existing sector with enough space that is not the sector to
536// skip, or an empty sector. Maintains the invariant that there is always at
537// least 1 empty sector unless set to bypass the rule.
Wyatt Hepler5a33d8c2020-02-06 09:32:58 -0800538Status KeyValueStore::FindSectorWithSpace(
539 SectorDescriptor** found_sector,
540 size_t size,
541 const SectorDescriptor* sector_to_skip,
542 bool bypass_empty_sector_rule) {
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800543 SectorDescriptor* first_empty_sector = nullptr;
544 bool at_least_two_empty_sectors = bypass_empty_sector_rule;
545
546 DBG("Find sector with %zu bytes available, starting with sector %u",
547 size,
548 SectorIndex(last_new_sector_));
549 if (sector_to_skip != nullptr) {
550 DBG(" Skip sector %u", SectorIndex(sector_to_skip));
551 }
552 if (bypass_empty_sector_rule) {
553 DBG(" Bypassing empty sector rule");
554 }
555
David Rogers8ce55cd2020-02-04 19:41:48 -0800556 // The last_new_sector_ is the sector that was last selected as the "new empty
557 // sector" to write to. This last new sector is used as the starting point for
558 // the next "find a new empty sector to write to" operation. By using the last
559 // new sector as the start point we will cycle which empty sector is selected
560 // next, spreading the wear across all the empty sectors and get a wear
561 // leveling benefit, rather than putting more wear on the lower number
562 // sectors.
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800563 SectorDescriptor* sector = last_new_sector_;
David Rogers67f4b6c2020-02-06 16:17:09 -0800564
David Rogers8ce55cd2020-02-04 19:41:48 -0800565 // Look for a partial sector to use with enough space. Immediately use the
566 // first one of those that is found. While scanning for a partial sector, keep
567 // track of the first empty sector and if a second sector was seen.
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800568 for (size_t j = 0; j < sectors_.size(); j++) {
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800569 sector += 1;
570 if (sector == sectors_.end()) {
571 sector = sectors_.begin();
572 }
Keir Mierle8c352dc2020-02-02 13:58:19 -0800573
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800574 if (sector_to_skip == sector) {
David Rogers8db5a722020-02-03 18:28:34 -0800575 continue;
576 }
577
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800578 const size_t sector_size_bytes = partition_.sector_size_bytes();
579 if (!sector->Empty(sector_size_bytes) && sector->HasSpace(size)) {
580 *found_sector = sector;
David Rogers8ce55cd2020-02-04 19:41:48 -0800581 return Status::OK;
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800582 }
583
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800584 if (sector->Empty(sector_size_bytes)) {
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800585 if (first_empty_sector == nullptr) {
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800586 first_empty_sector = sector;
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800587 } else {
588 at_least_two_empty_sectors = true;
Wyatt Hepler2ad60672020-01-21 08:00:16 -0800589 }
Wyatt Heplerb7609542020-01-24 10:29:54 -0800590 }
591 }
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800592
David Rogers8ce55cd2020-02-04 19:41:48 -0800593 // If the scan for a partial sector does not find a suitable sector, use the
594 // first empty sector that was found. Normally it is required to keep 1 empty
595 // sector after the sector found here, but that rule can be bypassed in
596 // special circumstances (such as during garbage collection).
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800597 if (at_least_two_empty_sectors) {
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800598 DBG(" Found a usable empty sector; returning the first found (%u)",
David Rogers8ce55cd2020-02-04 19:41:48 -0800599 SectorIndex(first_empty_sector));
600 last_new_sector_ = first_empty_sector;
601 *found_sector = first_empty_sector;
602 return Status::OK;
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800603 }
David Rogers8ce55cd2020-02-04 19:41:48 -0800604
605 // No sector was found.
David Rogers67f4b6c2020-02-06 16:17:09 -0800606 DBG(" Unable to find a usable sector");
David Rogers8ce55cd2020-02-04 19:41:48 -0800607 *found_sector = nullptr;
608 return Status::RESOURCE_EXHAUSTED;
Wyatt Heplerb7609542020-01-24 10:29:54 -0800609}
610
David Rogers2761aeb2020-01-31 17:09:00 -0800611Status KeyValueStore::FindOrRecoverSectorWithSpace(SectorDescriptor** sector,
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800612 size_t size) {
David Rogers8ce55cd2020-02-04 19:41:48 -0800613 Status result = FindSectorWithSpace(sector, size);
Wyatt Hepler2d401692020-02-13 16:01:23 -0800614 if (result == Status::RESOURCE_EXHAUSTED && options_.partial_gc_on_write) {
David Rogers1541d612020-02-06 23:47:02 -0800615 // Garbage collect and then try again to find the best sector.
616 TRY(GarbageCollectOneSector());
617 return FindSectorWithSpace(sector, size);
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800618 }
David Rogers8ce55cd2020-02-04 19:41:48 -0800619 return result;
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800620}
621
David Rogers2761aeb2020-01-31 17:09:00 -0800622KeyValueStore::SectorDescriptor* KeyValueStore::FindSectorToGarbageCollect() {
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800623 const size_t sector_size_bytes = partition_.sector_size_bytes();
David Rogers2761aeb2020-01-31 17:09:00 -0800624 SectorDescriptor* sector_candidate = nullptr;
David Rogersa12786b2020-01-31 16:02:33 -0800625 size_t candidate_bytes = 0;
626
627 // Step 1: Try to find a sectors with stale keys and no valid keys (no
628 // relocation needed). If any such sectors are found, use the sector with the
629 // most reclaimable bytes.
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800630 for (auto& sector : sectors_) {
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800631 if ((sector.valid_bytes() == 0) &&
632 (sector.RecoverableBytes(sector_size_bytes) > candidate_bytes)) {
David Rogersa12786b2020-01-31 16:02:33 -0800633 sector_candidate = &sector;
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800634 candidate_bytes = sector.RecoverableBytes(sector_size_bytes);
David Rogersa12786b2020-01-31 16:02:33 -0800635 }
636 }
637
638 // Step 2: If step 1 yields no sectors, just find the sector with the most
639 // reclaimable bytes.
640 if (sector_candidate == nullptr) {
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800641 for (auto& sector : sectors_) {
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800642 if (sector.RecoverableBytes(sector_size_bytes) > candidate_bytes) {
David Rogersa12786b2020-01-31 16:02:33 -0800643 sector_candidate = &sector;
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800644 candidate_bytes = sector.RecoverableBytes(sector_size_bytes);
David Rogersa12786b2020-01-31 16:02:33 -0800645 }
646 }
647 }
648
David Rogers5981f312020-02-13 13:33:56 -0800649 if (sector_candidate != nullptr) {
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800650 DBG("Found sector %u to Garbage Collect, %zu recoverable bytes",
David Rogers5981f312020-02-13 13:33:56 -0800651 SectorIndex(sector_candidate),
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800652 sector_candidate->RecoverableBytes(sector_size_bytes));
David Rogers5981f312020-02-13 13:33:56 -0800653 } else {
654 DBG("Unable to find sector to garbage collect!");
655 }
David Rogersa12786b2020-01-31 16:02:33 -0800656 return sector_candidate;
657}
658
David Rogers1541d612020-02-06 23:47:02 -0800659Status KeyValueStore::GarbageCollectOneSector() {
David Rogers67f4b6c2020-02-06 16:17:09 -0800660 DBG("Garbage Collect a single sector");
661
David Rogersa12786b2020-01-31 16:02:33 -0800662 // Step 1: Find the sector to garbage collect
David Rogers2761aeb2020-01-31 17:09:00 -0800663 SectorDescriptor* sector_to_gc = FindSectorToGarbageCollect();
David Rogers3464d0a2020-02-07 11:45:46 -0800664 LogSectors();
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800665
David Rogersa12786b2020-01-31 16:02:33 -0800666 if (sector_to_gc == nullptr) {
667 return Status::RESOURCE_EXHAUSTED;
668 }
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800669
David Rogersa12786b2020-01-31 16:02:33 -0800670 // Step 2: Move any valid entries in the GC sector to other sectors
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800671 if (sector_to_gc->valid_bytes() != 0) {
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800672 for (auto& descriptor : key_descriptors_) {
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800673 if (AddressInSector(*sector_to_gc, descriptor.address())) {
David Rogers67f4b6c2020-02-06 16:17:09 -0800674 DBG(" Relocate entry");
David Rogers2761aeb2020-01-31 17:09:00 -0800675 TRY(RelocateEntry(descriptor));
David Rogersa12786b2020-01-31 16:02:33 -0800676 }
Wyatt Heplerb7609542020-01-24 10:29:54 -0800677 }
678 }
Wyatt Heplerb7609542020-01-24 10:29:54 -0800679
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800680 if (sector_to_gc->valid_bytes() != 0) {
David Rogers67f4b6c2020-02-06 16:17:09 -0800681 ERR(" Failed to relocate valid entries from sector being garbage "
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800682 "collected, %zu valid bytes remain",
683 sector_to_gc->valid_bytes());
Wyatt Heplerb7609542020-01-24 10:29:54 -0800684 return Status::INTERNAL;
685 }
686
David Rogersa12786b2020-01-31 16:02:33 -0800687 // Step 3: Reinitialize the sector
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800688 sector_to_gc->set_writable_bytes(0);
David Rogersa12786b2020-01-31 16:02:33 -0800689 TRY(partition_.Erase(SectorBaseAddress(sector_to_gc), 1));
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800690 sector_to_gc->set_writable_bytes(partition_.sector_size_bytes());
Wyatt Heplerb7609542020-01-24 10:29:54 -0800691
David Rogers67f4b6c2020-02-06 16:17:09 -0800692 DBG(" Garbage Collect complete");
David Rogers50185ad2020-02-07 00:02:46 -0800693 LogSectors();
David Rogersa12786b2020-01-31 16:02:33 -0800694 return Status::OK;
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800695}
696
David Rogers2761aeb2020-01-31 17:09:00 -0800697Status KeyValueStore::AppendEntry(SectorDescriptor* sector,
698 KeyDescriptor* key_descriptor,
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800699 string_view key,
Wyatt Hepler5a33d8c2020-02-06 09:32:58 -0800700 span<const byte> value,
701 KeyDescriptor::State new_state) {
Wyatt Heplere541e072020-02-14 09:10:53 -0800702 const Address address = NextWritableAddress(sector);
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800703 Entry entry = CreateEntry(address, key, value, new_state);
Wyatt Heplere541e072020-02-14 09:10:53 -0800704
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800705 DBG("Appending %zu B entry with transaction ID %" PRIu32 " to address %#zx",
Wyatt Heplere541e072020-02-14 09:10:53 -0800706 entry.size(),
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800707 entry.transaction_id(),
708 size_t(address));
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800709
David Rogers6592d292020-02-14 14:19:26 -0800710 StatusWithSize result = entry.Write(key, value);
711 // Remove any bytes that were written, even if the write was not successful.
712 sector->RemoveWritableBytes(result.size());
713
714 if (!result.ok()) {
715 // TODO: add testing coverage for this once flash errors are supported in
716 // tests.
717 ERR("Failed to write %zu bytes. %zu actually written",
718 entry.size(),
719 result.size());
720 return result.status();
721 }
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800722
723 if (options_.verify_on_write) {
Wyatt Heplere541e072020-02-14 09:10:53 -0800724 TRY(entry.VerifyChecksumInFlash(entry_header_format_.checksum));
Wyatt Heplerb7609542020-01-24 10:29:54 -0800725 }
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800726
David Rogers6592d292020-02-14 14:19:26 -0800727 // Entry was written successfully, update the key descriptor and the sector
728 // descriptor to reflect the new entry.
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800729 entry.UpdateDescriptor(key_descriptor);
David Rogers6592d292020-02-14 14:19:26 -0800730 sector->AddValidBytes(result.size());
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800731 return Status::OK;
Wyatt Heplerb7609542020-01-24 10:29:54 -0800732}
733
Wyatt Heplerbdd8e5a2020-02-20 19:27:26 -0800734KeyValueStore::Entry KeyValueStore::CreateEntry(Address address,
735 std::string_view key,
736 span<const byte> value,
737 KeyDescriptor::State state) {
Wyatt Heplerd2298282020-02-20 17:12:45 -0800738 last_transaction_id_ += 1;
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800739
740 if (state == KeyDescriptor::kDeleted) {
741 return Entry::Tombstone(partition_,
742 address,
743 entry_header_format_.magic,
744 entry_header_format_.checksum,
745 key,
746 partition_.alignment_bytes(),
Wyatt Heplerd2298282020-02-20 17:12:45 -0800747 last_transaction_id_);
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800748 }
749 return Entry::Valid(partition_,
750 address,
751 entry_header_format_.magic,
752 entry_header_format_.checksum,
753 key,
754 value,
755 partition_.alignment_bytes(),
Wyatt Heplerd2298282020-02-20 17:12:45 -0800756 last_transaction_id_);
757}
758
759void KeyValueStore::Reset() {
760 initialized_ = false;
761 key_descriptors_.clear();
762 last_new_sector_ = nullptr;
763 last_transaction_id_ = 0;
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800764}
765
Keir Mierle8c352dc2020-02-02 13:58:19 -0800766void KeyValueStore::LogDebugInfo() {
Keir Mierle8c352dc2020-02-02 13:58:19 -0800767 const size_t sector_size_bytes = partition_.sector_size_bytes();
768 DBG("====================== KEY VALUE STORE DUMP =========================");
769 DBG(" ");
770 DBG("Flash partition:");
Wyatt Heplerad0a7932020-02-06 08:20:38 -0800771 DBG(" Sector count = %zu", partition_.sector_count());
Wyatt Hepler38ce30f2020-02-19 11:48:31 -0800772 DBG(" Sector max count = %zu", sectors_.max_size());
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800773 DBG(" Sectors in use = %zu", sectors_.size());
Keir Mierle8c352dc2020-02-02 13:58:19 -0800774 DBG(" Sector size = %zu", sector_size_bytes);
775 DBG(" Total size = %zu", partition_.size_bytes());
776 DBG(" Alignment = %zu", partition_.alignment_bytes());
777 DBG(" ");
778 DBG("Key descriptors:");
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800779 DBG(" Entry count = %zu", key_descriptors_.size());
Wyatt Hepler38ce30f2020-02-19 11:48:31 -0800780 DBG(" Max entry count = %zu", key_descriptors_.max_size());
Keir Mierle8c352dc2020-02-02 13:58:19 -0800781 DBG(" ");
782 DBG(" # hash version address address (hex)");
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800783 for (size_t i = 0; i < key_descriptors_.size(); ++i) {
784 const KeyDescriptor& kd = key_descriptors_[i];
Keir Mierle8c352dc2020-02-02 13:58:19 -0800785 DBG(" |%3zu: | %8zx |%8zu | %8zu | %8zx",
786 i,
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800787 size_t(kd.hash()),
788 size_t(kd.transaction_id()),
789 size_t(kd.address()),
790 size_t(kd.address()));
Keir Mierle8c352dc2020-02-02 13:58:19 -0800791 }
792 DBG(" ");
793
794 DBG("Sector descriptors:");
795 DBG(" # tail free valid has_space");
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800796 for (size_t sector_id = 0; sector_id < sectors_.size(); ++sector_id) {
797 const SectorDescriptor& sd = sectors_[sector_id];
Keir Mierle8c352dc2020-02-02 13:58:19 -0800798 DBG(" |%3zu: | %8zu |%8zu | %s",
799 sector_id,
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800800 size_t(sd.writable_bytes()),
801 sd.valid_bytes(),
802 sd.writable_bytes() ? "YES" : "");
Keir Mierle8c352dc2020-02-02 13:58:19 -0800803 }
804 DBG(" ");
805
806 // TODO: This should stop logging after some threshold.
807 // size_t dumped_bytes = 0;
808 DBG("Sector raw data:");
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800809 for (size_t sector_id = 0; sector_id < sectors_.size(); ++sector_id) {
Keir Mierle8c352dc2020-02-02 13:58:19 -0800810 // Read sector data. Yes, this will blow the stack on embedded.
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800811 std::array<byte, 500> raw_sector_data; // TODO!!!
Keir Mierle8c352dc2020-02-02 13:58:19 -0800812 StatusWithSize sws =
813 partition_.Read(sector_id * sector_size_bytes, raw_sector_data);
814 DBG("Read: %zu bytes", sws.size());
815
816 DBG(" base addr offs 0 1 2 3 4 5 6 7");
817 for (size_t i = 0; i < sector_size_bytes; i += 8) {
818 DBG(" %3zu %8zx %5zu | %02x %02x %02x %02x %02x %02x %02x %02x",
819 sector_id,
820 (sector_id * sector_size_bytes) + i,
821 i,
822 static_cast<unsigned int>(raw_sector_data[i + 0]),
823 static_cast<unsigned int>(raw_sector_data[i + 1]),
824 static_cast<unsigned int>(raw_sector_data[i + 2]),
825 static_cast<unsigned int>(raw_sector_data[i + 3]),
826 static_cast<unsigned int>(raw_sector_data[i + 4]),
827 static_cast<unsigned int>(raw_sector_data[i + 5]),
828 static_cast<unsigned int>(raw_sector_data[i + 6]),
829 static_cast<unsigned int>(raw_sector_data[i + 7]));
830
831 // TODO: Fix exit condition.
832 if (i > 128) {
833 break;
834 }
835 }
836 DBG(" ");
837 }
838
839 DBG("////////////////////// KEY VALUE STORE DUMP END /////////////////////");
840}
841
David Rogerscf680ab2020-02-12 23:28:32 -0800842void KeyValueStore::LogSectors() const {
843 DBG("Sector descriptors: count %zu", sectors_.size());
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800844 for (auto& sector : sectors_) {
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800845 DBG(" - Sector %u: valid %zu, recoverable %zu, free %zu",
David Rogers50185ad2020-02-07 00:02:46 -0800846 SectorIndex(&sector),
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800847 sector.valid_bytes(),
848 sector.RecoverableBytes(partition_.sector_size_bytes()),
849 sector.writable_bytes());
David Rogers50185ad2020-02-07 00:02:46 -0800850 }
851}
852
David Rogerscf680ab2020-02-12 23:28:32 -0800853void KeyValueStore::LogKeyDescriptor() const {
854 DBG("Key descriptors: count %zu", key_descriptors_.size());
855 for (auto& key : key_descriptors_) {
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800856 DBG(" - Key: %s, hash %#zx, transaction ID %zu, address %#zx",
David Rogerscf680ab2020-02-12 23:28:32 -0800857 key.deleted() ? "Deleted" : "Valid",
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800858 static_cast<size_t>(key.hash()),
859 static_cast<size_t>(key.transaction_id()),
860 static_cast<size_t>(key.address()));
David Rogerscf680ab2020-02-12 23:28:32 -0800861 }
862}
863
Wyatt Hepler2ad60672020-01-21 08:00:16 -0800864} // namespace pw::kvs