blob: 45bf2e494a1ada4b4f572c9432c57dbe57139eb3 [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;
David Rogers91627482020-02-27 17:38:12 -080082 bool empty_sector_found = false;
Alexei Frolovd4adf912020-02-21 13:29:15 -080083
Wyatt Hepler2c7eca02020-02-18 16:01:42 -080084 for (SectorDescriptor& sector : sectors_) {
Keir Mierle8c352dc2020-02-02 13:58:19 -080085 Address entry_address = sector_address;
86
Alexei Frolovd4adf912020-02-21 13:29:15 -080087 size_t sector_corrupt_bytes = 0;
88
Wyatt Hepler2c7eca02020-02-18 16:01:42 -080089 for (int num_entries_in_sector = 0; true; num_entries_in_sector++) {
90 DBG("Load entry: sector=%" PRIx32 ", entry#=%d, address=%" PRIx32,
91 sector_address,
Keir Mierle8c352dc2020-02-02 13:58:19 -080092 num_entries_in_sector,
Wyatt Hepler2c7eca02020-02-18 16:01:42 -080093 entry_address);
Keir Mierle8c352dc2020-02-02 13:58:19 -080094
Wyatt Hepler2c7eca02020-02-18 16:01:42 -080095 if (!AddressInSector(sector, entry_address)) {
Keir Mierle8c352dc2020-02-02 13:58:19 -080096 DBG("Fell off end of sector; moving to the next sector");
97 break;
98 }
99
100 Address next_entry_address;
101 Status status = LoadEntry(entry_address, &next_entry_address);
102 if (status == Status::NOT_FOUND) {
103 DBG("Hit un-written data in sector; moving to the next sector");
104 break;
105 }
106 if (status == Status::DATA_LOSS) {
Alexei Frolovd4adf912020-02-21 13:29:15 -0800107 // The entry could not be read, indicating data corruption within the
108 // sector. Try to scan the remainder of the sector for other entries.
109 ERR("KVS init: data loss detected in sector %u at address %zu",
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800110 SectorIndex(&sector),
111 size_t(entry_address));
Alexei Frolovd4adf912020-02-21 13:29:15 -0800112
113 corrupt_entries++;
114
115 status = ScanForEntry(sector,
116 entry_address + Entry::kMinAlignmentBytes,
117 &next_entry_address);
118 if (status == Status::NOT_FOUND) {
119 // No further entries in this sector. Mark the remaining bytes in the
120 // sector as corrupt (since we can't reliably know the size of the
121 // corrupt entry).
122 sector_corrupt_bytes +=
123 sector_size_bytes - (entry_address - sector_address);
124 break;
125 }
126
127 if (!status.ok()) {
128 ERR("Unexpected error in KVS initialization: %s", status.str());
129 return Status::UNKNOWN;
130 }
131
132 sector_corrupt_bytes += next_entry_address - entry_address;
133 } else if (!status.ok()) {
134 ERR("Unexpected error in KVS initialization: %s", status.str());
135 return Status::UNKNOWN;
Keir Mierle8c352dc2020-02-02 13:58:19 -0800136 }
Keir Mierle8c352dc2020-02-02 13:58:19 -0800137
138 // Entry loaded successfully; so get ready to load the next one.
139 entry_address = next_entry_address;
140
141 // Update of the number of writable bytes in this sector.
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800142 sector.set_writable_bytes(sector_size_bytes -
143 (entry_address - sector_address));
Keir Mierle8c352dc2020-02-02 13:58:19 -0800144 }
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800145
Alexei Frolovd4adf912020-02-21 13:29:15 -0800146 if (sector_corrupt_bytes > 0) {
147 // If the sector contains corrupt data, prevent any further entries from
148 // being written to it by indicating that it has no space. This should
149 // also make it a decent GC candidate. Valid keys in the sector are still
150 // readable as normal.
151 sector.set_writable_bytes(0);
152
153 WRN("Sector %u contains %zuB of corrupt data",
154 SectorIndex(&sector),
155 sector_corrupt_bytes);
156 }
157
David Rogers91627482020-02-27 17:38:12 -0800158 if (sector.Empty(sector_size_bytes)) {
159 empty_sector_found = true;
160 }
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800161 sector_address += sector_size_bytes;
Alexei Frolovd4adf912020-02-21 13:29:15 -0800162 total_corrupt_bytes += sector_corrupt_bytes;
Keir Mierle8c352dc2020-02-02 13:58:19 -0800163 }
164
165 DBG("Second pass: Count valid bytes in each sector");
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800166 const KeyDescriptor* newest_key = nullptr;
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800167
Keir Mierle8c352dc2020-02-02 13:58:19 -0800168 // For every valid key, increment the valid bytes for that sector.
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800169 for (KeyDescriptor& key_descriptor : key_descriptors_) {
Wyatt Heplere541e072020-02-14 09:10:53 -0800170 Entry entry;
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800171 TRY(Entry::Read(partition_, key_descriptor.address(), &entry));
172 SectorFromKey(key_descriptor)->AddValidBytes(entry.size());
173
174 if (key_descriptor.IsNewerThan(last_transaction_id_)) {
175 last_transaction_id_ = key_descriptor.transaction_id();
176 newest_key = &key_descriptor;
177 }
Keir Mierle8c352dc2020-02-02 13:58:19 -0800178 }
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800179
180 if (newest_key == nullptr) {
181 last_new_sector_ = sectors_.begin();
182 } else {
183 last_new_sector_ = SectorFromKey(newest_key);
184 }
185
David Rogers91627482020-02-27 17:38:12 -0800186 if (!empty_sector_found) {
187 // TODO: Record/report the error condition and recovery result.
188 Status gc_result = GarbageCollectPartial();
189
190 if (!gc_result.ok()) {
191 ERR("KVS init failed: Unable to maintain required free sector");
192 return Status::INTERNAL;
193 }
194 }
195
Wyatt Hepler729f28c2020-02-05 09:46:00 -0800196 initialized_ = true;
David Rogers2e9e0c82020-02-13 15:06:06 -0800197
Armando Montanez5464d5f2020-02-20 10:12:20 -0800198 INF("KeyValueStore init complete: active keys %zu, deleted keys %zu, sectors "
David Rogers2e9e0c82020-02-13 15:06:06 -0800199 "%zu, logical sector size %zu bytes",
200 size(),
201 (key_descriptors_.size() - size()),
202 sectors_.size(),
203 partition_.sector_size_bytes());
204
Alexei Frolovd4adf912020-02-21 13:29:15 -0800205 if (total_corrupt_bytes > 0) {
206 WRN("Found %zu corrupt bytes and %d corrupt entries during init process; "
207 "some keys may be missing",
208 total_corrupt_bytes,
209 corrupt_entries);
210 return Status::DATA_LOSS;
211 }
212
Keir Mierle8c352dc2020-02-02 13:58:19 -0800213 return Status::OK;
214}
215
Alexei Frolov9e235832020-02-24 12:44:45 -0800216KeyValueStore::StorageStats KeyValueStore::GetStorageStats() const {
217 StorageStats stats{0, 0, 0};
218 const size_t sector_size = partition_.sector_size_bytes();
219 bool found_empty_sector = false;
220
221 for (const SectorDescriptor& sector : sectors_) {
222 stats.in_use_bytes += sector.valid_bytes();
223 stats.reclaimable_bytes += sector.RecoverableBytes(sector_size);
224
225 if (!found_empty_sector && sector.Empty(sector_size)) {
226 // The KVS tries to always keep an empty sector for GC, so don't count
227 // the first empty sector seen as writable space. However, a free sector
228 // cannot always be assumed to exist; if a GC operation fails, all sectors
229 // may be partially written, in which case the space reported might be
230 // inaccurate.
231 found_empty_sector = true;
232 continue;
233 }
234
235 stats.writable_bytes += sector.writable_bytes();
236 }
237
238 return stats;
239}
240
Keir Mierle8c352dc2020-02-02 13:58:19 -0800241Status KeyValueStore::LoadEntry(Address entry_address,
242 Address* next_entry_address) {
Wyatt Heplere541e072020-02-14 09:10:53 -0800243 Entry entry;
244 TRY(Entry::Read(partition_, entry_address, &entry));
Keir Mierle8c352dc2020-02-02 13:58:19 -0800245
246 // TODO: Handle multiple magics for formats that have changed.
Wyatt Heplere541e072020-02-14 09:10:53 -0800247 if (entry.magic() != entry_header_format_.magic) {
Keir Mierle8c352dc2020-02-02 13:58:19 -0800248 // TODO: It may be cleaner to have some logging helpers for these cases.
Wyatt Heplere541e072020-02-14 09:10:53 -0800249 ERR("Found corrupt magic: %zx; expecting %zx; at address %zx",
250 size_t(entry.magic()),
Keir Mierle8c352dc2020-02-02 13:58:19 -0800251 size_t(entry_header_format_.magic),
252 size_t(entry_address));
253 return Status::DATA_LOSS;
254 }
255
256 // Read the key from flash & validate the entry (which reads the value).
Wyatt Heplera00d1ef2020-02-14 14:31:26 -0800257 Entry::KeyBuffer key_buffer;
Wyatt Heplere541e072020-02-14 09:10:53 -0800258 TRY_ASSIGN(size_t key_length, entry.ReadKey(key_buffer));
259 const string_view key(key_buffer.data(), key_length);
Wyatt Heplerbab0e202020-02-04 07:40:08 -0800260
Wyatt Heplere541e072020-02-14 09:10:53 -0800261 TRY(entry.VerifyChecksumInFlash(entry_header_format_.checksum));
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800262 TRY(AppendNewOrOverwriteStaleExistingDescriptor(entry.descriptor(key)));
Keir Mierle8c352dc2020-02-02 13:58:19 -0800263
Wyatt Heplere541e072020-02-14 09:10:53 -0800264 *next_entry_address = entry.next_address();
Keir Mierle8c352dc2020-02-02 13:58:19 -0800265 return Status::OK;
266}
267
Alexei Frolovd4adf912020-02-21 13:29:15 -0800268// Scans flash memory within a sector to find a KVS entry magic.
Alexei Frolovd4adf912020-02-21 13:29:15 -0800269Status KeyValueStore::ScanForEntry(const SectorDescriptor& sector,
270 Address start_address,
271 Address* next_entry_address) {
272 DBG("Scanning sector %u for entries starting from address %zx",
273 SectorIndex(&sector),
274 size_t(start_address));
275
276 // Entries must start at addresses which are aligned on a multiple of
277 // Entry::kMinAlignmentBytes. However, that multiple can vary between entries.
278 // When scanning, we don't have an entry to tell us what the current alignment
279 // is, so the minimum alignment is used to be exhaustive.
280 for (Address address = AlignUp(start_address, Entry::kMinAlignmentBytes);
281 AddressInSector(sector, address);
282 address += Entry::kMinAlignmentBytes) {
283 // TODO: Handle multiple magics for formats that have changed.
284 uint32_t magic;
285 TRY(partition_.Read(address, as_writable_bytes(span(&magic, 1))));
286 if (magic == entry_header_format_.magic) {
287 DBG("Found entry magic at address %zx", size_t(address));
288 *next_entry_address = address;
289 return Status::OK;
290 }
291 }
292
293 return Status::NOT_FOUND;
294}
295
Keir Mierle8c352dc2020-02-02 13:58:19 -0800296// TODO: This method is the trigger of the O(valid_entries * all_entries) time
297// complexity for reading. At some cost to memory, this could be optimized by
298// using a hash table instead of scanning, but in practice this should be fine
299// for a small number of keys
300Status KeyValueStore::AppendNewOrOverwriteStaleExistingDescriptor(
301 const KeyDescriptor& key_descriptor) {
302 // With the new key descriptor, either add it to the descriptor table or
303 // overwrite an existing entry with an older version of the key.
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800304 KeyDescriptor* existing_descriptor = FindDescriptor(key_descriptor.hash());
Keir Mierle8c352dc2020-02-02 13:58:19 -0800305
Wyatt Hepler5406a672020-02-18 15:42:38 -0800306 // Write a new entry.
307 if (existing_descriptor == nullptr) {
308 if (key_descriptors_.full()) {
309 return Status::RESOURCE_EXHAUSTED;
310 }
311 key_descriptors_.push_back(key_descriptor);
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800312 } else if (key_descriptor.IsNewerThan(
313 existing_descriptor->transaction_id())) {
Wyatt Hepler5406a672020-02-18 15:42:38 -0800314 // Existing entry is old; replace the existing entry with the new one.
315 *existing_descriptor = key_descriptor;
316 } else {
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800317 // Otherwise, check if the entries have a duplicate transaction ID, which is
318 // not valid.
319 if (existing_descriptor->transaction_id() ==
320 key_descriptor.transaction_id()) {
321 ERR("Data loss: Duplicated old(=%zu) and new(=%zu) transaction ID",
322 size_t(existing_descriptor->transaction_id()),
323 size_t(key_descriptor.transaction_id()));
Wyatt Hepler5406a672020-02-18 15:42:38 -0800324 return Status::DATA_LOSS;
325 }
326 DBG("Found stale entry when appending; ignoring");
Keir Mierle8c352dc2020-02-02 13:58:19 -0800327 }
Keir Mierle8c352dc2020-02-02 13:58:19 -0800328 return Status::OK;
329}
330
Keir Mierle8c352dc2020-02-02 13:58:19 -0800331KeyValueStore::KeyDescriptor* KeyValueStore::FindDescriptor(uint32_t hash) {
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800332 for (KeyDescriptor& key_descriptor : key_descriptors_) {
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800333 if (key_descriptor.hash() == hash) {
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800334 return &key_descriptor;
Keir Mierle8c352dc2020-02-02 13:58:19 -0800335 }
336 }
337 return nullptr;
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800338}
339
340StatusWithSize KeyValueStore::Get(string_view key,
Wyatt Hepler5f6efc02020-02-18 16:54:31 -0800341 span<byte> value_buffer,
342 size_t offset_bytes) const {
Wyatt Hepler50f70772020-02-13 11:25:10 -0800343 TRY_WITH_SIZE(CheckOperation(key));
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800344
David Rogers2761aeb2020-01-31 17:09:00 -0800345 const KeyDescriptor* key_descriptor;
Wyatt Hepler2d401692020-02-13 16:01:23 -0800346 TRY_WITH_SIZE(FindExistingKeyDescriptor(key, &key_descriptor));
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800347
Wyatt Heplere541e072020-02-14 09:10:53 -0800348 Entry entry;
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800349 TRY_WITH_SIZE(Entry::Read(partition_, key_descriptor->address(), &entry));
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800350
Wyatt Hepler5f6efc02020-02-18 16:54:31 -0800351 StatusWithSize result = entry.ReadValue(value_buffer, offset_bytes);
352 if (result.ok() && options_.verify_on_read && offset_bytes == 0u) {
Wyatt Heplerce7b8df2020-02-21 10:38:39 -0800353 Status verify_result = entry.VerifyChecksum(
354 entry_header_format_.checksum, key, value_buffer.first(result.size()));
David Rogerscf680ab2020-02-12 23:28:32 -0800355 if (!verify_result.ok()) {
Wyatt Heplerce7b8df2020-02-21 10:38:39 -0800356 std::memset(value_buffer.data(), 0, result.size());
Wyatt Heplerf7078802020-02-25 13:50:05 -0800357 return StatusWithSize(verify_result, 0);
David Rogerscf680ab2020-02-12 23:28:32 -0800358 }
359
360 return StatusWithSize(verify_result, result.size());
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800361 }
362 return result;
363}
364
365Status KeyValueStore::Put(string_view key, span<const byte> value) {
Keir Mierle8c352dc2020-02-02 13:58:19 -0800366 DBG("Writing key/value; key length=%zu, value length=%zu",
367 key.size(),
368 value.size());
Wyatt Hepler729f28c2020-02-05 09:46:00 -0800369
370 TRY(CheckOperation(key));
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800371
Wyatt Hepler5406a672020-02-18 15:42:38 -0800372 if (Entry::size(partition_, key, value) > partition_.sector_size_bytes()) {
373 DBG("%zu B value with %zu B key cannot fit in one sector",
374 value.size(),
375 key.size());
376 return Status::INVALID_ARGUMENT;
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800377 }
378
David Rogers2761aeb2020-01-31 17:09:00 -0800379 KeyDescriptor* key_descriptor;
Wyatt Hepler2d401692020-02-13 16:01:23 -0800380 Status status = FindKeyDescriptor(key, &key_descriptor);
381
382 if (status.ok()) {
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800383 DBG("Overwriting entry for key %#08" PRIx32 " in sector %u",
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800384 key_descriptor->hash(),
385 SectorIndex(SectorFromKey(key_descriptor)));
Wyatt Hepler5a33d8c2020-02-06 09:32:58 -0800386 return WriteEntryForExistingKey(
387 key_descriptor, KeyDescriptor::kValid, key, value);
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800388 }
David Rogers2761aeb2020-01-31 17:09:00 -0800389
Wyatt Hepler2d401692020-02-13 16:01:23 -0800390 if (status == Status::NOT_FOUND) {
391 return WriteEntryForNewKey(key, value);
392 }
393
394 return status;
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800395}
396
397Status KeyValueStore::Delete(string_view key) {
Wyatt Hepler729f28c2020-02-05 09:46:00 -0800398 TRY(CheckOperation(key));
399
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800400 KeyDescriptor* key_descriptor;
Wyatt Hepler2d401692020-02-13 16:01:23 -0800401 TRY(FindExistingKeyDescriptor(key, &key_descriptor));
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800402
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800403 DBG("Writing tombstone for key %#08" PRIx32 " in sector %u",
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800404 key_descriptor->hash(),
405 SectorIndex(SectorFromKey(key_descriptor)));
Wyatt Hepler5a33d8c2020-02-06 09:32:58 -0800406 return WriteEntryForExistingKey(
407 key_descriptor, KeyDescriptor::kDeleted, key, {});
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800408}
409
Wyatt Hepler08d37d82020-02-27 15:45:37 -0800410void KeyValueStore::Item::ReadKey() {
411 key_buffer_.fill('\0');
412
413 Entry entry;
414 if (Entry::Read(kvs_.partition_, descriptor_->address(), &entry).ok()) {
415 entry.ReadKey(key_buffer_);
416 }
417}
418
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800419KeyValueStore::iterator& KeyValueStore::iterator::operator++() {
420 // Skip to the next entry that is valid (not deleted).
Wyatt Hepler08d37d82020-02-27 15:45:37 -0800421 while (++item_.descriptor_ != item_.kvs_.key_descriptors_.end() &&
422 item_.descriptor_->deleted()) {
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800423 }
424 return *this;
425}
426
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800427KeyValueStore::iterator KeyValueStore::begin() const {
Wyatt Hepler08d37d82020-02-27 15:45:37 -0800428 const KeyDescriptor* descriptor = key_descriptors_.begin();
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800429 // Skip over any deleted entries at the start of the descriptor list.
Wyatt Hepler08d37d82020-02-27 15:45:37 -0800430 while (descriptor != key_descriptors_.end() && descriptor->deleted()) {
431 ++descriptor;
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800432 }
Wyatt Hepler08d37d82020-02-27 15:45:37 -0800433 return iterator(*this, descriptor);
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800434}
435
436// TODO(hepler): The valid entry count could be tracked in the KVS to avoid the
437// need for this for-loop.
438size_t KeyValueStore::size() const {
439 size_t valid_entries = 0;
440
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800441 for (const KeyDescriptor& key_descriptor : key_descriptors_) {
442 if (!key_descriptor.deleted()) {
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800443 valid_entries += 1;
444 }
445 }
446
447 return valid_entries;
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800448}
449
Wyatt Heplered163b02020-02-03 17:49:32 -0800450StatusWithSize KeyValueStore::ValueSize(std::string_view key) const {
Wyatt Hepler50f70772020-02-13 11:25:10 -0800451 TRY_WITH_SIZE(CheckOperation(key));
Wyatt Heplered163b02020-02-03 17:49:32 -0800452
453 const KeyDescriptor* key_descriptor;
Wyatt Hepler2d401692020-02-13 16:01:23 -0800454 TRY_WITH_SIZE(FindExistingKeyDescriptor(key, &key_descriptor));
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800455
Wyatt Heplere541e072020-02-14 09:10:53 -0800456 Entry entry;
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800457 TRY_WITH_SIZE(Entry::Read(partition_, key_descriptor->address(), &entry));
Wyatt Heplered163b02020-02-03 17:49:32 -0800458
Wyatt Heplere541e072020-02-14 09:10:53 -0800459 return StatusWithSize(entry.value_size());
Wyatt Heplered163b02020-02-03 17:49:32 -0800460}
461
Wyatt Hepler6e3a83b2020-02-04 07:36:45 -0800462Status KeyValueStore::FixedSizeGet(std::string_view key,
463 byte* value,
464 size_t size_bytes) const {
465 // Ensure that the size of the stored value matches the size of the type.
466 // Otherwise, report error. This check avoids potential memory corruption.
467 StatusWithSize result = ValueSize(key);
468 if (!result.ok()) {
469 return result.status();
Keir Mierle8c352dc2020-02-02 13:58:19 -0800470 }
Wyatt Hepler6e3a83b2020-02-04 07:36:45 -0800471 if (result.size() != size_bytes) {
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800472 DBG("Requested %zu B read, but value is %zu B", size_bytes, result.size());
Wyatt Hepler6e3a83b2020-02-04 07:36:45 -0800473 return Status::INVALID_ARGUMENT;
Wyatt Heplerbab0e202020-02-04 07:40:08 -0800474 }
Wyatt Hepler6e3a83b2020-02-04 07:36:45 -0800475 return Get(key, span(value, size_bytes)).status();
Keir Mierle8c352dc2020-02-02 13:58:19 -0800476}
477
Wyatt Hepler729f28c2020-02-05 09:46:00 -0800478Status KeyValueStore::CheckOperation(string_view key) const {
Wyatt Hepleracaacf92020-01-24 10:58:30 -0800479 if (InvalidKey(key)) {
Wyatt Heplerb7609542020-01-24 10:29:54 -0800480 return Status::INVALID_ARGUMENT;
481 }
Wyatt Heplerd2298282020-02-20 17:12:45 -0800482 if (!initialized()) {
Wyatt Heplerb7609542020-01-24 10:29:54 -0800483 return Status::FAILED_PRECONDITION;
484 }
Wyatt Heplerb7609542020-01-24 10:29:54 -0800485 return Status::OK;
486}
487
Wyatt Hepler2d401692020-02-13 16:01:23 -0800488// Searches for a KeyDescriptor that matches this key and sets *result to point
489// to it if one is found.
490//
491// OK: there is a matching descriptor and *result is set
492// NOT_FOUND: there is no descriptor that matches this key, but this key
493// has a unique hash (and could potentially be added to the KVS)
494// ALREADY_EXISTS: there is no descriptor that matches this key, but the
495// key's hash collides with the hash for an existing descriptor
496//
David Rogers2761aeb2020-01-31 17:09:00 -0800497Status KeyValueStore::FindKeyDescriptor(string_view key,
498 const KeyDescriptor** result) const {
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800499 const uint32_t hash = internal::Hash(key);
Wyatt Heplera00d1ef2020-02-14 14:31:26 -0800500 Entry::KeyBuffer key_buffer;
Wyatt Heplerb7609542020-01-24 10:29:54 -0800501
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800502 for (auto& descriptor : key_descriptors_) {
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800503 if (descriptor.hash() == hash) {
Wyatt Heplere541e072020-02-14 09:10:53 -0800504 TRY(Entry::ReadKey(
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800505 partition_, descriptor.address(), key.size(), key_buffer.data()));
Wyatt Heplerb7609542020-01-24 10:29:54 -0800506
Wyatt Heplere541e072020-02-14 09:10:53 -0800507 if (key == string_view(key_buffer.data(), key.size())) {
Wyatt Hepler5a33d8c2020-02-06 09:32:58 -0800508 DBG("Found match for key hash 0x%08" PRIx32, hash);
David Rogers2761aeb2020-01-31 17:09:00 -0800509 *result = &descriptor;
Wyatt Heplerb7609542020-01-24 10:29:54 -0800510 return Status::OK;
Wyatt Hepler2d401692020-02-13 16:01:23 -0800511 } else {
512 WRN("Found key hash collision for 0x%08" PRIx32, hash);
513 return Status::ALREADY_EXISTS;
Wyatt Heplerb7609542020-01-24 10:29:54 -0800514 }
Wyatt Heplerb7609542020-01-24 10:29:54 -0800515 }
516 }
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800517 return Status::NOT_FOUND;
518}
519
Wyatt Hepler2d401692020-02-13 16:01:23 -0800520// Searches for a KeyDescriptor that matches this key and sets *result to point
521// to it if one is found.
522//
523// OK: there is a matching descriptor and *result is set
524// NOT_FOUND: there is no descriptor that matches this key
525//
526Status KeyValueStore::FindExistingKeyDescriptor(
527 string_view key, const KeyDescriptor** result) const {
528 Status status = FindKeyDescriptor(key, result);
529
530 // If the key's hash collides with an existing key or if the key is deleted,
531 // treat it as if it is not in the KVS.
532 if (status == Status::ALREADY_EXISTS ||
533 (status.ok() && (*result)->deleted())) {
534 return Status::NOT_FOUND;
535 }
536 return status;
537}
538
David Rogers2761aeb2020-01-31 17:09:00 -0800539Status KeyValueStore::WriteEntryForExistingKey(KeyDescriptor* key_descriptor,
Wyatt Hepler5a33d8c2020-02-06 09:32:58 -0800540 KeyDescriptor::State new_state,
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800541 string_view key,
542 span<const byte> value) {
Wyatt Hepler5a33d8c2020-02-06 09:32:58 -0800543 // Find the original entry and sector to update the sector's valid_bytes.
Wyatt Hepler30a52152020-02-12 11:26:05 -0800544 Entry original_entry;
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800545 TRY(Entry::Read(partition_, key_descriptor->address(), &original_entry));
546 SectorDescriptor* old_sector = SectorFromKey(key_descriptor);
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800547
David Rogers2761aeb2020-01-31 17:09:00 -0800548 SectorDescriptor* sector;
Wyatt Hepler5406a672020-02-18 15:42:38 -0800549 TRY(FindOrRecoverSectorWithSpace(&sector,
550 Entry::size(partition_, key, value)));
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800551 DBG("Writing existing entry; found sector %u (%#" PRIx32 ")",
552 SectorIndex(sector),
553 SectorBaseAddress(sector));
David Rogers3464d0a2020-02-07 11:45:46 -0800554
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800555 if (old_sector != SectorFromKey(key_descriptor)) {
David Rogers3464d0a2020-02-07 11:45:46 -0800556 DBG("Sector for old entry (size %zu) was garbage collected. Old entry "
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800557 "relocated to sector %u",
David Rogers3464d0a2020-02-07 11:45:46 -0800558 original_entry.size(),
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800559 SectorIndex(SectorFromKey(key_descriptor)));
David Rogers3464d0a2020-02-07 11:45:46 -0800560
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800561 old_sector = SectorFromKey(key_descriptor);
David Rogers3464d0a2020-02-07 11:45:46 -0800562 }
563
Wyatt Hepler5a33d8c2020-02-06 09:32:58 -0800564 TRY(AppendEntry(sector, key_descriptor, key, value, new_state));
565
David Rogers3464d0a2020-02-07 11:45:46 -0800566 old_sector->RemoveValidBytes(original_entry.size());
Wyatt Hepler5a33d8c2020-02-06 09:32:58 -0800567 return Status::OK;
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800568}
569
570Status KeyValueStore::WriteEntryForNewKey(string_view key,
571 span<const byte> value) {
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800572 if (key_descriptors_.full()) {
Keir Mierle8c352dc2020-02-02 13:58:19 -0800573 WRN("KVS full: trying to store a new entry, but can't. Have %zu entries",
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800574 key_descriptors_.size());
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800575 return Status::RESOURCE_EXHAUSTED;
576 }
577
David Rogers2761aeb2020-01-31 17:09:00 -0800578 SectorDescriptor* sector;
Wyatt Hepler5406a672020-02-18 15:42:38 -0800579 TRY(FindOrRecoverSectorWithSpace(&sector,
580 Entry::size(partition_, key, value)));
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800581 DBG("Writing new entry; found sector: %u", SectorIndex(sector));
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800582
583 // Create the KeyDescriptor that will be added to the list. The transaction ID
584 // and address will be set by AppendEntry.
585 KeyDescriptor key_descriptor(key);
Wyatt Hepler0af6ad92020-02-13 15:54:46 -0800586 TRY(AppendEntry(sector, &key_descriptor, key, value, KeyDescriptor::kValid));
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800587
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800588 // Only add the entry when we are certain the write succeeded.
589 key_descriptors_.push_back(key_descriptor);
Wyatt Heplerb7609542020-01-24 10:29:54 -0800590 return Status::OK;
591}
592
David Rogers2761aeb2020-01-31 17:09:00 -0800593Status KeyValueStore::RelocateEntry(KeyDescriptor& key_descriptor) {
David Rogersf0a35442020-02-04 12:16:38 -0800594 struct TempEntry {
Wyatt Heplere541e072020-02-14 09:10:53 -0800595 Entry::KeyBuffer key;
Wyatt Heplerce7b8df2020-02-21 10:38:39 -0800596 std::array<byte, sizeof(working_buffer_) - sizeof(key)> value;
David Rogersf0a35442020-02-04 12:16:38 -0800597 };
Wyatt Heplerce7b8df2020-02-21 10:38:39 -0800598 auto [key_buffer, value_buffer] =
599 *std::launder(reinterpret_cast<TempEntry*>(working_buffer_.data()));
David Rogersf0a35442020-02-04 12:16:38 -0800600
Wyatt Heplerce7b8df2020-02-21 10:38:39 -0800601 DBG("Relocating entry at %zx for key %" PRIx32,
602 size_t(key_descriptor.address()),
603 key_descriptor.hash());
David Rogersdf025cd2020-02-06 17:05:34 -0800604
Wyatt Heplere541e072020-02-14 09:10:53 -0800605 // Read the entry to be relocated. Store the entry in a local variable and
David Rogersf0a35442020-02-04 12:16:38 -0800606 // store the key and value in the TempEntry stored in the static allocated
607 // working_buffer_.
Wyatt Heplere541e072020-02-14 09:10:53 -0800608 Entry entry;
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800609 TRY(Entry::Read(partition_, key_descriptor.address(), &entry));
Wyatt Heplerce7b8df2020-02-21 10:38:39 -0800610
611 TRY_ASSIGN(size_t key_length, entry.ReadKey(key_buffer));
612 string_view key = string_view(key_buffer.data(), key_length);
613
614 StatusWithSize result = entry.ReadValue(value_buffer);
615 if (!result.ok()) {
David Rogersf0a35442020-02-04 12:16:38 -0800616 return Status::INTERNAL;
617 }
618
Wyatt Heplerce7b8df2020-02-21 10:38:39 -0800619 const span value = span(value_buffer.data(), result.size());
620 TRY(entry.VerifyChecksum(entry_header_format_.checksum, key, value));
David Rogersf0a35442020-02-04 12:16:38 -0800621
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800622 SectorDescriptor* old_sector = SectorFromKey(key_descriptor);
David Rogersf0a35442020-02-04 12:16:38 -0800623
David Rogerscd87c322020-02-27 14:04:08 -0800624 // Find a new sector for the entry and write it to the new location. For
625 // relocation the find should not not be a sector already containing the key
626 // but can be the always empty sector, since this is part of the GC process
627 // that will result in a new empty sector. Also find a sector that does not
628 // have reclaimable space (mostly for the full GC, where that would result in
629 // an immediate extra relocation).
David Rogers8ce55cd2020-02-04 19:41:48 -0800630 SectorDescriptor* new_sector;
David Rogerscd87c322020-02-27 14:04:08 -0800631
632 // TODO: For redundancy work, replace old_sector_const with a span of sectors
633 // to avoid.
634 const SectorDescriptor* old_sector_const = old_sector;
635 TRY(FindSectorWithSpace(
636 &new_sector, entry.size(), span(&old_sector_const, 1), true, false));
Wyatt Heplerce7b8df2020-02-21 10:38:39 -0800637 TRY(AppendEntry(
638 new_sector, &key_descriptor, key, value, key_descriptor.state()));
David Rogersdf025cd2020-02-06 17:05:34 -0800639
Wyatt Heplerd2298282020-02-20 17:12:45 -0800640 // Do the valid bytes accounting for the sector the entry was relocated from.
Wyatt Heplere541e072020-02-14 09:10:53 -0800641 old_sector->RemoveValidBytes(entry.size());
David Rogersdf025cd2020-02-06 17:05:34 -0800642
643 return Status::OK;
David Rogersa12786b2020-01-31 16:02:33 -0800644}
645
David Rogers8db5a722020-02-03 18:28:34 -0800646// Find either an existing sector with enough space that is not the sector to
647// skip, or an empty sector. Maintains the invariant that there is always at
David Rogerscd87c322020-02-27 14:04:08 -0800648// least 1 empty sector unless set to bypass the rule. Optionally skip sectors
649// that have reclaimable bytes.
Wyatt Hepler5a33d8c2020-02-06 09:32:58 -0800650Status KeyValueStore::FindSectorWithSpace(
651 SectorDescriptor** found_sector,
652 size_t size,
David Rogerscd87c322020-02-27 14:04:08 -0800653 span<const SectorDescriptor*> sectors_to_skip,
654 bool bypass_empty_sector_rule,
655 bool allow_reclaimable) {
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800656 SectorDescriptor* first_empty_sector = nullptr;
657 bool at_least_two_empty_sectors = bypass_empty_sector_rule;
658
659 DBG("Find sector with %zu bytes available, starting with sector %u",
660 size,
661 SectorIndex(last_new_sector_));
David Rogerscd87c322020-02-27 14:04:08 -0800662 for (auto& skip_sector : sectors_to_skip) {
663 DBG(" Skip sector %u", SectorIndex(skip_sector));
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800664 }
665 if (bypass_empty_sector_rule) {
666 DBG(" Bypassing empty sector rule");
667 }
668
David Rogers8ce55cd2020-02-04 19:41:48 -0800669 // The last_new_sector_ is the sector that was last selected as the "new empty
670 // sector" to write to. This last new sector is used as the starting point for
671 // the next "find a new empty sector to write to" operation. By using the last
672 // new sector as the start point we will cycle which empty sector is selected
673 // next, spreading the wear across all the empty sectors and get a wear
674 // leveling benefit, rather than putting more wear on the lower number
675 // sectors.
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800676 SectorDescriptor* sector = last_new_sector_;
David Rogers67f4b6c2020-02-06 16:17:09 -0800677
David Rogerscd87c322020-02-27 14:04:08 -0800678 // Look for a sector to use with enough space. The search uses a 2 priority
679 // tier process.
680 //
681 // Tier 1 is sector that already has valid data. Optionally also only select
682 // sector that has no reclaimable bytes. Immediately use the first one of
683 // those that is found.
684 //
685 // Tier 2 is sectors that are empty. While scanning for a partial sector, keep
686 // track of the first empty sector and if a second empty sector was seen. If
687 // bypass_empty_sector_rule is true then count the second empty sector as
688 // always seen.
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800689 for (size_t j = 0; j < sectors_.size(); j++) {
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800690 sector += 1;
691 if (sector == sectors_.end()) {
692 sector = sectors_.begin();
693 }
Keir Mierle8c352dc2020-02-02 13:58:19 -0800694
David Rogerscd87c322020-02-27 14:04:08 -0800695 if (std::find(sectors_to_skip.begin(), sectors_to_skip.end(), sector) !=
696 sectors_to_skip.end()) {
David Rogers8db5a722020-02-03 18:28:34 -0800697 continue;
698 }
699
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800700 const size_t sector_size_bytes = partition_.sector_size_bytes();
David Rogerscd87c322020-02-27 14:04:08 -0800701 if (!sector->Empty(sector_size_bytes) && sector->HasSpace(size) &&
702 (allow_reclaimable ||
703 (sector->RecoverableBytes(sector_size_bytes) == 0))) {
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800704 *found_sector = sector;
David Rogers8ce55cd2020-02-04 19:41:48 -0800705 return Status::OK;
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800706 }
707
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800708 if (sector->Empty(sector_size_bytes)) {
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800709 if (first_empty_sector == nullptr) {
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800710 first_empty_sector = sector;
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800711 } else {
712 at_least_two_empty_sectors = true;
Wyatt Hepler2ad60672020-01-21 08:00:16 -0800713 }
Wyatt Heplerb7609542020-01-24 10:29:54 -0800714 }
715 }
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800716
David Rogers8ce55cd2020-02-04 19:41:48 -0800717 // If the scan for a partial sector does not find a suitable sector, use the
718 // first empty sector that was found. Normally it is required to keep 1 empty
719 // sector after the sector found here, but that rule can be bypassed in
720 // special circumstances (such as during garbage collection).
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800721 if (at_least_two_empty_sectors) {
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800722 DBG(" Found a usable empty sector; returning the first found (%u)",
David Rogers8ce55cd2020-02-04 19:41:48 -0800723 SectorIndex(first_empty_sector));
724 last_new_sector_ = first_empty_sector;
725 *found_sector = first_empty_sector;
726 return Status::OK;
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800727 }
David Rogers8ce55cd2020-02-04 19:41:48 -0800728
729 // No sector was found.
David Rogers67f4b6c2020-02-06 16:17:09 -0800730 DBG(" Unable to find a usable sector");
David Rogers8ce55cd2020-02-04 19:41:48 -0800731 *found_sector = nullptr;
732 return Status::RESOURCE_EXHAUSTED;
Wyatt Heplerb7609542020-01-24 10:29:54 -0800733}
734
David Rogers2761aeb2020-01-31 17:09:00 -0800735Status KeyValueStore::FindOrRecoverSectorWithSpace(SectorDescriptor** sector,
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800736 size_t size) {
David Rogers8ce55cd2020-02-04 19:41:48 -0800737 Status result = FindSectorWithSpace(sector, size);
Wyatt Hepler2d401692020-02-13 16:01:23 -0800738 if (result == Status::RESOURCE_EXHAUSTED && options_.partial_gc_on_write) {
David Rogers1541d612020-02-06 23:47:02 -0800739 // Garbage collect and then try again to find the best sector.
David Rogerscd87c322020-02-27 14:04:08 -0800740 TRY(GarbageCollectPartial());
David Rogers1541d612020-02-06 23:47:02 -0800741 return FindSectorWithSpace(sector, size);
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800742 }
David Rogers8ce55cd2020-02-04 19:41:48 -0800743 return result;
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800744}
745
David Rogers2761aeb2020-01-31 17:09:00 -0800746KeyValueStore::SectorDescriptor* KeyValueStore::FindSectorToGarbageCollect() {
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800747 const size_t sector_size_bytes = partition_.sector_size_bytes();
David Rogers2761aeb2020-01-31 17:09:00 -0800748 SectorDescriptor* sector_candidate = nullptr;
David Rogersa12786b2020-01-31 16:02:33 -0800749 size_t candidate_bytes = 0;
750
751 // Step 1: Try to find a sectors with stale keys and no valid keys (no
752 // relocation needed). If any such sectors are found, use the sector with the
753 // most reclaimable bytes.
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800754 for (auto& sector : sectors_) {
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800755 if ((sector.valid_bytes() == 0) &&
756 (sector.RecoverableBytes(sector_size_bytes) > candidate_bytes)) {
David Rogersa12786b2020-01-31 16:02:33 -0800757 sector_candidate = &sector;
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800758 candidate_bytes = sector.RecoverableBytes(sector_size_bytes);
David Rogersa12786b2020-01-31 16:02:33 -0800759 }
760 }
761
762 // Step 2: If step 1 yields no sectors, just find the sector with the most
763 // reclaimable bytes.
764 if (sector_candidate == nullptr) {
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800765 for (auto& sector : sectors_) {
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800766 if (sector.RecoverableBytes(sector_size_bytes) > candidate_bytes) {
David Rogersa12786b2020-01-31 16:02:33 -0800767 sector_candidate = &sector;
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800768 candidate_bytes = sector.RecoverableBytes(sector_size_bytes);
David Rogersa12786b2020-01-31 16:02:33 -0800769 }
770 }
771 }
772
David Rogers5981f312020-02-13 13:33:56 -0800773 if (sector_candidate != nullptr) {
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800774 DBG("Found sector %u to Garbage Collect, %zu recoverable bytes",
David Rogers5981f312020-02-13 13:33:56 -0800775 SectorIndex(sector_candidate),
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800776 sector_candidate->RecoverableBytes(sector_size_bytes));
David Rogers5981f312020-02-13 13:33:56 -0800777 } else {
778 DBG("Unable to find sector to garbage collect!");
779 }
David Rogersa12786b2020-01-31 16:02:33 -0800780 return sector_candidate;
781}
782
David Rogerscd87c322020-02-27 14:04:08 -0800783Status KeyValueStore::GarbageCollectFull() {
784 DBG("Garbage Collect all sectors");
785 LogSectors();
786 SectorDescriptor* sector = last_new_sector_;
787
788 // TODO: look in to making an iterator method for cycling through sectors
789 // starting from last_new_sector_.
790 for (size_t j = 0; j < sectors_.size(); j++) {
791 sector += 1;
792 if (sector == sectors_.end()) {
793 sector = sectors_.begin();
794 }
795
796 if (sector->RecoverableBytes(partition_.sector_size_bytes()) > 0) {
797 TRY(GarbageCollectSector(sector));
798 }
799 }
800
801 DBG("Garbage Collect all complete");
802 LogSectors();
803 return Status::OK;
804}
805
806Status KeyValueStore::GarbageCollectPartial() {
David Rogers67f4b6c2020-02-06 16:17:09 -0800807 DBG("Garbage Collect a single sector");
808
David Rogersa12786b2020-01-31 16:02:33 -0800809 // Step 1: Find the sector to garbage collect
David Rogers2761aeb2020-01-31 17:09:00 -0800810 SectorDescriptor* sector_to_gc = FindSectorToGarbageCollect();
David Rogers3464d0a2020-02-07 11:45:46 -0800811 LogSectors();
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800812
David Rogersa12786b2020-01-31 16:02:33 -0800813 if (sector_to_gc == nullptr) {
David Rogerscd87c322020-02-27 14:04:08 -0800814 // Nothing to GC, all done.
815 return Status::OK;
David Rogersa12786b2020-01-31 16:02:33 -0800816 }
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800817
David Rogerscd87c322020-02-27 14:04:08 -0800818 TRY(GarbageCollectSector(sector_to_gc));
819 LogSectors();
820 return Status::OK;
821}
822
823Status KeyValueStore::GarbageCollectSector(SectorDescriptor* sector_to_gc) {
824 // Step 1: Move any valid entries in the GC sector to other sectors
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800825 if (sector_to_gc->valid_bytes() != 0) {
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800826 for (auto& descriptor : key_descriptors_) {
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800827 if (AddressInSector(*sector_to_gc, descriptor.address())) {
David Rogers67f4b6c2020-02-06 16:17:09 -0800828 DBG(" Relocate entry");
David Rogers2761aeb2020-01-31 17:09:00 -0800829 TRY(RelocateEntry(descriptor));
David Rogersa12786b2020-01-31 16:02:33 -0800830 }
Wyatt Heplerb7609542020-01-24 10:29:54 -0800831 }
832 }
Wyatt Heplerb7609542020-01-24 10:29:54 -0800833
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800834 if (sector_to_gc->valid_bytes() != 0) {
David Rogers67f4b6c2020-02-06 16:17:09 -0800835 ERR(" Failed to relocate valid entries from sector being garbage "
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800836 "collected, %zu valid bytes remain",
837 sector_to_gc->valid_bytes());
Wyatt Heplerb7609542020-01-24 10:29:54 -0800838 return Status::INTERNAL;
839 }
840
David Rogerscd87c322020-02-27 14:04:08 -0800841 // Step 2: Reinitialize the sector
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800842 sector_to_gc->set_writable_bytes(0);
David Rogersa12786b2020-01-31 16:02:33 -0800843 TRY(partition_.Erase(SectorBaseAddress(sector_to_gc), 1));
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800844 sector_to_gc->set_writable_bytes(partition_.sector_size_bytes());
Wyatt Heplerb7609542020-01-24 10:29:54 -0800845
David Rogerscd87c322020-02-27 14:04:08 -0800846 DBG(" Garbage Collect sector %u complete", SectorIndex(sector_to_gc));
David Rogersa12786b2020-01-31 16:02:33 -0800847 return Status::OK;
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800848}
849
David Rogers2761aeb2020-01-31 17:09:00 -0800850Status KeyValueStore::AppendEntry(SectorDescriptor* sector,
851 KeyDescriptor* key_descriptor,
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800852 string_view key,
Wyatt Hepler5a33d8c2020-02-06 09:32:58 -0800853 span<const byte> value,
854 KeyDescriptor::State new_state) {
Wyatt Heplere541e072020-02-14 09:10:53 -0800855 const Address address = NextWritableAddress(sector);
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800856 Entry entry = CreateEntry(address, key, value, new_state);
Wyatt Heplere541e072020-02-14 09:10:53 -0800857
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800858 DBG("Appending %zu B entry with transaction ID %" PRIu32 " to address %#zx",
Wyatt Heplere541e072020-02-14 09:10:53 -0800859 entry.size(),
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800860 entry.transaction_id(),
861 size_t(address));
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800862
David Rogers6592d292020-02-14 14:19:26 -0800863 StatusWithSize result = entry.Write(key, value);
864 // Remove any bytes that were written, even if the write was not successful.
Keir Mierle0a52aed2020-02-21 09:24:36 -0800865 // This is important to retain the writable space invariant on the sectors.
David Rogers6592d292020-02-14 14:19:26 -0800866 sector->RemoveWritableBytes(result.size());
867
868 if (!result.ok()) {
Keir Mierle0a52aed2020-02-21 09:24:36 -0800869 ERR("Failed to write %zu bytes at %" PRIx32 ". %zu actually written",
David Rogers6592d292020-02-14 14:19:26 -0800870 entry.size(),
Keir Mierle0a52aed2020-02-21 09:24:36 -0800871 address,
David Rogers6592d292020-02-14 14:19:26 -0800872 result.size());
873 return result.status();
874 }
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800875
876 if (options_.verify_on_write) {
Wyatt Heplere541e072020-02-14 09:10:53 -0800877 TRY(entry.VerifyChecksumInFlash(entry_header_format_.checksum));
Wyatt Heplerb7609542020-01-24 10:29:54 -0800878 }
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800879
Keir Mierle9e38b402020-02-21 13:06:21 -0800880 // Entry was written successfully; update the key descriptor and the sector
881 // descriptor to reflect the new entry.
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800882 entry.UpdateDescriptor(key_descriptor);
David Rogers6592d292020-02-14 14:19:26 -0800883 sector->AddValidBytes(result.size());
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800884 return Status::OK;
Wyatt Heplerb7609542020-01-24 10:29:54 -0800885}
886
Wyatt Heplerbdd8e5a2020-02-20 19:27:26 -0800887KeyValueStore::Entry KeyValueStore::CreateEntry(Address address,
888 std::string_view key,
889 span<const byte> value,
890 KeyDescriptor::State state) {
Keir Mierle9e38b402020-02-21 13:06:21 -0800891 // Always bump the transaction ID when creating a new entry.
892 //
893 // Burning transaction IDs prevents inconsistencies between flash and memory
894 // that which could happen if a write succeeds, but for some reason the read
895 // and verify step fails. Here's how this would happen:
896 //
897 // 1. The entry is written but for some reason the flash reports failure OR
898 // The write succeeds, but the read / verify operation fails.
899 // 2. The transaction ID is NOT incremented, because of the failure
900 // 3. (later) A new entry is written, re-using the transaction ID (oops)
901 //
902 // By always burning transaction IDs, the above problem can't happen.
903 last_transaction_id_ += 1;
904
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800905 if (state == KeyDescriptor::kDeleted) {
Wyatt Hepler7465be32020-02-21 15:30:53 -0800906 return Entry::Tombstone(
907 partition_, address, entry_header_format_, key, last_transaction_id_);
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800908 }
909 return Entry::Valid(partition_,
910 address,
Wyatt Hepler88adfe82020-02-20 19:33:27 -0800911 entry_header_format_,
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800912 key,
913 value,
Keir Mierle9e38b402020-02-21 13:06:21 -0800914 last_transaction_id_);
Wyatt Heplerd2298282020-02-20 17:12:45 -0800915}
916
917void KeyValueStore::Reset() {
918 initialized_ = false;
919 key_descriptors_.clear();
920 last_new_sector_ = nullptr;
921 last_transaction_id_ = 0;
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800922}
923
Keir Mierle8c352dc2020-02-02 13:58:19 -0800924void KeyValueStore::LogDebugInfo() {
Keir Mierle8c352dc2020-02-02 13:58:19 -0800925 const size_t sector_size_bytes = partition_.sector_size_bytes();
926 DBG("====================== KEY VALUE STORE DUMP =========================");
927 DBG(" ");
928 DBG("Flash partition:");
Wyatt Heplerad0a7932020-02-06 08:20:38 -0800929 DBG(" Sector count = %zu", partition_.sector_count());
Wyatt Hepler38ce30f2020-02-19 11:48:31 -0800930 DBG(" Sector max count = %zu", sectors_.max_size());
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800931 DBG(" Sectors in use = %zu", sectors_.size());
Keir Mierle8c352dc2020-02-02 13:58:19 -0800932 DBG(" Sector size = %zu", sector_size_bytes);
933 DBG(" Total size = %zu", partition_.size_bytes());
934 DBG(" Alignment = %zu", partition_.alignment_bytes());
935 DBG(" ");
936 DBG("Key descriptors:");
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800937 DBG(" Entry count = %zu", key_descriptors_.size());
Wyatt Hepler38ce30f2020-02-19 11:48:31 -0800938 DBG(" Max entry count = %zu", key_descriptors_.max_size());
Keir Mierle8c352dc2020-02-02 13:58:19 -0800939 DBG(" ");
940 DBG(" # hash version address address (hex)");
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800941 for (size_t i = 0; i < key_descriptors_.size(); ++i) {
942 const KeyDescriptor& kd = key_descriptors_[i];
Keir Mierle8c352dc2020-02-02 13:58:19 -0800943 DBG(" |%3zu: | %8zx |%8zu | %8zu | %8zx",
944 i,
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800945 size_t(kd.hash()),
946 size_t(kd.transaction_id()),
947 size_t(kd.address()),
948 size_t(kd.address()));
Keir Mierle8c352dc2020-02-02 13:58:19 -0800949 }
950 DBG(" ");
951
952 DBG("Sector descriptors:");
953 DBG(" # tail free valid has_space");
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800954 for (size_t sector_id = 0; sector_id < sectors_.size(); ++sector_id) {
955 const SectorDescriptor& sd = sectors_[sector_id];
Keir Mierle8c352dc2020-02-02 13:58:19 -0800956 DBG(" |%3zu: | %8zu |%8zu | %s",
957 sector_id,
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800958 size_t(sd.writable_bytes()),
959 sd.valid_bytes(),
960 sd.writable_bytes() ? "YES" : "");
Keir Mierle8c352dc2020-02-02 13:58:19 -0800961 }
962 DBG(" ");
963
964 // TODO: This should stop logging after some threshold.
965 // size_t dumped_bytes = 0;
966 DBG("Sector raw data:");
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800967 for (size_t sector_id = 0; sector_id < sectors_.size(); ++sector_id) {
Keir Mierle8c352dc2020-02-02 13:58:19 -0800968 // Read sector data. Yes, this will blow the stack on embedded.
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800969 std::array<byte, 500> raw_sector_data; // TODO!!!
Keir Mierle8c352dc2020-02-02 13:58:19 -0800970 StatusWithSize sws =
971 partition_.Read(sector_id * sector_size_bytes, raw_sector_data);
972 DBG("Read: %zu bytes", sws.size());
973
974 DBG(" base addr offs 0 1 2 3 4 5 6 7");
975 for (size_t i = 0; i < sector_size_bytes; i += 8) {
976 DBG(" %3zu %8zx %5zu | %02x %02x %02x %02x %02x %02x %02x %02x",
977 sector_id,
978 (sector_id * sector_size_bytes) + i,
979 i,
980 static_cast<unsigned int>(raw_sector_data[i + 0]),
981 static_cast<unsigned int>(raw_sector_data[i + 1]),
982 static_cast<unsigned int>(raw_sector_data[i + 2]),
983 static_cast<unsigned int>(raw_sector_data[i + 3]),
984 static_cast<unsigned int>(raw_sector_data[i + 4]),
985 static_cast<unsigned int>(raw_sector_data[i + 5]),
986 static_cast<unsigned int>(raw_sector_data[i + 6]),
987 static_cast<unsigned int>(raw_sector_data[i + 7]));
988
989 // TODO: Fix exit condition.
990 if (i > 128) {
991 break;
992 }
993 }
994 DBG(" ");
995 }
996
997 DBG("////////////////////// KEY VALUE STORE DUMP END /////////////////////");
998}
999
David Rogerscf680ab2020-02-12 23:28:32 -08001000void KeyValueStore::LogSectors() const {
1001 DBG("Sector descriptors: count %zu", sectors_.size());
Wyatt Hepler1c329ca2020-02-07 18:07:23 -08001002 for (auto& sector : sectors_) {
Wyatt Hepler2c7eca02020-02-18 16:01:42 -08001003 DBG(" - Sector %u: valid %zu, recoverable %zu, free %zu",
David Rogers50185ad2020-02-07 00:02:46 -08001004 SectorIndex(&sector),
Wyatt Hepler2c7eca02020-02-18 16:01:42 -08001005 sector.valid_bytes(),
1006 sector.RecoverableBytes(partition_.sector_size_bytes()),
1007 sector.writable_bytes());
David Rogers50185ad2020-02-07 00:02:46 -08001008 }
1009}
1010
David Rogerscf680ab2020-02-12 23:28:32 -08001011void KeyValueStore::LogKeyDescriptor() const {
1012 DBG("Key descriptors: count %zu", key_descriptors_.size());
1013 for (auto& key : key_descriptors_) {
Wyatt Hepler1fc11042020-02-19 17:17:51 -08001014 DBG(" - Key: %s, hash %#zx, transaction ID %zu, address %#zx",
David Rogerscf680ab2020-02-12 23:28:32 -08001015 key.deleted() ? "Deleted" : "Valid",
Wyatt Hepler1fc11042020-02-19 17:17:51 -08001016 static_cast<size_t>(key.hash()),
1017 static_cast<size_t>(key.transaction_id()),
1018 static_cast<size_t>(key.address()));
David Rogerscf680ab2020-02-12 23:28:32 -08001019 }
1020}
1021
Wyatt Hepler2ad60672020-01-21 08:00:16 -08001022} // namespace pw::kvs