blob: 306ad826c79badb2e15ce03991f6dc4632a479d8 [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 Hepler88adfe82020-02-20 19:33:27 -080042 const EntryFormat& format,
Wyatt Heplerad0a7932020-02-06 08:20:38 -080043 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) {
Wyatt Heplerce7b8df2020-02-21 10:38:39 -080067 ERR("KVS init failed: working_buffer_ (%zu B) is smaller than sector size "
68 "(%zu B)",
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
Alexei Frolovd4adf912020-02-21 13:29:15 -080080 size_t total_corrupt_bytes = 0;
81 int corrupt_entries = 0;
82
Wyatt Hepler2c7eca02020-02-18 16:01:42 -080083 for (SectorDescriptor& sector : sectors_) {
Keir Mierle8c352dc2020-02-02 13:58:19 -080084 Address entry_address = sector_address;
85
Alexei Frolovd4adf912020-02-21 13:29:15 -080086 size_t sector_corrupt_bytes = 0;
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) {
Alexei Frolovd4adf912020-02-21 13:29:15 -0800106 // The entry could not be read, indicating data corruption within the
107 // sector. Try to scan the remainder of the sector for other entries.
108 ERR("KVS init: data loss detected in sector %u at address %zu",
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800109 SectorIndex(&sector),
110 size_t(entry_address));
Alexei Frolovd4adf912020-02-21 13:29:15 -0800111
112 corrupt_entries++;
113
114 status = ScanForEntry(sector,
115 entry_address + Entry::kMinAlignmentBytes,
116 &next_entry_address);
117 if (status == Status::NOT_FOUND) {
118 // No further entries in this sector. Mark the remaining bytes in the
119 // sector as corrupt (since we can't reliably know the size of the
120 // corrupt entry).
121 sector_corrupt_bytes +=
122 sector_size_bytes - (entry_address - sector_address);
123 break;
124 }
125
126 if (!status.ok()) {
127 ERR("Unexpected error in KVS initialization: %s", status.str());
128 return Status::UNKNOWN;
129 }
130
131 sector_corrupt_bytes += next_entry_address - entry_address;
132 } else if (!status.ok()) {
133 ERR("Unexpected error in KVS initialization: %s", status.str());
134 return Status::UNKNOWN;
Keir Mierle8c352dc2020-02-02 13:58:19 -0800135 }
Keir Mierle8c352dc2020-02-02 13:58:19 -0800136
137 // Entry loaded successfully; so get ready to load the next one.
138 entry_address = next_entry_address;
139
140 // Update of the number of writable bytes in this sector.
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800141 sector.set_writable_bytes(sector_size_bytes -
142 (entry_address - sector_address));
Keir Mierle8c352dc2020-02-02 13:58:19 -0800143 }
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800144
Alexei Frolovd4adf912020-02-21 13:29:15 -0800145 if (sector_corrupt_bytes > 0) {
146 // If the sector contains corrupt data, prevent any further entries from
147 // being written to it by indicating that it has no space. This should
148 // also make it a decent GC candidate. Valid keys in the sector are still
149 // readable as normal.
150 sector.set_writable_bytes(0);
151
152 WRN("Sector %u contains %zuB of corrupt data",
153 SectorIndex(&sector),
154 sector_corrupt_bytes);
155 }
156
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800157 sector_address += sector_size_bytes;
Alexei Frolovd4adf912020-02-21 13:29:15 -0800158 total_corrupt_bytes += sector_corrupt_bytes;
Keir Mierle8c352dc2020-02-02 13:58:19 -0800159 }
160
161 DBG("Second pass: Count valid bytes in each sector");
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800162 const KeyDescriptor* newest_key = nullptr;
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800163
Keir Mierle8c352dc2020-02-02 13:58:19 -0800164 // For every valid key, increment the valid bytes for that sector.
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800165 for (KeyDescriptor& key_descriptor : key_descriptors_) {
Wyatt Heplere541e072020-02-14 09:10:53 -0800166 Entry entry;
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800167 TRY(Entry::Read(partition_, key_descriptor.address(), &entry));
168 SectorFromKey(key_descriptor)->AddValidBytes(entry.size());
169
170 if (key_descriptor.IsNewerThan(last_transaction_id_)) {
171 last_transaction_id_ = key_descriptor.transaction_id();
172 newest_key = &key_descriptor;
173 }
Keir Mierle8c352dc2020-02-02 13:58:19 -0800174 }
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800175
176 if (newest_key == nullptr) {
177 last_new_sector_ = sectors_.begin();
178 } else {
179 last_new_sector_ = SectorFromKey(newest_key);
180 }
181
Wyatt Hepler729f28c2020-02-05 09:46:00 -0800182 initialized_ = true;
David Rogers2e9e0c82020-02-13 15:06:06 -0800183
Armando Montanez5464d5f2020-02-20 10:12:20 -0800184 INF("KeyValueStore init complete: active keys %zu, deleted keys %zu, sectors "
David Rogers2e9e0c82020-02-13 15:06:06 -0800185 "%zu, logical sector size %zu bytes",
186 size(),
187 (key_descriptors_.size() - size()),
188 sectors_.size(),
189 partition_.sector_size_bytes());
190
Alexei Frolovd4adf912020-02-21 13:29:15 -0800191 if (total_corrupt_bytes > 0) {
192 WRN("Found %zu corrupt bytes and %d corrupt entries during init process; "
193 "some keys may be missing",
194 total_corrupt_bytes,
195 corrupt_entries);
196 return Status::DATA_LOSS;
197 }
198
Keir Mierle8c352dc2020-02-02 13:58:19 -0800199 return Status::OK;
200}
201
Alexei Frolov9e235832020-02-24 12:44:45 -0800202KeyValueStore::StorageStats KeyValueStore::GetStorageStats() const {
203 StorageStats stats{0, 0, 0};
204 const size_t sector_size = partition_.sector_size_bytes();
205 bool found_empty_sector = false;
206
207 for (const SectorDescriptor& sector : sectors_) {
208 stats.in_use_bytes += sector.valid_bytes();
209 stats.reclaimable_bytes += sector.RecoverableBytes(sector_size);
210
211 if (!found_empty_sector && sector.Empty(sector_size)) {
212 // The KVS tries to always keep an empty sector for GC, so don't count
213 // the first empty sector seen as writable space. However, a free sector
214 // cannot always be assumed to exist; if a GC operation fails, all sectors
215 // may be partially written, in which case the space reported might be
216 // inaccurate.
217 found_empty_sector = true;
218 continue;
219 }
220
221 stats.writable_bytes += sector.writable_bytes();
222 }
223
224 return stats;
225}
226
Keir Mierle8c352dc2020-02-02 13:58:19 -0800227Status KeyValueStore::LoadEntry(Address entry_address,
228 Address* next_entry_address) {
Wyatt Heplere541e072020-02-14 09:10:53 -0800229 Entry entry;
230 TRY(Entry::Read(partition_, entry_address, &entry));
Keir Mierle8c352dc2020-02-02 13:58:19 -0800231
232 // TODO: Handle multiple magics for formats that have changed.
Wyatt Heplere541e072020-02-14 09:10:53 -0800233 if (entry.magic() != entry_header_format_.magic) {
Keir Mierle8c352dc2020-02-02 13:58:19 -0800234 // TODO: It may be cleaner to have some logging helpers for these cases.
Wyatt Heplere541e072020-02-14 09:10:53 -0800235 ERR("Found corrupt magic: %zx; expecting %zx; at address %zx",
236 size_t(entry.magic()),
Keir Mierle8c352dc2020-02-02 13:58:19 -0800237 size_t(entry_header_format_.magic),
238 size_t(entry_address));
239 return Status::DATA_LOSS;
240 }
241
242 // Read the key from flash & validate the entry (which reads the value).
Wyatt Heplera00d1ef2020-02-14 14:31:26 -0800243 Entry::KeyBuffer key_buffer;
Wyatt Heplere541e072020-02-14 09:10:53 -0800244 TRY_ASSIGN(size_t key_length, entry.ReadKey(key_buffer));
245 const string_view key(key_buffer.data(), key_length);
Wyatt Heplerbab0e202020-02-04 07:40:08 -0800246
Wyatt Heplere541e072020-02-14 09:10:53 -0800247 TRY(entry.VerifyChecksumInFlash(entry_header_format_.checksum));
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800248 TRY(AppendNewOrOverwriteStaleExistingDescriptor(entry.descriptor(key)));
Keir Mierle8c352dc2020-02-02 13:58:19 -0800249
Wyatt Heplere541e072020-02-14 09:10:53 -0800250 *next_entry_address = entry.next_address();
Keir Mierle8c352dc2020-02-02 13:58:19 -0800251 return Status::OK;
252}
253
Alexei Frolovd4adf912020-02-21 13:29:15 -0800254// Scans flash memory within a sector to find a KVS entry magic.
255// TODO(frolv): This needs to be unit tested!
256Status KeyValueStore::ScanForEntry(const SectorDescriptor& sector,
257 Address start_address,
258 Address* next_entry_address) {
259 DBG("Scanning sector %u for entries starting from address %zx",
260 SectorIndex(&sector),
261 size_t(start_address));
262
263 // Entries must start at addresses which are aligned on a multiple of
264 // Entry::kMinAlignmentBytes. However, that multiple can vary between entries.
265 // When scanning, we don't have an entry to tell us what the current alignment
266 // is, so the minimum alignment is used to be exhaustive.
267 for (Address address = AlignUp(start_address, Entry::kMinAlignmentBytes);
268 AddressInSector(sector, address);
269 address += Entry::kMinAlignmentBytes) {
270 // TODO: Handle multiple magics for formats that have changed.
271 uint32_t magic;
272 TRY(partition_.Read(address, as_writable_bytes(span(&magic, 1))));
273 if (magic == entry_header_format_.magic) {
274 DBG("Found entry magic at address %zx", size_t(address));
275 *next_entry_address = address;
276 return Status::OK;
277 }
278 }
279
280 return Status::NOT_FOUND;
281}
282
Keir Mierle8c352dc2020-02-02 13:58:19 -0800283// TODO: This method is the trigger of the O(valid_entries * all_entries) time
284// complexity for reading. At some cost to memory, this could be optimized by
285// using a hash table instead of scanning, but in practice this should be fine
286// for a small number of keys
287Status KeyValueStore::AppendNewOrOverwriteStaleExistingDescriptor(
288 const KeyDescriptor& key_descriptor) {
289 // With the new key descriptor, either add it to the descriptor table or
290 // overwrite an existing entry with an older version of the key.
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800291 KeyDescriptor* existing_descriptor = FindDescriptor(key_descriptor.hash());
Keir Mierle8c352dc2020-02-02 13:58:19 -0800292
Wyatt Hepler5406a672020-02-18 15:42:38 -0800293 // Write a new entry.
294 if (existing_descriptor == nullptr) {
295 if (key_descriptors_.full()) {
296 return Status::RESOURCE_EXHAUSTED;
297 }
298 key_descriptors_.push_back(key_descriptor);
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800299 } else if (key_descriptor.IsNewerThan(
300 existing_descriptor->transaction_id())) {
Wyatt Hepler5406a672020-02-18 15:42:38 -0800301 // Existing entry is old; replace the existing entry with the new one.
302 *existing_descriptor = key_descriptor;
303 } else {
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800304 // Otherwise, check if the entries have a duplicate transaction ID, which is
305 // not valid.
306 if (existing_descriptor->transaction_id() ==
307 key_descriptor.transaction_id()) {
308 ERR("Data loss: Duplicated old(=%zu) and new(=%zu) transaction ID",
309 size_t(existing_descriptor->transaction_id()),
310 size_t(key_descriptor.transaction_id()));
Wyatt Hepler5406a672020-02-18 15:42:38 -0800311 return Status::DATA_LOSS;
312 }
313 DBG("Found stale entry when appending; ignoring");
Keir Mierle8c352dc2020-02-02 13:58:19 -0800314 }
Keir Mierle8c352dc2020-02-02 13:58:19 -0800315 return Status::OK;
316}
317
Keir Mierle8c352dc2020-02-02 13:58:19 -0800318KeyValueStore::KeyDescriptor* KeyValueStore::FindDescriptor(uint32_t hash) {
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800319 for (KeyDescriptor& key_descriptor : key_descriptors_) {
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800320 if (key_descriptor.hash() == hash) {
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800321 return &key_descriptor;
Keir Mierle8c352dc2020-02-02 13:58:19 -0800322 }
323 }
324 return nullptr;
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800325}
326
327StatusWithSize KeyValueStore::Get(string_view key,
Wyatt Hepler5f6efc02020-02-18 16:54:31 -0800328 span<byte> value_buffer,
329 size_t offset_bytes) const {
Wyatt Hepler50f70772020-02-13 11:25:10 -0800330 TRY_WITH_SIZE(CheckOperation(key));
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800331
David Rogers2761aeb2020-01-31 17:09:00 -0800332 const KeyDescriptor* key_descriptor;
Wyatt Hepler2d401692020-02-13 16:01:23 -0800333 TRY_WITH_SIZE(FindExistingKeyDescriptor(key, &key_descriptor));
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800334
Wyatt Heplere541e072020-02-14 09:10:53 -0800335 Entry entry;
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800336 TRY_WITH_SIZE(Entry::Read(partition_, key_descriptor->address(), &entry));
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800337
Wyatt Hepler5f6efc02020-02-18 16:54:31 -0800338 StatusWithSize result = entry.ReadValue(value_buffer, offset_bytes);
339 if (result.ok() && options_.verify_on_read && offset_bytes == 0u) {
Wyatt Heplerce7b8df2020-02-21 10:38:39 -0800340 Status verify_result = entry.VerifyChecksum(
341 entry_header_format_.checksum, key, value_buffer.first(result.size()));
David Rogerscf680ab2020-02-12 23:28:32 -0800342 if (!verify_result.ok()) {
Wyatt Heplerce7b8df2020-02-21 10:38:39 -0800343 std::memset(value_buffer.data(), 0, result.size());
Wyatt Hepler50f70772020-02-13 11:25:10 -0800344 return StatusWithSize(verify_result);
David Rogerscf680ab2020-02-12 23:28:32 -0800345 }
346
347 return StatusWithSize(verify_result, result.size());
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800348 }
349 return result;
350}
351
352Status KeyValueStore::Put(string_view key, span<const byte> value) {
Keir Mierle8c352dc2020-02-02 13:58:19 -0800353 DBG("Writing key/value; key length=%zu, value length=%zu",
354 key.size(),
355 value.size());
Wyatt Hepler729f28c2020-02-05 09:46:00 -0800356
357 TRY(CheckOperation(key));
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800358
Wyatt Hepler5406a672020-02-18 15:42:38 -0800359 if (Entry::size(partition_, key, value) > partition_.sector_size_bytes()) {
360 DBG("%zu B value with %zu B key cannot fit in one sector",
361 value.size(),
362 key.size());
363 return Status::INVALID_ARGUMENT;
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800364 }
365
David Rogers2761aeb2020-01-31 17:09:00 -0800366 KeyDescriptor* key_descriptor;
Wyatt Hepler2d401692020-02-13 16:01:23 -0800367 Status status = FindKeyDescriptor(key, &key_descriptor);
368
369 if (status.ok()) {
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800370 DBG("Overwriting entry for key %#08" PRIx32 " in sector %u",
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800371 key_descriptor->hash(),
372 SectorIndex(SectorFromKey(key_descriptor)));
Wyatt Hepler5a33d8c2020-02-06 09:32:58 -0800373 return WriteEntryForExistingKey(
374 key_descriptor, KeyDescriptor::kValid, key, value);
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800375 }
David Rogers2761aeb2020-01-31 17:09:00 -0800376
Wyatt Hepler2d401692020-02-13 16:01:23 -0800377 if (status == Status::NOT_FOUND) {
378 return WriteEntryForNewKey(key, value);
379 }
380
381 return status;
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800382}
383
384Status KeyValueStore::Delete(string_view key) {
Wyatt Hepler729f28c2020-02-05 09:46:00 -0800385 TRY(CheckOperation(key));
386
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800387 KeyDescriptor* key_descriptor;
Wyatt Hepler2d401692020-02-13 16:01:23 -0800388 TRY(FindExistingKeyDescriptor(key, &key_descriptor));
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800389
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800390 DBG("Writing tombstone for key %#08" PRIx32 " in sector %u",
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800391 key_descriptor->hash(),
392 SectorIndex(SectorFromKey(key_descriptor)));
Wyatt Hepler5a33d8c2020-02-06 09:32:58 -0800393 return WriteEntryForExistingKey(
394 key_descriptor, KeyDescriptor::kDeleted, key, {});
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800395}
396
397KeyValueStore::iterator& KeyValueStore::iterator::operator++() {
398 // Skip to the next entry that is valid (not deleted).
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800399 while (++index_ < item_.kvs_.key_descriptors_.size() &&
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800400 descriptor().deleted()) {
401 }
402 return *this;
403}
404
405const KeyValueStore::Item& KeyValueStore::iterator::operator*() {
406 std::memset(item_.key_buffer_.data(), 0, item_.key_buffer_.size());
407
Wyatt Heplere541e072020-02-14 09:10:53 -0800408 Entry entry;
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800409 if (Entry::Read(item_.kvs_.partition_, descriptor().address(), &entry).ok()) {
Wyatt Heplere541e072020-02-14 09:10:53 -0800410 entry.ReadKey(item_.key_buffer_);
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800411 }
412
413 return item_;
414}
415
416KeyValueStore::iterator KeyValueStore::begin() const {
417 size_t i = 0;
418 // Skip over any deleted entries at the start of the descriptor list.
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800419 while (i < key_descriptors_.size() && key_descriptors_[i].deleted()) {
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800420 i += 1;
421 }
422 return iterator(*this, i);
423}
424
425// TODO(hepler): The valid entry count could be tracked in the KVS to avoid the
426// need for this for-loop.
427size_t KeyValueStore::size() const {
428 size_t valid_entries = 0;
429
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800430 for (const KeyDescriptor& key_descriptor : key_descriptors_) {
431 if (!key_descriptor.deleted()) {
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800432 valid_entries += 1;
433 }
434 }
435
436 return valid_entries;
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800437}
438
Wyatt Heplered163b02020-02-03 17:49:32 -0800439StatusWithSize KeyValueStore::ValueSize(std::string_view key) const {
Wyatt Hepler50f70772020-02-13 11:25:10 -0800440 TRY_WITH_SIZE(CheckOperation(key));
Wyatt Heplered163b02020-02-03 17:49:32 -0800441
442 const KeyDescriptor* key_descriptor;
Wyatt Hepler2d401692020-02-13 16:01:23 -0800443 TRY_WITH_SIZE(FindExistingKeyDescriptor(key, &key_descriptor));
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800444
Wyatt Heplere541e072020-02-14 09:10:53 -0800445 Entry entry;
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800446 TRY_WITH_SIZE(Entry::Read(partition_, key_descriptor->address(), &entry));
Wyatt Heplered163b02020-02-03 17:49:32 -0800447
Wyatt Heplere541e072020-02-14 09:10:53 -0800448 return StatusWithSize(entry.value_size());
Wyatt Heplered163b02020-02-03 17:49:32 -0800449}
450
Wyatt Hepler6e3a83b2020-02-04 07:36:45 -0800451Status KeyValueStore::FixedSizeGet(std::string_view key,
452 byte* value,
453 size_t size_bytes) const {
454 // Ensure that the size of the stored value matches the size of the type.
455 // Otherwise, report error. This check avoids potential memory corruption.
456 StatusWithSize result = ValueSize(key);
457 if (!result.ok()) {
458 return result.status();
Keir Mierle8c352dc2020-02-02 13:58:19 -0800459 }
Wyatt Hepler6e3a83b2020-02-04 07:36:45 -0800460 if (result.size() != size_bytes) {
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800461 DBG("Requested %zu B read, but value is %zu B", size_bytes, result.size());
Wyatt Hepler6e3a83b2020-02-04 07:36:45 -0800462 return Status::INVALID_ARGUMENT;
Wyatt Heplerbab0e202020-02-04 07:40:08 -0800463 }
Wyatt Hepler6e3a83b2020-02-04 07:36:45 -0800464 return Get(key, span(value, size_bytes)).status();
Keir Mierle8c352dc2020-02-02 13:58:19 -0800465}
466
Wyatt Hepler729f28c2020-02-05 09:46:00 -0800467Status KeyValueStore::CheckOperation(string_view key) const {
Wyatt Hepleracaacf92020-01-24 10:58:30 -0800468 if (InvalidKey(key)) {
Wyatt Heplerb7609542020-01-24 10:29:54 -0800469 return Status::INVALID_ARGUMENT;
470 }
Wyatt Heplerd2298282020-02-20 17:12:45 -0800471 if (!initialized()) {
Wyatt Heplerb7609542020-01-24 10:29:54 -0800472 return Status::FAILED_PRECONDITION;
473 }
Wyatt Heplerb7609542020-01-24 10:29:54 -0800474 return Status::OK;
475}
476
Wyatt Hepler2d401692020-02-13 16:01:23 -0800477// Searches for a KeyDescriptor that matches this key and sets *result to point
478// to it if one is found.
479//
480// OK: there is a matching descriptor and *result is set
481// NOT_FOUND: there is no descriptor that matches this key, but this key
482// has a unique hash (and could potentially be added to the KVS)
483// ALREADY_EXISTS: there is no descriptor that matches this key, but the
484// key's hash collides with the hash for an existing descriptor
485//
David Rogers2761aeb2020-01-31 17:09:00 -0800486Status KeyValueStore::FindKeyDescriptor(string_view key,
487 const KeyDescriptor** result) const {
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800488 const uint32_t hash = internal::Hash(key);
Wyatt Heplera00d1ef2020-02-14 14:31:26 -0800489 Entry::KeyBuffer key_buffer;
Wyatt Heplerb7609542020-01-24 10:29:54 -0800490
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800491 for (auto& descriptor : key_descriptors_) {
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800492 if (descriptor.hash() == hash) {
Wyatt Heplere541e072020-02-14 09:10:53 -0800493 TRY(Entry::ReadKey(
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800494 partition_, descriptor.address(), key.size(), key_buffer.data()));
Wyatt Heplerb7609542020-01-24 10:29:54 -0800495
Wyatt Heplere541e072020-02-14 09:10:53 -0800496 if (key == string_view(key_buffer.data(), key.size())) {
Wyatt Hepler5a33d8c2020-02-06 09:32:58 -0800497 DBG("Found match for key hash 0x%08" PRIx32, hash);
David Rogers2761aeb2020-01-31 17:09:00 -0800498 *result = &descriptor;
Wyatt Heplerb7609542020-01-24 10:29:54 -0800499 return Status::OK;
Wyatt Hepler2d401692020-02-13 16:01:23 -0800500 } else {
501 WRN("Found key hash collision for 0x%08" PRIx32, hash);
502 return Status::ALREADY_EXISTS;
Wyatt Heplerb7609542020-01-24 10:29:54 -0800503 }
Wyatt Heplerb7609542020-01-24 10:29:54 -0800504 }
505 }
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800506 return Status::NOT_FOUND;
507}
508
Wyatt Hepler2d401692020-02-13 16:01:23 -0800509// Searches for a KeyDescriptor that matches this key and sets *result to point
510// to it if one is found.
511//
512// OK: there is a matching descriptor and *result is set
513// NOT_FOUND: there is no descriptor that matches this key
514//
515Status KeyValueStore::FindExistingKeyDescriptor(
516 string_view key, const KeyDescriptor** result) const {
517 Status status = FindKeyDescriptor(key, result);
518
519 // If the key's hash collides with an existing key or if the key is deleted,
520 // treat it as if it is not in the KVS.
521 if (status == Status::ALREADY_EXISTS ||
522 (status.ok() && (*result)->deleted())) {
523 return Status::NOT_FOUND;
524 }
525 return status;
526}
527
David Rogers2761aeb2020-01-31 17:09:00 -0800528Status KeyValueStore::WriteEntryForExistingKey(KeyDescriptor* key_descriptor,
Wyatt Hepler5a33d8c2020-02-06 09:32:58 -0800529 KeyDescriptor::State new_state,
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800530 string_view key,
531 span<const byte> value) {
Wyatt Hepler5a33d8c2020-02-06 09:32:58 -0800532 // Find the original entry and sector to update the sector's valid_bytes.
Wyatt Hepler30a52152020-02-12 11:26:05 -0800533 Entry original_entry;
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800534 TRY(Entry::Read(partition_, key_descriptor->address(), &original_entry));
535 SectorDescriptor* old_sector = SectorFromKey(key_descriptor);
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800536
David Rogers2761aeb2020-01-31 17:09:00 -0800537 SectorDescriptor* sector;
Wyatt Hepler5406a672020-02-18 15:42:38 -0800538 TRY(FindOrRecoverSectorWithSpace(&sector,
539 Entry::size(partition_, key, value)));
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800540 DBG("Writing existing entry; found sector %u (%#" PRIx32 ")",
541 SectorIndex(sector),
542 SectorBaseAddress(sector));
David Rogers3464d0a2020-02-07 11:45:46 -0800543
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800544 if (old_sector != SectorFromKey(key_descriptor)) {
David Rogers3464d0a2020-02-07 11:45:46 -0800545 DBG("Sector for old entry (size %zu) was garbage collected. Old entry "
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800546 "relocated to sector %u",
David Rogers3464d0a2020-02-07 11:45:46 -0800547 original_entry.size(),
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800548 SectorIndex(SectorFromKey(key_descriptor)));
David Rogers3464d0a2020-02-07 11:45:46 -0800549
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800550 old_sector = SectorFromKey(key_descriptor);
David Rogers3464d0a2020-02-07 11:45:46 -0800551 }
552
Wyatt Hepler5a33d8c2020-02-06 09:32:58 -0800553 TRY(AppendEntry(sector, key_descriptor, key, value, new_state));
554
David Rogers3464d0a2020-02-07 11:45:46 -0800555 old_sector->RemoveValidBytes(original_entry.size());
Wyatt Hepler5a33d8c2020-02-06 09:32:58 -0800556 return Status::OK;
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800557}
558
559Status KeyValueStore::WriteEntryForNewKey(string_view key,
560 span<const byte> value) {
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800561 if (key_descriptors_.full()) {
Keir Mierle8c352dc2020-02-02 13:58:19 -0800562 WRN("KVS full: trying to store a new entry, but can't. Have %zu entries",
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800563 key_descriptors_.size());
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800564 return Status::RESOURCE_EXHAUSTED;
565 }
566
David Rogers2761aeb2020-01-31 17:09:00 -0800567 SectorDescriptor* sector;
Wyatt Hepler5406a672020-02-18 15:42:38 -0800568 TRY(FindOrRecoverSectorWithSpace(&sector,
569 Entry::size(partition_, key, value)));
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800570 DBG("Writing new entry; found sector: %u", SectorIndex(sector));
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800571
572 // Create the KeyDescriptor that will be added to the list. The transaction ID
573 // and address will be set by AppendEntry.
574 KeyDescriptor key_descriptor(key);
Wyatt Hepler0af6ad92020-02-13 15:54:46 -0800575 TRY(AppendEntry(sector, &key_descriptor, key, value, KeyDescriptor::kValid));
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800576
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800577 // Only add the entry when we are certain the write succeeded.
578 key_descriptors_.push_back(key_descriptor);
Wyatt Heplerb7609542020-01-24 10:29:54 -0800579 return Status::OK;
580}
581
David Rogers2761aeb2020-01-31 17:09:00 -0800582Status KeyValueStore::RelocateEntry(KeyDescriptor& key_descriptor) {
David Rogersf0a35442020-02-04 12:16:38 -0800583 struct TempEntry {
Wyatt Heplere541e072020-02-14 09:10:53 -0800584 Entry::KeyBuffer key;
Wyatt Heplerce7b8df2020-02-21 10:38:39 -0800585 std::array<byte, sizeof(working_buffer_) - sizeof(key)> value;
David Rogersf0a35442020-02-04 12:16:38 -0800586 };
Wyatt Heplerce7b8df2020-02-21 10:38:39 -0800587 auto [key_buffer, value_buffer] =
588 *std::launder(reinterpret_cast<TempEntry*>(working_buffer_.data()));
David Rogersf0a35442020-02-04 12:16:38 -0800589
Wyatt Heplerce7b8df2020-02-21 10:38:39 -0800590 DBG("Relocating entry at %zx for key %" PRIx32,
591 size_t(key_descriptor.address()),
592 key_descriptor.hash());
David Rogersdf025cd2020-02-06 17:05:34 -0800593
Wyatt Heplere541e072020-02-14 09:10:53 -0800594 // Read the entry to be relocated. Store the entry in a local variable and
David Rogersf0a35442020-02-04 12:16:38 -0800595 // store the key and value in the TempEntry stored in the static allocated
596 // working_buffer_.
Wyatt Heplere541e072020-02-14 09:10:53 -0800597 Entry entry;
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800598 TRY(Entry::Read(partition_, key_descriptor.address(), &entry));
Wyatt Heplerce7b8df2020-02-21 10:38:39 -0800599
600 TRY_ASSIGN(size_t key_length, entry.ReadKey(key_buffer));
601 string_view key = string_view(key_buffer.data(), key_length);
602
603 StatusWithSize result = entry.ReadValue(value_buffer);
604 if (!result.ok()) {
David Rogersf0a35442020-02-04 12:16:38 -0800605 return Status::INTERNAL;
606 }
607
Wyatt Heplerce7b8df2020-02-21 10:38:39 -0800608 const span value = span(value_buffer.data(), result.size());
609 TRY(entry.VerifyChecksum(entry_header_format_.checksum, key, value));
David Rogersf0a35442020-02-04 12:16:38 -0800610
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800611 SectorDescriptor* old_sector = SectorFromKey(key_descriptor);
David Rogersf0a35442020-02-04 12:16:38 -0800612
613 // Find a new sector for the entry and write it to the new location.
David Rogers8ce55cd2020-02-04 19:41:48 -0800614 SectorDescriptor* new_sector;
Wyatt Heplere541e072020-02-14 09:10:53 -0800615 TRY(FindSectorWithSpace(&new_sector, entry.size(), old_sector, true));
Wyatt Heplerce7b8df2020-02-21 10:38:39 -0800616 TRY(AppendEntry(
617 new_sector, &key_descriptor, key, value, key_descriptor.state()));
David Rogersdf025cd2020-02-06 17:05:34 -0800618
Wyatt Heplerd2298282020-02-20 17:12:45 -0800619 // Do the valid bytes accounting for the sector the entry was relocated from.
Wyatt Heplere541e072020-02-14 09:10:53 -0800620 old_sector->RemoveValidBytes(entry.size());
David Rogersdf025cd2020-02-06 17:05:34 -0800621
622 return Status::OK;
David Rogersa12786b2020-01-31 16:02:33 -0800623}
624
David Rogers8db5a722020-02-03 18:28:34 -0800625// Find either an existing sector with enough space that is not the sector to
626// skip, or an empty sector. Maintains the invariant that there is always at
627// least 1 empty sector unless set to bypass the rule.
Wyatt Hepler5a33d8c2020-02-06 09:32:58 -0800628Status KeyValueStore::FindSectorWithSpace(
629 SectorDescriptor** found_sector,
630 size_t size,
631 const SectorDescriptor* sector_to_skip,
632 bool bypass_empty_sector_rule) {
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800633 SectorDescriptor* first_empty_sector = nullptr;
634 bool at_least_two_empty_sectors = bypass_empty_sector_rule;
635
636 DBG("Find sector with %zu bytes available, starting with sector %u",
637 size,
638 SectorIndex(last_new_sector_));
639 if (sector_to_skip != nullptr) {
640 DBG(" Skip sector %u", SectorIndex(sector_to_skip));
641 }
642 if (bypass_empty_sector_rule) {
643 DBG(" Bypassing empty sector rule");
644 }
645
David Rogers8ce55cd2020-02-04 19:41:48 -0800646 // The last_new_sector_ is the sector that was last selected as the "new empty
647 // sector" to write to. This last new sector is used as the starting point for
648 // the next "find a new empty sector to write to" operation. By using the last
649 // new sector as the start point we will cycle which empty sector is selected
650 // next, spreading the wear across all the empty sectors and get a wear
651 // leveling benefit, rather than putting more wear on the lower number
652 // sectors.
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800653 SectorDescriptor* sector = last_new_sector_;
David Rogers67f4b6c2020-02-06 16:17:09 -0800654
David Rogers8ce55cd2020-02-04 19:41:48 -0800655 // Look for a partial sector to use with enough space. Immediately use the
656 // first one of those that is found. While scanning for a partial sector, keep
657 // track of the first empty sector and if a second sector was seen.
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800658 for (size_t j = 0; j < sectors_.size(); j++) {
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800659 sector += 1;
660 if (sector == sectors_.end()) {
661 sector = sectors_.begin();
662 }
Keir Mierle8c352dc2020-02-02 13:58:19 -0800663
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800664 if (sector_to_skip == sector) {
David Rogers8db5a722020-02-03 18:28:34 -0800665 continue;
666 }
667
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800668 const size_t sector_size_bytes = partition_.sector_size_bytes();
669 if (!sector->Empty(sector_size_bytes) && sector->HasSpace(size)) {
670 *found_sector = sector;
David Rogers8ce55cd2020-02-04 19:41:48 -0800671 return Status::OK;
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800672 }
673
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800674 if (sector->Empty(sector_size_bytes)) {
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800675 if (first_empty_sector == nullptr) {
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800676 first_empty_sector = sector;
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800677 } else {
678 at_least_two_empty_sectors = true;
Wyatt Hepler2ad60672020-01-21 08:00:16 -0800679 }
Wyatt Heplerb7609542020-01-24 10:29:54 -0800680 }
681 }
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800682
David Rogers8ce55cd2020-02-04 19:41:48 -0800683 // If the scan for a partial sector does not find a suitable sector, use the
684 // first empty sector that was found. Normally it is required to keep 1 empty
685 // sector after the sector found here, but that rule can be bypassed in
686 // special circumstances (such as during garbage collection).
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800687 if (at_least_two_empty_sectors) {
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800688 DBG(" Found a usable empty sector; returning the first found (%u)",
David Rogers8ce55cd2020-02-04 19:41:48 -0800689 SectorIndex(first_empty_sector));
690 last_new_sector_ = first_empty_sector;
691 *found_sector = first_empty_sector;
692 return Status::OK;
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800693 }
David Rogers8ce55cd2020-02-04 19:41:48 -0800694
695 // No sector was found.
David Rogers67f4b6c2020-02-06 16:17:09 -0800696 DBG(" Unable to find a usable sector");
David Rogers8ce55cd2020-02-04 19:41:48 -0800697 *found_sector = nullptr;
698 return Status::RESOURCE_EXHAUSTED;
Wyatt Heplerb7609542020-01-24 10:29:54 -0800699}
700
David Rogers2761aeb2020-01-31 17:09:00 -0800701Status KeyValueStore::FindOrRecoverSectorWithSpace(SectorDescriptor** sector,
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800702 size_t size) {
David Rogers8ce55cd2020-02-04 19:41:48 -0800703 Status result = FindSectorWithSpace(sector, size);
Wyatt Hepler2d401692020-02-13 16:01:23 -0800704 if (result == Status::RESOURCE_EXHAUSTED && options_.partial_gc_on_write) {
David Rogers1541d612020-02-06 23:47:02 -0800705 // Garbage collect and then try again to find the best sector.
706 TRY(GarbageCollectOneSector());
707 return FindSectorWithSpace(sector, size);
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800708 }
David Rogers8ce55cd2020-02-04 19:41:48 -0800709 return result;
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800710}
711
David Rogers2761aeb2020-01-31 17:09:00 -0800712KeyValueStore::SectorDescriptor* KeyValueStore::FindSectorToGarbageCollect() {
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800713 const size_t sector_size_bytes = partition_.sector_size_bytes();
David Rogers2761aeb2020-01-31 17:09:00 -0800714 SectorDescriptor* sector_candidate = nullptr;
David Rogersa12786b2020-01-31 16:02:33 -0800715 size_t candidate_bytes = 0;
716
717 // Step 1: Try to find a sectors with stale keys and no valid keys (no
718 // relocation needed). If any such sectors are found, use the sector with the
719 // most reclaimable bytes.
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800720 for (auto& sector : sectors_) {
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800721 if ((sector.valid_bytes() == 0) &&
722 (sector.RecoverableBytes(sector_size_bytes) > candidate_bytes)) {
David Rogersa12786b2020-01-31 16:02:33 -0800723 sector_candidate = &sector;
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800724 candidate_bytes = sector.RecoverableBytes(sector_size_bytes);
David Rogersa12786b2020-01-31 16:02:33 -0800725 }
726 }
727
728 // Step 2: If step 1 yields no sectors, just find the sector with the most
729 // reclaimable bytes.
730 if (sector_candidate == nullptr) {
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800731 for (auto& sector : sectors_) {
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800732 if (sector.RecoverableBytes(sector_size_bytes) > candidate_bytes) {
David Rogersa12786b2020-01-31 16:02:33 -0800733 sector_candidate = &sector;
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800734 candidate_bytes = sector.RecoverableBytes(sector_size_bytes);
David Rogersa12786b2020-01-31 16:02:33 -0800735 }
736 }
737 }
738
David Rogers5981f312020-02-13 13:33:56 -0800739 if (sector_candidate != nullptr) {
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800740 DBG("Found sector %u to Garbage Collect, %zu recoverable bytes",
David Rogers5981f312020-02-13 13:33:56 -0800741 SectorIndex(sector_candidate),
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800742 sector_candidate->RecoverableBytes(sector_size_bytes));
David Rogers5981f312020-02-13 13:33:56 -0800743 } else {
744 DBG("Unable to find sector to garbage collect!");
745 }
David Rogersa12786b2020-01-31 16:02:33 -0800746 return sector_candidate;
747}
748
David Rogers1541d612020-02-06 23:47:02 -0800749Status KeyValueStore::GarbageCollectOneSector() {
David Rogers67f4b6c2020-02-06 16:17:09 -0800750 DBG("Garbage Collect a single sector");
751
David Rogersa12786b2020-01-31 16:02:33 -0800752 // Step 1: Find the sector to garbage collect
David Rogers2761aeb2020-01-31 17:09:00 -0800753 SectorDescriptor* sector_to_gc = FindSectorToGarbageCollect();
David Rogers3464d0a2020-02-07 11:45:46 -0800754 LogSectors();
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800755
David Rogersa12786b2020-01-31 16:02:33 -0800756 if (sector_to_gc == nullptr) {
757 return Status::RESOURCE_EXHAUSTED;
758 }
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800759
David Rogersa12786b2020-01-31 16:02:33 -0800760 // Step 2: Move any valid entries in the GC sector to other sectors
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800761 if (sector_to_gc->valid_bytes() != 0) {
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800762 for (auto& descriptor : key_descriptors_) {
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800763 if (AddressInSector(*sector_to_gc, descriptor.address())) {
David Rogers67f4b6c2020-02-06 16:17:09 -0800764 DBG(" Relocate entry");
David Rogers2761aeb2020-01-31 17:09:00 -0800765 TRY(RelocateEntry(descriptor));
David Rogersa12786b2020-01-31 16:02:33 -0800766 }
Wyatt Heplerb7609542020-01-24 10:29:54 -0800767 }
768 }
Wyatt Heplerb7609542020-01-24 10:29:54 -0800769
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800770 if (sector_to_gc->valid_bytes() != 0) {
David Rogers67f4b6c2020-02-06 16:17:09 -0800771 ERR(" Failed to relocate valid entries from sector being garbage "
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800772 "collected, %zu valid bytes remain",
773 sector_to_gc->valid_bytes());
Wyatt Heplerb7609542020-01-24 10:29:54 -0800774 return Status::INTERNAL;
775 }
776
David Rogersa12786b2020-01-31 16:02:33 -0800777 // Step 3: Reinitialize the sector
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800778 sector_to_gc->set_writable_bytes(0);
David Rogersa12786b2020-01-31 16:02:33 -0800779 TRY(partition_.Erase(SectorBaseAddress(sector_to_gc), 1));
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800780 sector_to_gc->set_writable_bytes(partition_.sector_size_bytes());
Wyatt Heplerb7609542020-01-24 10:29:54 -0800781
David Rogers67f4b6c2020-02-06 16:17:09 -0800782 DBG(" Garbage Collect complete");
David Rogers50185ad2020-02-07 00:02:46 -0800783 LogSectors();
David Rogersa12786b2020-01-31 16:02:33 -0800784 return Status::OK;
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800785}
786
David Rogers2761aeb2020-01-31 17:09:00 -0800787Status KeyValueStore::AppendEntry(SectorDescriptor* sector,
788 KeyDescriptor* key_descriptor,
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800789 string_view key,
Wyatt Hepler5a33d8c2020-02-06 09:32:58 -0800790 span<const byte> value,
791 KeyDescriptor::State new_state) {
Wyatt Heplere541e072020-02-14 09:10:53 -0800792 const Address address = NextWritableAddress(sector);
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800793 Entry entry = CreateEntry(address, key, value, new_state);
Wyatt Heplere541e072020-02-14 09:10:53 -0800794
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800795 DBG("Appending %zu B entry with transaction ID %" PRIu32 " to address %#zx",
Wyatt Heplere541e072020-02-14 09:10:53 -0800796 entry.size(),
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800797 entry.transaction_id(),
798 size_t(address));
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800799
David Rogers6592d292020-02-14 14:19:26 -0800800 StatusWithSize result = entry.Write(key, value);
801 // Remove any bytes that were written, even if the write was not successful.
Keir Mierle0a52aed2020-02-21 09:24:36 -0800802 // This is important to retain the writable space invariant on the sectors.
David Rogers6592d292020-02-14 14:19:26 -0800803 sector->RemoveWritableBytes(result.size());
804
805 if (!result.ok()) {
Keir Mierle0a52aed2020-02-21 09:24:36 -0800806 // TODO: Once fake flash errors are supported in tests, test this branch.
807 ERR("Failed to write %zu bytes at %" PRIx32 ". %zu actually written",
David Rogers6592d292020-02-14 14:19:26 -0800808 entry.size(),
Keir Mierle0a52aed2020-02-21 09:24:36 -0800809 address,
David Rogers6592d292020-02-14 14:19:26 -0800810 result.size());
811 return result.status();
812 }
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800813
814 if (options_.verify_on_write) {
Wyatt Heplere541e072020-02-14 09:10:53 -0800815 TRY(entry.VerifyChecksumInFlash(entry_header_format_.checksum));
Wyatt Heplerb7609542020-01-24 10:29:54 -0800816 }
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800817
Keir Mierle9e38b402020-02-21 13:06:21 -0800818 // Entry was written successfully; update the key descriptor and the sector
819 // descriptor to reflect the new entry.
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800820 entry.UpdateDescriptor(key_descriptor);
David Rogers6592d292020-02-14 14:19:26 -0800821 sector->AddValidBytes(result.size());
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800822 return Status::OK;
Wyatt Heplerb7609542020-01-24 10:29:54 -0800823}
824
Wyatt Heplerbdd8e5a2020-02-20 19:27:26 -0800825KeyValueStore::Entry KeyValueStore::CreateEntry(Address address,
826 std::string_view key,
827 span<const byte> value,
828 KeyDescriptor::State state) {
Keir Mierle9e38b402020-02-21 13:06:21 -0800829 // Always bump the transaction ID when creating a new entry.
830 //
831 // Burning transaction IDs prevents inconsistencies between flash and memory
832 // that which could happen if a write succeeds, but for some reason the read
833 // and verify step fails. Here's how this would happen:
834 //
835 // 1. The entry is written but for some reason the flash reports failure OR
836 // The write succeeds, but the read / verify operation fails.
837 // 2. The transaction ID is NOT incremented, because of the failure
838 // 3. (later) A new entry is written, re-using the transaction ID (oops)
839 //
840 // By always burning transaction IDs, the above problem can't happen.
841 last_transaction_id_ += 1;
842
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800843 if (state == KeyDescriptor::kDeleted) {
Wyatt Hepler7465be32020-02-21 15:30:53 -0800844 return Entry::Tombstone(
845 partition_, address, entry_header_format_, key, last_transaction_id_);
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800846 }
847 return Entry::Valid(partition_,
848 address,
Wyatt Hepler88adfe82020-02-20 19:33:27 -0800849 entry_header_format_,
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800850 key,
851 value,
Keir Mierle9e38b402020-02-21 13:06:21 -0800852 last_transaction_id_);
Wyatt Heplerd2298282020-02-20 17:12:45 -0800853}
854
855void KeyValueStore::Reset() {
856 initialized_ = false;
857 key_descriptors_.clear();
858 last_new_sector_ = nullptr;
859 last_transaction_id_ = 0;
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800860}
861
Keir Mierle8c352dc2020-02-02 13:58:19 -0800862void KeyValueStore::LogDebugInfo() {
Keir Mierle8c352dc2020-02-02 13:58:19 -0800863 const size_t sector_size_bytes = partition_.sector_size_bytes();
864 DBG("====================== KEY VALUE STORE DUMP =========================");
865 DBG(" ");
866 DBG("Flash partition:");
Wyatt Heplerad0a7932020-02-06 08:20:38 -0800867 DBG(" Sector count = %zu", partition_.sector_count());
Wyatt Hepler38ce30f2020-02-19 11:48:31 -0800868 DBG(" Sector max count = %zu", sectors_.max_size());
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800869 DBG(" Sectors in use = %zu", sectors_.size());
Keir Mierle8c352dc2020-02-02 13:58:19 -0800870 DBG(" Sector size = %zu", sector_size_bytes);
871 DBG(" Total size = %zu", partition_.size_bytes());
872 DBG(" Alignment = %zu", partition_.alignment_bytes());
873 DBG(" ");
874 DBG("Key descriptors:");
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800875 DBG(" Entry count = %zu", key_descriptors_.size());
Wyatt Hepler38ce30f2020-02-19 11:48:31 -0800876 DBG(" Max entry count = %zu", key_descriptors_.max_size());
Keir Mierle8c352dc2020-02-02 13:58:19 -0800877 DBG(" ");
878 DBG(" # hash version address address (hex)");
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800879 for (size_t i = 0; i < key_descriptors_.size(); ++i) {
880 const KeyDescriptor& kd = key_descriptors_[i];
Keir Mierle8c352dc2020-02-02 13:58:19 -0800881 DBG(" |%3zu: | %8zx |%8zu | %8zu | %8zx",
882 i,
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800883 size_t(kd.hash()),
884 size_t(kd.transaction_id()),
885 size_t(kd.address()),
886 size_t(kd.address()));
Keir Mierle8c352dc2020-02-02 13:58:19 -0800887 }
888 DBG(" ");
889
890 DBG("Sector descriptors:");
891 DBG(" # tail free valid has_space");
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800892 for (size_t sector_id = 0; sector_id < sectors_.size(); ++sector_id) {
893 const SectorDescriptor& sd = sectors_[sector_id];
Keir Mierle8c352dc2020-02-02 13:58:19 -0800894 DBG(" |%3zu: | %8zu |%8zu | %s",
895 sector_id,
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800896 size_t(sd.writable_bytes()),
897 sd.valid_bytes(),
898 sd.writable_bytes() ? "YES" : "");
Keir Mierle8c352dc2020-02-02 13:58:19 -0800899 }
900 DBG(" ");
901
902 // TODO: This should stop logging after some threshold.
903 // size_t dumped_bytes = 0;
904 DBG("Sector raw data:");
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800905 for (size_t sector_id = 0; sector_id < sectors_.size(); ++sector_id) {
Keir Mierle8c352dc2020-02-02 13:58:19 -0800906 // Read sector data. Yes, this will blow the stack on embedded.
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800907 std::array<byte, 500> raw_sector_data; // TODO!!!
Keir Mierle8c352dc2020-02-02 13:58:19 -0800908 StatusWithSize sws =
909 partition_.Read(sector_id * sector_size_bytes, raw_sector_data);
910 DBG("Read: %zu bytes", sws.size());
911
912 DBG(" base addr offs 0 1 2 3 4 5 6 7");
913 for (size_t i = 0; i < sector_size_bytes; i += 8) {
914 DBG(" %3zu %8zx %5zu | %02x %02x %02x %02x %02x %02x %02x %02x",
915 sector_id,
916 (sector_id * sector_size_bytes) + i,
917 i,
918 static_cast<unsigned int>(raw_sector_data[i + 0]),
919 static_cast<unsigned int>(raw_sector_data[i + 1]),
920 static_cast<unsigned int>(raw_sector_data[i + 2]),
921 static_cast<unsigned int>(raw_sector_data[i + 3]),
922 static_cast<unsigned int>(raw_sector_data[i + 4]),
923 static_cast<unsigned int>(raw_sector_data[i + 5]),
924 static_cast<unsigned int>(raw_sector_data[i + 6]),
925 static_cast<unsigned int>(raw_sector_data[i + 7]));
926
927 // TODO: Fix exit condition.
928 if (i > 128) {
929 break;
930 }
931 }
932 DBG(" ");
933 }
934
935 DBG("////////////////////// KEY VALUE STORE DUMP END /////////////////////");
936}
937
David Rogerscf680ab2020-02-12 23:28:32 -0800938void KeyValueStore::LogSectors() const {
939 DBG("Sector descriptors: count %zu", sectors_.size());
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800940 for (auto& sector : sectors_) {
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800941 DBG(" - Sector %u: valid %zu, recoverable %zu, free %zu",
David Rogers50185ad2020-02-07 00:02:46 -0800942 SectorIndex(&sector),
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800943 sector.valid_bytes(),
944 sector.RecoverableBytes(partition_.sector_size_bytes()),
945 sector.writable_bytes());
David Rogers50185ad2020-02-07 00:02:46 -0800946 }
947}
948
David Rogerscf680ab2020-02-12 23:28:32 -0800949void KeyValueStore::LogKeyDescriptor() const {
950 DBG("Key descriptors: count %zu", key_descriptors_.size());
951 for (auto& key : key_descriptors_) {
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800952 DBG(" - Key: %s, hash %#zx, transaction ID %zu, address %#zx",
David Rogerscf680ab2020-02-12 23:28:32 -0800953 key.deleted() ? "Deleted" : "Valid",
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800954 static_cast<size_t>(key.hash()),
955 static_cast<size_t>(key.transaction_id()),
956 static_cast<size_t>(key.address()));
David Rogerscf680ab2020-02-12 23:28:32 -0800957 }
958}
959
Wyatt Hepler2ad60672020-01-21 08:00:16 -0800960} // namespace pw::kvs