blob: eb1631fe29b8eb72d4eb56ac8d25a3e829e03921 [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
Wyatt Hepler22d0d9f2020-03-05 14:57:11 -080022#include "pw_kvs/format.h"
23
Keir Mierle8c352dc2020-02-02 13:58:19 -080024#define PW_LOG_USE_ULTRA_SHORT_NAMES 1
Wyatt Heplerbdd8e5a2020-02-20 19:27:26 -080025#include "pw_kvs/internal/entry.h"
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -080026#include "pw_kvs_private/macros.h"
Keir Mierle8c352dc2020-02-02 13:58:19 -080027#include "pw_log/log.h"
Wyatt Heplerb7609542020-01-24 10:29:54 -080028
Wyatt Hepler2ad60672020-01-21 08:00:16 -080029namespace pw::kvs {
Wyatt Heplera00d1ef2020-02-14 14:31:26 -080030namespace {
Wyatt Heplerb7609542020-01-24 10:29:54 -080031
Wyatt Hepleracaacf92020-01-24 10:58:30 -080032using std::byte;
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -080033using std::string_view;
Wyatt Hepleracaacf92020-01-24 10:58:30 -080034
Wyatt Heplera00d1ef2020-02-14 14:31:26 -080035constexpr bool InvalidKey(std::string_view key) {
Wyatt Heplerbdd8e5a2020-02-20 19:27:26 -080036 return key.empty() || (key.size() > internal::Entry::kMaxKeyLength);
Wyatt Heplera00d1ef2020-02-14 14:31:26 -080037}
38
39} // namespace
40
Wyatt Heplerad0a7932020-02-06 08:20:38 -080041KeyValueStore::KeyValueStore(FlashPartition* partition,
Wyatt Hepler38ce30f2020-02-19 11:48:31 -080042 Vector<KeyDescriptor>& key_descriptor_list,
43 Vector<SectorDescriptor>& sector_descriptor_list,
Wyatt Hepler22d0d9f2020-03-05 14:57:11 -080044 span<const EntryFormat> formats,
Wyatt Heplerad0a7932020-02-06 08:20:38 -080045 const Options& options)
46 : partition_(*partition),
Wyatt Hepler22d0d9f2020-03-05 14:57:11 -080047 formats_(formats),
Wyatt Hepler38ce30f2020-02-19 11:48:31 -080048 key_descriptors_(key_descriptor_list),
Wyatt Heplerd2298282020-02-20 17:12:45 -080049 sectors_(sector_descriptor_list),
50 options_(options) {
51 Reset();
52}
Wyatt Heplerad0a7932020-02-06 08:20:38 -080053
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -080054Status KeyValueStore::Init() {
Wyatt Heplerd2298282020-02-20 17:12:45 -080055 Reset();
56
David Rogers2e9e0c82020-02-13 15:06:06 -080057 INF("Initializing key value store");
Wyatt Hepler38ce30f2020-02-19 11:48:31 -080058 if (partition_.sector_count() > sectors_.max_size()) {
David Rogers2e9e0c82020-02-13 15:06:06 -080059 ERR("KVS init failed: kMaxUsableSectors (=%zu) must be at least as "
60 "large as the number of sectors in the flash partition (=%zu)",
Wyatt Hepler38ce30f2020-02-19 11:48:31 -080061 sectors_.max_size(),
David Rogers2e9e0c82020-02-13 15:06:06 -080062 partition_.sector_count());
Wyatt Heplerad0a7932020-02-06 08:20:38 -080063 return Status::FAILED_PRECONDITION;
64 }
65
Keir Mierle8c352dc2020-02-02 13:58:19 -080066 const size_t sector_size_bytes = partition_.sector_size_bytes();
Keir Mierle8c352dc2020-02-02 13:58:19 -080067
David Rogersf0a35442020-02-04 12:16:38 -080068 if (working_buffer_.size() < sector_size_bytes) {
Wyatt Heplerce7b8df2020-02-21 10:38:39 -080069 ERR("KVS init failed: working_buffer_ (%zu B) is smaller than sector size "
70 "(%zu B)",
David Rogersf0a35442020-02-04 12:16:38 -080071 working_buffer_.size(),
72 sector_size_bytes);
73 return Status::INVALID_ARGUMENT;
74 }
75
Keir Mierle8c352dc2020-02-02 13:58:19 -080076 DBG("First pass: Read all entries from all sectors");
Wyatt Hepler2c7eca02020-02-18 16:01:42 -080077 Address sector_address = 0;
Keir Mierle8c352dc2020-02-02 13:58:19 -080078
Wyatt Heplerd2298282020-02-20 17:12:45 -080079 sectors_.assign(partition_.sector_count(),
80 SectorDescriptor(sector_size_bytes));
81
Alexei Frolovd4adf912020-02-21 13:29:15 -080082 size_t total_corrupt_bytes = 0;
83 int corrupt_entries = 0;
David Rogers91627482020-02-27 17:38:12 -080084 bool empty_sector_found = false;
Alexei Frolovd4adf912020-02-21 13:29:15 -080085
Wyatt Hepler2c7eca02020-02-18 16:01:42 -080086 for (SectorDescriptor& sector : sectors_) {
Keir Mierle8c352dc2020-02-02 13:58:19 -080087 Address entry_address = sector_address;
88
Alexei Frolovd4adf912020-02-21 13:29:15 -080089 size_t sector_corrupt_bytes = 0;
90
Wyatt Hepler2c7eca02020-02-18 16:01:42 -080091 for (int num_entries_in_sector = 0; true; num_entries_in_sector++) {
92 DBG("Load entry: sector=%" PRIx32 ", entry#=%d, address=%" PRIx32,
93 sector_address,
Keir Mierle8c352dc2020-02-02 13:58:19 -080094 num_entries_in_sector,
Wyatt Hepler2c7eca02020-02-18 16:01:42 -080095 entry_address);
Keir Mierle8c352dc2020-02-02 13:58:19 -080096
Wyatt Hepler2c7eca02020-02-18 16:01:42 -080097 if (!AddressInSector(sector, entry_address)) {
Keir Mierle8c352dc2020-02-02 13:58:19 -080098 DBG("Fell off end of sector; moving to the next sector");
99 break;
100 }
101
102 Address next_entry_address;
103 Status status = LoadEntry(entry_address, &next_entry_address);
104 if (status == Status::NOT_FOUND) {
105 DBG("Hit un-written data in sector; moving to the next sector");
106 break;
107 }
108 if (status == Status::DATA_LOSS) {
Alexei Frolovd4adf912020-02-21 13:29:15 -0800109 // The entry could not be read, indicating data corruption within the
110 // sector. Try to scan the remainder of the sector for other entries.
111 ERR("KVS init: data loss detected in sector %u at address %zu",
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800112 SectorIndex(&sector),
113 size_t(entry_address));
Alexei Frolovd4adf912020-02-21 13:29:15 -0800114
115 corrupt_entries++;
116
117 status = ScanForEntry(sector,
118 entry_address + Entry::kMinAlignmentBytes,
119 &next_entry_address);
120 if (status == Status::NOT_FOUND) {
121 // No further entries in this sector. Mark the remaining bytes in the
122 // sector as corrupt (since we can't reliably know the size of the
123 // corrupt entry).
124 sector_corrupt_bytes +=
125 sector_size_bytes - (entry_address - sector_address);
126 break;
127 }
128
129 if (!status.ok()) {
130 ERR("Unexpected error in KVS initialization: %s", status.str());
131 return Status::UNKNOWN;
132 }
133
134 sector_corrupt_bytes += next_entry_address - entry_address;
135 } else if (!status.ok()) {
136 ERR("Unexpected error in KVS initialization: %s", status.str());
137 return Status::UNKNOWN;
Keir Mierle8c352dc2020-02-02 13:58:19 -0800138 }
Keir Mierle8c352dc2020-02-02 13:58:19 -0800139
140 // Entry loaded successfully; so get ready to load the next one.
141 entry_address = next_entry_address;
142
143 // Update of the number of writable bytes in this sector.
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800144 sector.set_writable_bytes(sector_size_bytes -
145 (entry_address - sector_address));
Keir Mierle8c352dc2020-02-02 13:58:19 -0800146 }
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800147
Alexei Frolovd4adf912020-02-21 13:29:15 -0800148 if (sector_corrupt_bytes > 0) {
149 // If the sector contains corrupt data, prevent any further entries from
150 // being written to it by indicating that it has no space. This should
151 // also make it a decent GC candidate. Valid keys in the sector are still
152 // readable as normal.
153 sector.set_writable_bytes(0);
154
155 WRN("Sector %u contains %zuB of corrupt data",
156 SectorIndex(&sector),
157 sector_corrupt_bytes);
158 }
159
David Rogers91627482020-02-27 17:38:12 -0800160 if (sector.Empty(sector_size_bytes)) {
161 empty_sector_found = true;
162 }
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800163 sector_address += sector_size_bytes;
Alexei Frolovd4adf912020-02-21 13:29:15 -0800164 total_corrupt_bytes += sector_corrupt_bytes;
Keir Mierle8c352dc2020-02-02 13:58:19 -0800165 }
166
167 DBG("Second pass: Count valid bytes in each sector");
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800168 const KeyDescriptor* newest_key = nullptr;
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800169
Keir Mierle8c352dc2020-02-02 13:58:19 -0800170 // For every valid key, increment the valid bytes for that sector.
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800171 for (KeyDescriptor& key_descriptor : key_descriptors_) {
David Rogersf56131c2020-03-04 10:19:22 -0800172 for (auto& address : key_descriptor.addresses()) {
173 Entry entry;
Wyatt Hepler22d0d9f2020-03-05 14:57:11 -0800174 TRY(Entry::Read(partition_, key_descriptor.address(), formats_, &entry));
David Rogersf56131c2020-03-04 10:19:22 -0800175 SectorFromAddress(address)->AddValidBytes(entry.size());
176 }
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800177 if (key_descriptor.IsNewerThan(last_transaction_id_)) {
178 last_transaction_id_ = key_descriptor.transaction_id();
179 newest_key = &key_descriptor;
180 }
Keir Mierle8c352dc2020-02-02 13:58:19 -0800181 }
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800182
183 if (newest_key == nullptr) {
184 last_new_sector_ = sectors_.begin();
185 } else {
David Rogersf56131c2020-03-04 10:19:22 -0800186 last_new_sector_ = SectorFromAddress(newest_key->addresses().back());
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800187 }
188
David Rogers91627482020-02-27 17:38:12 -0800189 if (!empty_sector_found) {
190 // TODO: Record/report the error condition and recovery result.
191 Status gc_result = GarbageCollectPartial();
192
193 if (!gc_result.ok()) {
194 ERR("KVS init failed: Unable to maintain required free sector");
195 return Status::INTERNAL;
196 }
197 }
198
Wyatt Hepler729f28c2020-02-05 09:46:00 -0800199 initialized_ = true;
David Rogers2e9e0c82020-02-13 15:06:06 -0800200
Armando Montanez5464d5f2020-02-20 10:12:20 -0800201 INF("KeyValueStore init complete: active keys %zu, deleted keys %zu, sectors "
David Rogers2e9e0c82020-02-13 15:06:06 -0800202 "%zu, logical sector size %zu bytes",
203 size(),
204 (key_descriptors_.size() - size()),
205 sectors_.size(),
206 partition_.sector_size_bytes());
207
Alexei Frolovd4adf912020-02-21 13:29:15 -0800208 if (total_corrupt_bytes > 0) {
209 WRN("Found %zu corrupt bytes and %d corrupt entries during init process; "
210 "some keys may be missing",
211 total_corrupt_bytes,
212 corrupt_entries);
213 return Status::DATA_LOSS;
214 }
215
Keir Mierle8c352dc2020-02-02 13:58:19 -0800216 return Status::OK;
217}
218
Alexei Frolov9e235832020-02-24 12:44:45 -0800219KeyValueStore::StorageStats KeyValueStore::GetStorageStats() const {
220 StorageStats stats{0, 0, 0};
221 const size_t sector_size = partition_.sector_size_bytes();
222 bool found_empty_sector = false;
223
224 for (const SectorDescriptor& sector : sectors_) {
225 stats.in_use_bytes += sector.valid_bytes();
226 stats.reclaimable_bytes += sector.RecoverableBytes(sector_size);
227
228 if (!found_empty_sector && sector.Empty(sector_size)) {
229 // The KVS tries to always keep an empty sector for GC, so don't count
230 // the first empty sector seen as writable space. However, a free sector
231 // cannot always be assumed to exist; if a GC operation fails, all sectors
232 // may be partially written, in which case the space reported might be
233 // inaccurate.
234 found_empty_sector = true;
235 continue;
236 }
237
238 stats.writable_bytes += sector.writable_bytes();
239 }
240
241 return stats;
242}
243
Keir Mierle8c352dc2020-02-02 13:58:19 -0800244Status KeyValueStore::LoadEntry(Address entry_address,
245 Address* next_entry_address) {
Wyatt Heplere541e072020-02-14 09:10:53 -0800246 Entry entry;
Wyatt Hepler22d0d9f2020-03-05 14:57:11 -0800247 TRY(Entry::Read(partition_, entry_address, formats_, &entry));
Keir Mierle8c352dc2020-02-02 13:58:19 -0800248
249 // Read the key from flash & validate the entry (which reads the value).
Wyatt Heplera00d1ef2020-02-14 14:31:26 -0800250 Entry::KeyBuffer key_buffer;
Wyatt Heplere541e072020-02-14 09:10:53 -0800251 TRY_ASSIGN(size_t key_length, entry.ReadKey(key_buffer));
252 const string_view key(key_buffer.data(), key_length);
Wyatt Heplerbab0e202020-02-04 07:40:08 -0800253
Wyatt Hepler22d0d9f2020-03-05 14:57:11 -0800254 TRY(entry.VerifyChecksumInFlash());
David Rogersf56131c2020-03-04 10:19:22 -0800255
256 // A valid entry was found, so update the next entry address before doing any
257 // of the checks that happen in AppendNewOrOverwriteStaleExistingDescriptor().
258 *next_entry_address = entry.next_address();
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800259 TRY(AppendNewOrOverwriteStaleExistingDescriptor(entry.descriptor(key)));
Keir Mierle8c352dc2020-02-02 13:58:19 -0800260
Keir Mierle8c352dc2020-02-02 13:58:19 -0800261 return Status::OK;
262}
263
Alexei Frolovd4adf912020-02-21 13:29:15 -0800264// Scans flash memory within a sector to find a KVS entry magic.
Alexei Frolovd4adf912020-02-21 13:29:15 -0800265Status KeyValueStore::ScanForEntry(const SectorDescriptor& sector,
266 Address start_address,
267 Address* next_entry_address) {
268 DBG("Scanning sector %u for entries starting from address %zx",
269 SectorIndex(&sector),
270 size_t(start_address));
271
272 // Entries must start at addresses which are aligned on a multiple of
273 // Entry::kMinAlignmentBytes. However, that multiple can vary between entries.
274 // When scanning, we don't have an entry to tell us what the current alignment
275 // is, so the minimum alignment is used to be exhaustive.
276 for (Address address = AlignUp(start_address, Entry::kMinAlignmentBytes);
277 AddressInSector(sector, address);
278 address += Entry::kMinAlignmentBytes) {
Alexei Frolovd4adf912020-02-21 13:29:15 -0800279 uint32_t magic;
280 TRY(partition_.Read(address, as_writable_bytes(span(&magic, 1))));
Wyatt Hepler22d0d9f2020-03-05 14:57:11 -0800281 if (formats_.KnownMagic(magic)) {
Alexei Frolovd4adf912020-02-21 13:29:15 -0800282 DBG("Found entry magic at address %zx", size_t(address));
283 *next_entry_address = address;
284 return Status::OK;
285 }
286 }
287
288 return Status::NOT_FOUND;
289}
290
Keir Mierle8c352dc2020-02-02 13:58:19 -0800291// TODO: This method is the trigger of the O(valid_entries * all_entries) time
292// complexity for reading. At some cost to memory, this could be optimized by
293// using a hash table instead of scanning, but in practice this should be fine
294// for a small number of keys
295Status KeyValueStore::AppendNewOrOverwriteStaleExistingDescriptor(
296 const KeyDescriptor& key_descriptor) {
297 // With the new key descriptor, either add it to the descriptor table or
298 // overwrite an existing entry with an older version of the key.
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800299 KeyDescriptor* existing_descriptor = FindDescriptor(key_descriptor.hash());
Keir Mierle8c352dc2020-02-02 13:58:19 -0800300
Wyatt Hepler5406a672020-02-18 15:42:38 -0800301 // Write a new entry.
302 if (existing_descriptor == nullptr) {
303 if (key_descriptors_.full()) {
304 return Status::RESOURCE_EXHAUSTED;
305 }
306 key_descriptors_.push_back(key_descriptor);
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800307 } else if (key_descriptor.IsNewerThan(
308 existing_descriptor->transaction_id())) {
Wyatt Hepler5406a672020-02-18 15:42:38 -0800309 // Existing entry is old; replace the existing entry with the new one.
310 *existing_descriptor = key_descriptor;
David Rogersf56131c2020-03-04 10:19:22 -0800311 } else if (existing_descriptor->transaction_id() ==
312 key_descriptor.transaction_id()) {
313 // If the entries have a duplicate transaction ID, add the new (redundant)
314 // entry to the existing descriptor.
315 if (existing_descriptor->hash() != key_descriptor.hash()) {
316 ERR("Duplicate entry for key %#010" PRIx32 " with transaction ID %" PRIu32
317 " has non-matching hash",
318 key_descriptor.hash(),
319 key_descriptor.transaction_id());
Wyatt Hepler5406a672020-02-18 15:42:38 -0800320 return Status::DATA_LOSS;
321 }
David Rogersf56131c2020-03-04 10:19:22 -0800322
323 // Verify that this entry is not in the same sector as an existing copy of
324 // this same key.
325 for (auto address : existing_descriptor->addresses()) {
326 if (SectorFromAddress(address) ==
327 SectorFromAddress(key_descriptor.address())) {
328 DBG("Multiple Redundant entries in same sector %u",
329 SectorIndex(SectorFromAddress(address)));
330 return Status::DATA_LOSS;
331 }
332 }
333 existing_descriptor->addresses().push_back(key_descriptor.address());
334 } else {
Wyatt Hepler5406a672020-02-18 15:42:38 -0800335 DBG("Found stale entry when appending; ignoring");
Keir Mierle8c352dc2020-02-02 13:58:19 -0800336 }
Keir Mierle8c352dc2020-02-02 13:58:19 -0800337 return Status::OK;
338}
339
Keir Mierle8c352dc2020-02-02 13:58:19 -0800340KeyValueStore::KeyDescriptor* KeyValueStore::FindDescriptor(uint32_t hash) {
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800341 for (KeyDescriptor& key_descriptor : key_descriptors_) {
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800342 if (key_descriptor.hash() == hash) {
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800343 return &key_descriptor;
Keir Mierle8c352dc2020-02-02 13:58:19 -0800344 }
345 }
346 return nullptr;
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800347}
348
349StatusWithSize KeyValueStore::Get(string_view key,
Wyatt Hepler5f6efc02020-02-18 16:54:31 -0800350 span<byte> value_buffer,
351 size_t offset_bytes) const {
Wyatt Hepler50f70772020-02-13 11:25:10 -0800352 TRY_WITH_SIZE(CheckOperation(key));
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800353
David Rogers2761aeb2020-01-31 17:09:00 -0800354 const KeyDescriptor* key_descriptor;
Wyatt Hepler2d401692020-02-13 16:01:23 -0800355 TRY_WITH_SIZE(FindExistingKeyDescriptor(key, &key_descriptor));
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800356
Wyatt Heplerfac81132020-02-27 17:26:33 -0800357 return Get(key, *key_descriptor, value_buffer, offset_bytes);
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800358}
359
Wyatt Heplerfac81132020-02-27 17:26:33 -0800360Status KeyValueStore::PutBytes(string_view key, span<const byte> value) {
Keir Mierle8c352dc2020-02-02 13:58:19 -0800361 DBG("Writing key/value; key length=%zu, value length=%zu",
362 key.size(),
363 value.size());
Wyatt Hepler729f28c2020-02-05 09:46:00 -0800364
365 TRY(CheckOperation(key));
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800366
Wyatt Hepler5406a672020-02-18 15:42:38 -0800367 if (Entry::size(partition_, key, value) > partition_.sector_size_bytes()) {
368 DBG("%zu B value with %zu B key cannot fit in one sector",
369 value.size(),
370 key.size());
371 return Status::INVALID_ARGUMENT;
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800372 }
373
David Rogers2761aeb2020-01-31 17:09:00 -0800374 KeyDescriptor* key_descriptor;
Wyatt Hepler2d401692020-02-13 16:01:23 -0800375 Status status = FindKeyDescriptor(key, &key_descriptor);
376
377 if (status.ok()) {
David Rogersf56131c2020-03-04 10:19:22 -0800378 // TODO: figure out logging how to support multiple addresses.
379 DBG("Overwriting entry for key %#08" PRIx32 " in %u sectors including %u",
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800380 key_descriptor->hash(),
David Rogersf56131c2020-03-04 10:19:22 -0800381 unsigned(key_descriptor->addresses().size()),
382 SectorIndex(SectorFromAddress(key_descriptor->address())));
Wyatt Hepler5a33d8c2020-02-06 09:32:58 -0800383 return WriteEntryForExistingKey(
384 key_descriptor, KeyDescriptor::kValid, key, value);
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800385 }
David Rogers2761aeb2020-01-31 17:09:00 -0800386
Wyatt Hepler2d401692020-02-13 16:01:23 -0800387 if (status == Status::NOT_FOUND) {
388 return WriteEntryForNewKey(key, value);
389 }
390
391 return status;
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800392}
393
394Status KeyValueStore::Delete(string_view key) {
Wyatt Hepler729f28c2020-02-05 09:46:00 -0800395 TRY(CheckOperation(key));
396
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800397 KeyDescriptor* key_descriptor;
Wyatt Hepler2d401692020-02-13 16:01:23 -0800398 TRY(FindExistingKeyDescriptor(key, &key_descriptor));
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800399
David Rogersf56131c2020-03-04 10:19:22 -0800400 // TODO: figure out logging how to support multiple addresses.
401 DBG("Writing tombstone for key %#08" PRIx32 " in %u sectors including %u",
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800402 key_descriptor->hash(),
David Rogersf56131c2020-03-04 10:19:22 -0800403 unsigned(key_descriptor->addresses().size()),
404 SectorIndex(SectorFromAddress(key_descriptor->address())));
Wyatt Hepler5a33d8c2020-02-06 09:32:58 -0800405 return WriteEntryForExistingKey(
406 key_descriptor, KeyDescriptor::kDeleted, key, {});
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800407}
408
Wyatt Hepler08d37d82020-02-27 15:45:37 -0800409void KeyValueStore::Item::ReadKey() {
410 key_buffer_.fill('\0');
411
412 Entry entry;
Wyatt Hepler22d0d9f2020-03-05 14:57:11 -0800413 if (Entry::Read(
414 kvs_.partition_, descriptor_->address(), kvs_.formats_, &entry)
415 .ok()) {
Wyatt Hepler08d37d82020-02-27 15:45:37 -0800416 entry.ReadKey(key_buffer_);
417 }
418}
419
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800420KeyValueStore::iterator& KeyValueStore::iterator::operator++() {
421 // Skip to the next entry that is valid (not deleted).
Wyatt Hepler08d37d82020-02-27 15:45:37 -0800422 while (++item_.descriptor_ != item_.kvs_.key_descriptors_.end() &&
423 item_.descriptor_->deleted()) {
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800424 }
425 return *this;
426}
427
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800428KeyValueStore::iterator KeyValueStore::begin() const {
Wyatt Hepler08d37d82020-02-27 15:45:37 -0800429 const KeyDescriptor* descriptor = key_descriptors_.begin();
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800430 // Skip over any deleted entries at the start of the descriptor list.
Wyatt Hepler08d37d82020-02-27 15:45:37 -0800431 while (descriptor != key_descriptors_.end() && descriptor->deleted()) {
432 ++descriptor;
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800433 }
Wyatt Hepler08d37d82020-02-27 15:45:37 -0800434 return iterator(*this, descriptor);
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800435}
436
437// TODO(hepler): The valid entry count could be tracked in the KVS to avoid the
438// need for this for-loop.
439size_t KeyValueStore::size() const {
440 size_t valid_entries = 0;
441
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800442 for (const KeyDescriptor& key_descriptor : key_descriptors_) {
443 if (!key_descriptor.deleted()) {
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800444 valid_entries += 1;
445 }
446 }
447
448 return valid_entries;
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800449}
450
Wyatt Heplered163b02020-02-03 17:49:32 -0800451StatusWithSize KeyValueStore::ValueSize(std::string_view key) const {
Wyatt Hepler50f70772020-02-13 11:25:10 -0800452 TRY_WITH_SIZE(CheckOperation(key));
Wyatt Heplered163b02020-02-03 17:49:32 -0800453
454 const KeyDescriptor* key_descriptor;
Wyatt Hepler2d401692020-02-13 16:01:23 -0800455 TRY_WITH_SIZE(FindExistingKeyDescriptor(key, &key_descriptor));
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800456
Wyatt Heplerfac81132020-02-27 17:26:33 -0800457 return ValueSize(*key_descriptor);
458}
Wyatt Heplered163b02020-02-03 17:49:32 -0800459
Wyatt Heplerfac81132020-02-27 17:26:33 -0800460StatusWithSize KeyValueStore::Get(string_view key,
461 const KeyDescriptor& descriptor,
462 span<std::byte> value_buffer,
463 size_t offset_bytes) const {
464 Entry entry;
Wyatt Hepler22d0d9f2020-03-05 14:57:11 -0800465 TRY_WITH_SIZE(
466 Entry::Read(partition_, descriptor.address(), formats_, &entry));
Wyatt Heplerfac81132020-02-27 17:26:33 -0800467
468 StatusWithSize result = entry.ReadValue(value_buffer, offset_bytes);
469 if (result.ok() && options_.verify_on_read && offset_bytes == 0u) {
Wyatt Hepler22d0d9f2020-03-05 14:57:11 -0800470 Status verify_result =
471 entry.VerifyChecksum(key, value_buffer.first(result.size()));
Wyatt Heplerfac81132020-02-27 17:26:33 -0800472 if (!verify_result.ok()) {
473 std::memset(value_buffer.data(), 0, result.size());
474 return StatusWithSize(verify_result, 0);
475 }
476
477 return StatusWithSize(verify_result, result.size());
478 }
479 return result;
Wyatt Heplered163b02020-02-03 17:49:32 -0800480}
481
Wyatt Hepler6e3a83b2020-02-04 07:36:45 -0800482Status KeyValueStore::FixedSizeGet(std::string_view key,
Wyatt Heplerfac81132020-02-27 17:26:33 -0800483 void* value,
484 size_t size_bytes) const {
485 TRY(CheckOperation(key));
486
487 const KeyDescriptor* descriptor;
488 TRY(FindExistingKeyDescriptor(key, &descriptor));
489
490 return FixedSizeGet(key, *descriptor, value, size_bytes);
491}
492
493Status KeyValueStore::FixedSizeGet(std::string_view key,
494 const KeyDescriptor& descriptor,
495 void* value,
Wyatt Hepler6e3a83b2020-02-04 07:36:45 -0800496 size_t size_bytes) const {
497 // Ensure that the size of the stored value matches the size of the type.
498 // Otherwise, report error. This check avoids potential memory corruption.
Wyatt Heplerfac81132020-02-27 17:26:33 -0800499 TRY_ASSIGN(const size_t actual_size, ValueSize(descriptor));
500
501 if (actual_size != size_bytes) {
502 DBG("Requested %zu B read, but value is %zu B", size_bytes, actual_size);
Wyatt Hepler6e3a83b2020-02-04 07:36:45 -0800503 return Status::INVALID_ARGUMENT;
Wyatt Heplerbab0e202020-02-04 07:40:08 -0800504 }
Wyatt Heplerfac81132020-02-27 17:26:33 -0800505
506 StatusWithSize result =
507 Get(key, descriptor, span(static_cast<byte*>(value), size_bytes), 0);
508
509 return result.status();
510}
511
512StatusWithSize KeyValueStore::ValueSize(const KeyDescriptor& descriptor) const {
513 Entry entry;
Wyatt Hepler22d0d9f2020-03-05 14:57:11 -0800514 TRY_WITH_SIZE(
515 Entry::Read(partition_, descriptor.address(), formats_, &entry));
Wyatt Heplerfac81132020-02-27 17:26:33 -0800516
517 return StatusWithSize(entry.value_size());
Keir Mierle8c352dc2020-02-02 13:58:19 -0800518}
519
Wyatt Hepler729f28c2020-02-05 09:46:00 -0800520Status KeyValueStore::CheckOperation(string_view key) const {
Wyatt Hepleracaacf92020-01-24 10:58:30 -0800521 if (InvalidKey(key)) {
Wyatt Heplerb7609542020-01-24 10:29:54 -0800522 return Status::INVALID_ARGUMENT;
523 }
Wyatt Heplerd2298282020-02-20 17:12:45 -0800524 if (!initialized()) {
Wyatt Heplerb7609542020-01-24 10:29:54 -0800525 return Status::FAILED_PRECONDITION;
526 }
Wyatt Heplerb7609542020-01-24 10:29:54 -0800527 return Status::OK;
528}
529
Wyatt Hepler2d401692020-02-13 16:01:23 -0800530// Searches for a KeyDescriptor that matches this key and sets *result to point
531// to it if one is found.
532//
533// OK: there is a matching descriptor and *result is set
534// NOT_FOUND: there is no descriptor that matches this key, but this key
535// has a unique hash (and could potentially be added to the KVS)
536// ALREADY_EXISTS: there is no descriptor that matches this key, but the
537// key's hash collides with the hash for an existing descriptor
538//
David Rogers2761aeb2020-01-31 17:09:00 -0800539Status KeyValueStore::FindKeyDescriptor(string_view key,
540 const KeyDescriptor** result) const {
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800541 const uint32_t hash = internal::Hash(key);
Wyatt Heplera00d1ef2020-02-14 14:31:26 -0800542 Entry::KeyBuffer key_buffer;
Wyatt Heplerb7609542020-01-24 10:29:54 -0800543
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800544 for (auto& descriptor : key_descriptors_) {
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800545 if (descriptor.hash() == hash) {
Wyatt Heplere541e072020-02-14 09:10:53 -0800546 TRY(Entry::ReadKey(
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800547 partition_, descriptor.address(), key.size(), key_buffer.data()));
Wyatt Heplerb7609542020-01-24 10:29:54 -0800548
Wyatt Heplere541e072020-02-14 09:10:53 -0800549 if (key == string_view(key_buffer.data(), key.size())) {
Wyatt Hepler5a33d8c2020-02-06 09:32:58 -0800550 DBG("Found match for key hash 0x%08" PRIx32, hash);
David Rogers2761aeb2020-01-31 17:09:00 -0800551 *result = &descriptor;
Wyatt Heplerb7609542020-01-24 10:29:54 -0800552 return Status::OK;
Wyatt Hepler2d401692020-02-13 16:01:23 -0800553 } else {
554 WRN("Found key hash collision for 0x%08" PRIx32, hash);
555 return Status::ALREADY_EXISTS;
Wyatt Heplerb7609542020-01-24 10:29:54 -0800556 }
Wyatt Heplerb7609542020-01-24 10:29:54 -0800557 }
558 }
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800559 return Status::NOT_FOUND;
560}
561
Wyatt Hepler2d401692020-02-13 16:01:23 -0800562// Searches for a KeyDescriptor that matches this key and sets *result to point
563// to it if one is found.
564//
565// OK: there is a matching descriptor and *result is set
566// NOT_FOUND: there is no descriptor that matches this key
567//
568Status KeyValueStore::FindExistingKeyDescriptor(
569 string_view key, const KeyDescriptor** result) const {
570 Status status = FindKeyDescriptor(key, result);
571
572 // If the key's hash collides with an existing key or if the key is deleted,
573 // treat it as if it is not in the KVS.
574 if (status == Status::ALREADY_EXISTS ||
575 (status.ok() && (*result)->deleted())) {
576 return Status::NOT_FOUND;
577 }
578 return status;
579}
580
David Rogers2761aeb2020-01-31 17:09:00 -0800581Status KeyValueStore::WriteEntryForExistingKey(KeyDescriptor* key_descriptor,
Wyatt Hepler5a33d8c2020-02-06 09:32:58 -0800582 KeyDescriptor::State new_state,
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800583 string_view key,
584 span<const byte> value) {
Wyatt Hepler5a33d8c2020-02-06 09:32:58 -0800585 // Find the original entry and sector to update the sector's valid_bytes.
Wyatt Hepler30a52152020-02-12 11:26:05 -0800586 Entry original_entry;
Wyatt Hepler22d0d9f2020-03-05 14:57:11 -0800587 TRY(Entry::Read(
588 partition_, key_descriptor->address(), formats_, &original_entry));
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800589
David Rogers2761aeb2020-01-31 17:09:00 -0800590 SectorDescriptor* sector;
Wyatt Hepler5406a672020-02-18 15:42:38 -0800591 TRY(FindOrRecoverSectorWithSpace(&sector,
592 Entry::size(partition_, key, value)));
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800593 DBG("Writing existing entry; found sector %u (%#" PRIx32 ")",
594 SectorIndex(sector),
595 SectorBaseAddress(sector));
David Rogers3464d0a2020-02-07 11:45:46 -0800596
David Rogersf56131c2020-03-04 10:19:22 -0800597 // TODO: Verify the copy does a full copy including the address vector.
598 KeyDescriptor old_key_descriptor = *key_descriptor;
David Rogers3464d0a2020-02-07 11:45:46 -0800599
Wyatt Hepler5a33d8c2020-02-06 09:32:58 -0800600 TRY(AppendEntry(sector, key_descriptor, key, value, new_state));
601
David Rogersf56131c2020-03-04 10:19:22 -0800602 for (auto& address : old_key_descriptor.addresses()) {
603 SectorFromAddress(address)->RemoveValidBytes(original_entry.size());
604 }
605
Wyatt Hepler5a33d8c2020-02-06 09:32:58 -0800606 return Status::OK;
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800607}
608
609Status KeyValueStore::WriteEntryForNewKey(string_view key,
610 span<const byte> value) {
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800611 if (key_descriptors_.full()) {
Keir Mierle8c352dc2020-02-02 13:58:19 -0800612 WRN("KVS full: trying to store a new entry, but can't. Have %zu entries",
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800613 key_descriptors_.size());
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800614 return Status::RESOURCE_EXHAUSTED;
615 }
616
David Rogers2761aeb2020-01-31 17:09:00 -0800617 SectorDescriptor* sector;
Wyatt Hepler5406a672020-02-18 15:42:38 -0800618 TRY(FindOrRecoverSectorWithSpace(&sector,
619 Entry::size(partition_, key, value)));
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800620 DBG("Writing new entry; found sector: %u", SectorIndex(sector));
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800621
622 // Create the KeyDescriptor that will be added to the list. The transaction ID
623 // and address will be set by AppendEntry.
624 KeyDescriptor key_descriptor(key);
Wyatt Hepler0af6ad92020-02-13 15:54:46 -0800625 TRY(AppendEntry(sector, &key_descriptor, key, value, KeyDescriptor::kValid));
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800626
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800627 // Only add the entry when we are certain the write succeeded.
628 key_descriptors_.push_back(key_descriptor);
Wyatt Heplerb7609542020-01-24 10:29:54 -0800629 return Status::OK;
630}
631
David Rogersf56131c2020-03-04 10:19:22 -0800632Status KeyValueStore::RelocateEntry(KeyDescriptor& key_descriptor,
633 KeyValueStore::Address address) {
David Rogersf0a35442020-02-04 12:16:38 -0800634 struct TempEntry {
Wyatt Heplere541e072020-02-14 09:10:53 -0800635 Entry::KeyBuffer key;
Wyatt Heplerce7b8df2020-02-21 10:38:39 -0800636 std::array<byte, sizeof(working_buffer_) - sizeof(key)> value;
David Rogersf0a35442020-02-04 12:16:38 -0800637 };
Wyatt Heplerce7b8df2020-02-21 10:38:39 -0800638 auto [key_buffer, value_buffer] =
639 *std::launder(reinterpret_cast<TempEntry*>(working_buffer_.data()));
David Rogersf0a35442020-02-04 12:16:38 -0800640
David Rogersf56131c2020-03-04 10:19:22 -0800641 DBG("Relocating entry at %zx for key %#010" PRIx32,
642 size_t(address),
Wyatt Heplerce7b8df2020-02-21 10:38:39 -0800643 key_descriptor.hash());
David Rogersdf025cd2020-02-06 17:05:34 -0800644
Wyatt Heplere541e072020-02-14 09:10:53 -0800645 // Read the entry to be relocated. Store the entry in a local variable and
David Rogersf0a35442020-02-04 12:16:38 -0800646 // store the key and value in the TempEntry stored in the static allocated
647 // working_buffer_.
Wyatt Heplere541e072020-02-14 09:10:53 -0800648 Entry entry;
Wyatt Hepler22d0d9f2020-03-05 14:57:11 -0800649 TRY(Entry::Read(partition_, key_descriptor.address(), formats_, &entry));
Wyatt Heplerce7b8df2020-02-21 10:38:39 -0800650
651 TRY_ASSIGN(size_t key_length, entry.ReadKey(key_buffer));
652 string_view key = string_view(key_buffer.data(), key_length);
653
654 StatusWithSize result = entry.ReadValue(value_buffer);
655 if (!result.ok()) {
David Rogersf0a35442020-02-04 12:16:38 -0800656 return Status::INTERNAL;
657 }
658
Wyatt Heplerce7b8df2020-02-21 10:38:39 -0800659 const span value = span(value_buffer.data(), result.size());
Wyatt Hepler22d0d9f2020-03-05 14:57:11 -0800660 TRY(entry.VerifyChecksum(key, value));
David Rogersf0a35442020-02-04 12:16:38 -0800661
David Rogerscd87c322020-02-27 14:04:08 -0800662 // Find a new sector for the entry and write it to the new location. For
663 // relocation the find should not not be a sector already containing the key
664 // but can be the always empty sector, since this is part of the GC process
665 // that will result in a new empty sector. Also find a sector that does not
666 // have reclaimable space (mostly for the full GC, where that would result in
667 // an immediate extra relocation).
David Rogers8ce55cd2020-02-04 19:41:48 -0800668 SectorDescriptor* new_sector;
David Rogerscd87c322020-02-27 14:04:08 -0800669
David Rogersf56131c2020-03-04 10:19:22 -0800670 // Build a vector of sectors to avoid.
671 Vector<SectorDescriptor*, internal::kEntryRedundancy> old_sectors;
672 for (auto& address : key_descriptor.addresses()) {
673 old_sectors.push_back(SectorFromAddress(address));
674 }
675
676 // TODO: Remove this once const span can take a non-const span.
677 auto old_sectors_const =
678 span(const_cast<const SectorDescriptor**>(old_sectors.data()),
679 old_sectors.size());
680
David Rogerscd87c322020-02-27 14:04:08 -0800681 TRY(FindSectorWithSpace(
David Rogersf56131c2020-03-04 10:19:22 -0800682 &new_sector, entry.size(), kGarbageCollect, old_sectors_const));
683
684 // TODO: This does an entry with new transaction ID. This needs to get changed
685 // to be a copy of this entry with the same transaction ID.
Wyatt Heplerce7b8df2020-02-21 10:38:39 -0800686 TRY(AppendEntry(
687 new_sector, &key_descriptor, key, value, key_descriptor.state()));
David Rogersdf025cd2020-02-06 17:05:34 -0800688
Wyatt Heplerd2298282020-02-20 17:12:45 -0800689 // Do the valid bytes accounting for the sector the entry was relocated from.
David Rogersf56131c2020-03-04 10:19:22 -0800690 // TODO: AppendEntry() creates an entry with new transaction ID. While that is
691 // used all the old sectors need the valid bytes to be removed. Once it is
692 // switched over to do a copy of the current entry with the same transaction
693 // ID, then the valid bytes need to be removed from only the one sector being
694 // relocated out of.
695 // SectorFromAddress(address)->RemoveValidBytes(entry.size());
696 (void)address;
697 for (auto& old_sector : old_sectors) {
698 old_sector->RemoveValidBytes(entry.size());
699 }
David Rogersdf025cd2020-02-06 17:05:34 -0800700
701 return Status::OK;
David Rogersa12786b2020-01-31 16:02:33 -0800702}
703
David Rogers8db5a722020-02-03 18:28:34 -0800704// Find either an existing sector with enough space that is not the sector to
705// skip, or an empty sector. Maintains the invariant that there is always at
David Rogersc8fe1f52020-02-27 14:04:08 -0800706// least 1 empty sector except during GC. On GC, skip sectors that have
707// reclaimable bytes.
Wyatt Hepler5a33d8c2020-02-06 09:32:58 -0800708Status KeyValueStore::FindSectorWithSpace(
709 SectorDescriptor** found_sector,
710 size_t size,
David Rogersc8fe1f52020-02-27 14:04:08 -0800711 FindSectorMode find_mode,
712 span<const SectorDescriptor*> sectors_to_skip) {
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800713 SectorDescriptor* first_empty_sector = nullptr;
David Rogersc8fe1f52020-02-27 14:04:08 -0800714 bool at_least_two_empty_sectors = (find_mode == kGarbageCollect);
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800715
716 DBG("Find sector with %zu bytes available, starting with sector %u",
717 size,
718 SectorIndex(last_new_sector_));
David Rogerscd87c322020-02-27 14:04:08 -0800719 for (auto& skip_sector : sectors_to_skip) {
720 DBG(" Skip sector %u", SectorIndex(skip_sector));
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800721 }
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800722
David Rogers8ce55cd2020-02-04 19:41:48 -0800723 // The last_new_sector_ is the sector that was last selected as the "new empty
724 // sector" to write to. This last new sector is used as the starting point for
725 // the next "find a new empty sector to write to" operation. By using the last
726 // new sector as the start point we will cycle which empty sector is selected
727 // next, spreading the wear across all the empty sectors and get a wear
728 // leveling benefit, rather than putting more wear on the lower number
729 // sectors.
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800730 SectorDescriptor* sector = last_new_sector_;
David Rogers67f4b6c2020-02-06 16:17:09 -0800731
David Rogerscd87c322020-02-27 14:04:08 -0800732 // Look for a sector to use with enough space. The search uses a 2 priority
733 // tier process.
734 //
David Rogersc8fe1f52020-02-27 14:04:08 -0800735 // Tier 1 is sector that already has valid data. During GC only select a
736 // sector that has no reclaimable bytes. Immediately use the first matching
737 // sector that is found.
David Rogerscd87c322020-02-27 14:04:08 -0800738 //
David Rogersc8fe1f52020-02-27 14:04:08 -0800739 // Tier 2 is find sectors that are empty/erased. While scanning for a partial
740 // sector, keep track of the first empty sector and if a second empty sector
741 // was seen. If during GC then count the second empty sector as always seen.
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800742 for (size_t j = 0; j < sectors_.size(); j++) {
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800743 sector += 1;
744 if (sector == sectors_.end()) {
745 sector = sectors_.begin();
746 }
Keir Mierle8c352dc2020-02-02 13:58:19 -0800747
David Rogerscd87c322020-02-27 14:04:08 -0800748 if (std::find(sectors_to_skip.begin(), sectors_to_skip.end(), sector) !=
749 sectors_to_skip.end()) {
David Rogers8db5a722020-02-03 18:28:34 -0800750 continue;
751 }
752
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800753 const size_t sector_size_bytes = partition_.sector_size_bytes();
David Rogerscd87c322020-02-27 14:04:08 -0800754 if (!sector->Empty(sector_size_bytes) && sector->HasSpace(size) &&
David Rogersc8fe1f52020-02-27 14:04:08 -0800755 ((find_mode == kAppendEntry) ||
David Rogerscd87c322020-02-27 14:04:08 -0800756 (sector->RecoverableBytes(sector_size_bytes) == 0))) {
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800757 *found_sector = sector;
David Rogers8ce55cd2020-02-04 19:41:48 -0800758 return Status::OK;
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800759 }
760
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800761 if (sector->Empty(sector_size_bytes)) {
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800762 if (first_empty_sector == nullptr) {
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800763 first_empty_sector = sector;
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800764 } else {
765 at_least_two_empty_sectors = true;
Wyatt Hepler2ad60672020-01-21 08:00:16 -0800766 }
Wyatt Heplerb7609542020-01-24 10:29:54 -0800767 }
768 }
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800769
David Rogers8ce55cd2020-02-04 19:41:48 -0800770 // If the scan for a partial sector does not find a suitable sector, use the
771 // first empty sector that was found. Normally it is required to keep 1 empty
David Rogersc8fe1f52020-02-27 14:04:08 -0800772 // sector after the sector found here, but that rule does not apply during GC.
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800773 if (at_least_two_empty_sectors) {
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800774 DBG(" Found a usable empty sector; returning the first found (%u)",
David Rogers8ce55cd2020-02-04 19:41:48 -0800775 SectorIndex(first_empty_sector));
776 last_new_sector_ = first_empty_sector;
777 *found_sector = first_empty_sector;
778 return Status::OK;
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800779 }
David Rogers8ce55cd2020-02-04 19:41:48 -0800780
781 // No sector was found.
David Rogers67f4b6c2020-02-06 16:17:09 -0800782 DBG(" Unable to find a usable sector");
David Rogers8ce55cd2020-02-04 19:41:48 -0800783 *found_sector = nullptr;
784 return Status::RESOURCE_EXHAUSTED;
Wyatt Heplerb7609542020-01-24 10:29:54 -0800785}
786
David Rogers2761aeb2020-01-31 17:09:00 -0800787Status KeyValueStore::FindOrRecoverSectorWithSpace(SectorDescriptor** sector,
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800788 size_t size) {
David Rogersc8fe1f52020-02-27 14:04:08 -0800789 Status result = FindSectorWithSpace(sector, size, kAppendEntry);
David Rogers890acb52020-02-28 09:06:50 -0800790 if (result == Status::RESOURCE_EXHAUSTED &&
791 options_.gc_on_write != GargbageCollectOnWrite::kDisabled) {
David Rogers1541d612020-02-06 23:47:02 -0800792 // Garbage collect and then try again to find the best sector.
David Rogerscd87c322020-02-27 14:04:08 -0800793 TRY(GarbageCollectPartial());
David Rogersc8fe1f52020-02-27 14:04:08 -0800794 return FindSectorWithSpace(sector, size, kAppendEntry);
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800795 }
David Rogers8ce55cd2020-02-04 19:41:48 -0800796 return result;
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800797}
798
David Rogers2761aeb2020-01-31 17:09:00 -0800799KeyValueStore::SectorDescriptor* KeyValueStore::FindSectorToGarbageCollect() {
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800800 const size_t sector_size_bytes = partition_.sector_size_bytes();
David Rogers2761aeb2020-01-31 17:09:00 -0800801 SectorDescriptor* sector_candidate = nullptr;
David Rogersa12786b2020-01-31 16:02:33 -0800802 size_t candidate_bytes = 0;
803
804 // Step 1: Try to find a sectors with stale keys and no valid keys (no
805 // relocation needed). If any such sectors are found, use the sector with the
806 // most reclaimable bytes.
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800807 for (auto& sector : sectors_) {
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800808 if ((sector.valid_bytes() == 0) &&
809 (sector.RecoverableBytes(sector_size_bytes) > candidate_bytes)) {
David Rogersa12786b2020-01-31 16:02:33 -0800810 sector_candidate = &sector;
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800811 candidate_bytes = sector.RecoverableBytes(sector_size_bytes);
David Rogersa12786b2020-01-31 16:02:33 -0800812 }
813 }
814
815 // Step 2: If step 1 yields no sectors, just find the sector with the most
816 // reclaimable bytes.
817 if (sector_candidate == nullptr) {
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800818 for (auto& sector : sectors_) {
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800819 if (sector.RecoverableBytes(sector_size_bytes) > candidate_bytes) {
David Rogersa12786b2020-01-31 16:02:33 -0800820 sector_candidate = &sector;
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800821 candidate_bytes = sector.RecoverableBytes(sector_size_bytes);
David Rogersa12786b2020-01-31 16:02:33 -0800822 }
823 }
824 }
825
David Rogers5981f312020-02-13 13:33:56 -0800826 if (sector_candidate != nullptr) {
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800827 DBG("Found sector %u to Garbage Collect, %zu recoverable bytes",
David Rogers5981f312020-02-13 13:33:56 -0800828 SectorIndex(sector_candidate),
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800829 sector_candidate->RecoverableBytes(sector_size_bytes));
David Rogers5981f312020-02-13 13:33:56 -0800830 } else {
831 DBG("Unable to find sector to garbage collect!");
832 }
David Rogersa12786b2020-01-31 16:02:33 -0800833 return sector_candidate;
834}
835
David Rogerscd87c322020-02-27 14:04:08 -0800836Status KeyValueStore::GarbageCollectFull() {
837 DBG("Garbage Collect all sectors");
David Rogerscd87c322020-02-27 14:04:08 -0800838 SectorDescriptor* sector = last_new_sector_;
839
840 // TODO: look in to making an iterator method for cycling through sectors
841 // starting from last_new_sector_.
842 for (size_t j = 0; j < sectors_.size(); j++) {
843 sector += 1;
844 if (sector == sectors_.end()) {
845 sector = sectors_.begin();
846 }
847
848 if (sector->RecoverableBytes(partition_.sector_size_bytes()) > 0) {
849 TRY(GarbageCollectSector(sector));
850 }
851 }
852
853 DBG("Garbage Collect all complete");
David Rogerscd87c322020-02-27 14:04:08 -0800854 return Status::OK;
855}
856
857Status KeyValueStore::GarbageCollectPartial() {
David Rogers67f4b6c2020-02-06 16:17:09 -0800858 DBG("Garbage Collect a single sector");
859
David Rogersa12786b2020-01-31 16:02:33 -0800860 // Step 1: Find the sector to garbage collect
David Rogers2761aeb2020-01-31 17:09:00 -0800861 SectorDescriptor* sector_to_gc = FindSectorToGarbageCollect();
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800862
David Rogersa12786b2020-01-31 16:02:33 -0800863 if (sector_to_gc == nullptr) {
David Rogerscd87c322020-02-27 14:04:08 -0800864 // Nothing to GC, all done.
865 return Status::OK;
David Rogersa12786b2020-01-31 16:02:33 -0800866 }
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800867
David Rogerscd87c322020-02-27 14:04:08 -0800868 TRY(GarbageCollectSector(sector_to_gc));
David Rogerscd87c322020-02-27 14:04:08 -0800869 return Status::OK;
870}
871
872Status KeyValueStore::GarbageCollectSector(SectorDescriptor* sector_to_gc) {
873 // Step 1: Move any valid entries in the GC sector to other sectors
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800874 if (sector_to_gc->valid_bytes() != 0) {
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800875 for (auto& descriptor : key_descriptors_) {
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800876 if (AddressInSector(*sector_to_gc, descriptor.address())) {
David Rogers67f4b6c2020-02-06 16:17:09 -0800877 DBG(" Relocate entry");
David Rogersf56131c2020-03-04 10:19:22 -0800878 TRY(RelocateEntry(descriptor, descriptor.address()));
David Rogersa12786b2020-01-31 16:02:33 -0800879 }
Wyatt Heplerb7609542020-01-24 10:29:54 -0800880 }
881 }
Wyatt Heplerb7609542020-01-24 10:29:54 -0800882
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800883 if (sector_to_gc->valid_bytes() != 0) {
David Rogers67f4b6c2020-02-06 16:17:09 -0800884 ERR(" Failed to relocate valid entries from sector being garbage "
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800885 "collected, %zu valid bytes remain",
886 sector_to_gc->valid_bytes());
Wyatt Heplerb7609542020-01-24 10:29:54 -0800887 return Status::INTERNAL;
888 }
889
David Rogerscd87c322020-02-27 14:04:08 -0800890 // Step 2: Reinitialize the sector
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800891 sector_to_gc->set_writable_bytes(0);
David Rogersa12786b2020-01-31 16:02:33 -0800892 TRY(partition_.Erase(SectorBaseAddress(sector_to_gc), 1));
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800893 sector_to_gc->set_writable_bytes(partition_.sector_size_bytes());
Wyatt Heplerb7609542020-01-24 10:29:54 -0800894
David Rogerscd87c322020-02-27 14:04:08 -0800895 DBG(" Garbage Collect sector %u complete", SectorIndex(sector_to_gc));
David Rogersa12786b2020-01-31 16:02:33 -0800896 return Status::OK;
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800897}
898
David Rogers2761aeb2020-01-31 17:09:00 -0800899Status KeyValueStore::AppendEntry(SectorDescriptor* sector,
900 KeyDescriptor* key_descriptor,
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800901 string_view key,
Wyatt Hepler5a33d8c2020-02-06 09:32:58 -0800902 span<const byte> value,
903 KeyDescriptor::State new_state) {
Wyatt Heplere541e072020-02-14 09:10:53 -0800904 const Address address = NextWritableAddress(sector);
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800905 Entry entry = CreateEntry(address, key, value, new_state);
Wyatt Heplere541e072020-02-14 09:10:53 -0800906
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800907 DBG("Appending %zu B entry with transaction ID %" PRIu32 " to address %#zx",
Wyatt Heplere541e072020-02-14 09:10:53 -0800908 entry.size(),
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800909 entry.transaction_id(),
910 size_t(address));
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800911
David Rogers6592d292020-02-14 14:19:26 -0800912 StatusWithSize result = entry.Write(key, value);
913 // Remove any bytes that were written, even if the write was not successful.
Keir Mierle0a52aed2020-02-21 09:24:36 -0800914 // This is important to retain the writable space invariant on the sectors.
David Rogers6592d292020-02-14 14:19:26 -0800915 sector->RemoveWritableBytes(result.size());
916
917 if (!result.ok()) {
Keir Mierle0a52aed2020-02-21 09:24:36 -0800918 ERR("Failed to write %zu bytes at %" PRIx32 ". %zu actually written",
David Rogers6592d292020-02-14 14:19:26 -0800919 entry.size(),
Keir Mierle0a52aed2020-02-21 09:24:36 -0800920 address,
David Rogers6592d292020-02-14 14:19:26 -0800921 result.size());
922 return result.status();
923 }
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800924
925 if (options_.verify_on_write) {
Wyatt Hepler22d0d9f2020-03-05 14:57:11 -0800926 TRY(entry.VerifyChecksumInFlash());
Wyatt Heplerb7609542020-01-24 10:29:54 -0800927 }
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800928
Keir Mierle9e38b402020-02-21 13:06:21 -0800929 // Entry was written successfully; update the key descriptor and the sector
930 // descriptor to reflect the new entry.
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800931 entry.UpdateDescriptor(key_descriptor);
David Rogers6592d292020-02-14 14:19:26 -0800932 sector->AddValidBytes(result.size());
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800933 return Status::OK;
Wyatt Heplerb7609542020-01-24 10:29:54 -0800934}
935
Wyatt Heplerbdd8e5a2020-02-20 19:27:26 -0800936KeyValueStore::Entry KeyValueStore::CreateEntry(Address address,
937 std::string_view key,
938 span<const byte> value,
939 KeyDescriptor::State state) {
Keir Mierle9e38b402020-02-21 13:06:21 -0800940 // Always bump the transaction ID when creating a new entry.
941 //
942 // Burning transaction IDs prevents inconsistencies between flash and memory
943 // that which could happen if a write succeeds, but for some reason the read
944 // and verify step fails. Here's how this would happen:
945 //
946 // 1. The entry is written but for some reason the flash reports failure OR
947 // The write succeeds, but the read / verify operation fails.
948 // 2. The transaction ID is NOT incremented, because of the failure
949 // 3. (later) A new entry is written, re-using the transaction ID (oops)
950 //
951 // By always burning transaction IDs, the above problem can't happen.
952 last_transaction_id_ += 1;
953
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800954 if (state == KeyDescriptor::kDeleted) {
Wyatt Hepler7465be32020-02-21 15:30:53 -0800955 return Entry::Tombstone(
Wyatt Hepler22d0d9f2020-03-05 14:57:11 -0800956 partition_, address, formats_.primary(), key, last_transaction_id_);
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800957 }
958 return Entry::Valid(partition_,
959 address,
Wyatt Hepler22d0d9f2020-03-05 14:57:11 -0800960 formats_.primary(),
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800961 key,
962 value,
Keir Mierle9e38b402020-02-21 13:06:21 -0800963 last_transaction_id_);
Wyatt Heplerd2298282020-02-20 17:12:45 -0800964}
965
966void KeyValueStore::Reset() {
967 initialized_ = false;
968 key_descriptors_.clear();
969 last_new_sector_ = nullptr;
970 last_transaction_id_ = 0;
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800971}
972
Keir Mierle8c352dc2020-02-02 13:58:19 -0800973void KeyValueStore::LogDebugInfo() {
Keir Mierle8c352dc2020-02-02 13:58:19 -0800974 const size_t sector_size_bytes = partition_.sector_size_bytes();
975 DBG("====================== KEY VALUE STORE DUMP =========================");
976 DBG(" ");
977 DBG("Flash partition:");
Wyatt Heplerad0a7932020-02-06 08:20:38 -0800978 DBG(" Sector count = %zu", partition_.sector_count());
Wyatt Hepler38ce30f2020-02-19 11:48:31 -0800979 DBG(" Sector max count = %zu", sectors_.max_size());
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800980 DBG(" Sectors in use = %zu", sectors_.size());
Keir Mierle8c352dc2020-02-02 13:58:19 -0800981 DBG(" Sector size = %zu", sector_size_bytes);
982 DBG(" Total size = %zu", partition_.size_bytes());
983 DBG(" Alignment = %zu", partition_.alignment_bytes());
984 DBG(" ");
985 DBG("Key descriptors:");
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800986 DBG(" Entry count = %zu", key_descriptors_.size());
Wyatt Hepler38ce30f2020-02-19 11:48:31 -0800987 DBG(" Max entry count = %zu", key_descriptors_.max_size());
Keir Mierle8c352dc2020-02-02 13:58:19 -0800988 DBG(" ");
989 DBG(" # hash version address address (hex)");
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800990 for (size_t i = 0; i < key_descriptors_.size(); ++i) {
991 const KeyDescriptor& kd = key_descriptors_[i];
Keir Mierle8c352dc2020-02-02 13:58:19 -0800992 DBG(" |%3zu: | %8zx |%8zu | %8zu | %8zx",
993 i,
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800994 size_t(kd.hash()),
995 size_t(kd.transaction_id()),
996 size_t(kd.address()),
997 size_t(kd.address()));
Keir Mierle8c352dc2020-02-02 13:58:19 -0800998 }
999 DBG(" ");
1000
1001 DBG("Sector descriptors:");
1002 DBG(" # tail free valid has_space");
Wyatt Hepler1c329ca2020-02-07 18:07:23 -08001003 for (size_t sector_id = 0; sector_id < sectors_.size(); ++sector_id) {
1004 const SectorDescriptor& sd = sectors_[sector_id];
Keir Mierle8c352dc2020-02-02 13:58:19 -08001005 DBG(" |%3zu: | %8zu |%8zu | %s",
1006 sector_id,
Wyatt Hepler2c7eca02020-02-18 16:01:42 -08001007 size_t(sd.writable_bytes()),
1008 sd.valid_bytes(),
1009 sd.writable_bytes() ? "YES" : "");
Keir Mierle8c352dc2020-02-02 13:58:19 -08001010 }
1011 DBG(" ");
1012
1013 // TODO: This should stop logging after some threshold.
1014 // size_t dumped_bytes = 0;
1015 DBG("Sector raw data:");
Wyatt Hepler1c329ca2020-02-07 18:07:23 -08001016 for (size_t sector_id = 0; sector_id < sectors_.size(); ++sector_id) {
Keir Mierle8c352dc2020-02-02 13:58:19 -08001017 // Read sector data. Yes, this will blow the stack on embedded.
Wyatt Hepler1c329ca2020-02-07 18:07:23 -08001018 std::array<byte, 500> raw_sector_data; // TODO!!!
Keir Mierle8c352dc2020-02-02 13:58:19 -08001019 StatusWithSize sws =
1020 partition_.Read(sector_id * sector_size_bytes, raw_sector_data);
1021 DBG("Read: %zu bytes", sws.size());
1022
1023 DBG(" base addr offs 0 1 2 3 4 5 6 7");
1024 for (size_t i = 0; i < sector_size_bytes; i += 8) {
1025 DBG(" %3zu %8zx %5zu | %02x %02x %02x %02x %02x %02x %02x %02x",
1026 sector_id,
1027 (sector_id * sector_size_bytes) + i,
1028 i,
1029 static_cast<unsigned int>(raw_sector_data[i + 0]),
1030 static_cast<unsigned int>(raw_sector_data[i + 1]),
1031 static_cast<unsigned int>(raw_sector_data[i + 2]),
1032 static_cast<unsigned int>(raw_sector_data[i + 3]),
1033 static_cast<unsigned int>(raw_sector_data[i + 4]),
1034 static_cast<unsigned int>(raw_sector_data[i + 5]),
1035 static_cast<unsigned int>(raw_sector_data[i + 6]),
1036 static_cast<unsigned int>(raw_sector_data[i + 7]));
1037
1038 // TODO: Fix exit condition.
1039 if (i > 128) {
1040 break;
1041 }
1042 }
1043 DBG(" ");
1044 }
1045
1046 DBG("////////////////////// KEY VALUE STORE DUMP END /////////////////////");
1047}
1048
David Rogerscf680ab2020-02-12 23:28:32 -08001049void KeyValueStore::LogSectors() const {
1050 DBG("Sector descriptors: count %zu", sectors_.size());
Wyatt Hepler1c329ca2020-02-07 18:07:23 -08001051 for (auto& sector : sectors_) {
Wyatt Hepler2c7eca02020-02-18 16:01:42 -08001052 DBG(" - Sector %u: valid %zu, recoverable %zu, free %zu",
David Rogers50185ad2020-02-07 00:02:46 -08001053 SectorIndex(&sector),
Wyatt Hepler2c7eca02020-02-18 16:01:42 -08001054 sector.valid_bytes(),
1055 sector.RecoverableBytes(partition_.sector_size_bytes()),
1056 sector.writable_bytes());
David Rogers50185ad2020-02-07 00:02:46 -08001057 }
1058}
1059
David Rogerscf680ab2020-02-12 23:28:32 -08001060void KeyValueStore::LogKeyDescriptor() const {
1061 DBG("Key descriptors: count %zu", key_descriptors_.size());
1062 for (auto& key : key_descriptors_) {
Wyatt Hepler1fc11042020-02-19 17:17:51 -08001063 DBG(" - Key: %s, hash %#zx, transaction ID %zu, address %#zx",
David Rogerscf680ab2020-02-12 23:28:32 -08001064 key.deleted() ? "Deleted" : "Valid",
Wyatt Hepler1fc11042020-02-19 17:17:51 -08001065 static_cast<size_t>(key.hash()),
1066 static_cast<size_t>(key.transaction_id()),
1067 static_cast<size_t>(key.address()));
David Rogerscf680ab2020-02-12 23:28:32 -08001068 }
1069}
1070
Wyatt Hepler2ad60672020-01-21 08:00:16 -08001071} // namespace pw::kvs