blob: 84cc4cf471f4261b3663cea7f1b1e5d1b3e8b3af [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
Armando Montanez28ecccb2020-05-04 15:35:54 -070015#define PW_LOG_MODULE_NAME "KVS"
16
Wyatt Heplerb7609542020-01-24 10:29:54 -080017#include "pw_kvs/key_value_store.h"
18
Wyatt Heplerbab0e202020-02-04 07:40:08 -080019#include <algorithm>
Wyatt Hepler5a33d8c2020-02-06 09:32:58 -080020#include <cinttypes>
Wyatt Heplerb7609542020-01-24 10:29:54 -080021#include <cstring>
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -080022#include <type_traits>
Wyatt Heplerb7609542020-01-24 10:29:54 -080023
Keir Mierle8c352dc2020-02-02 13:58:19 -080024#define PW_LOG_USE_ULTRA_SHORT_NAMES 1
David Rogersc0104462020-05-08 15:50:23 -070025#include "pw_assert/assert.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 Hepler22d0d9f2020-03-05 14:57:11 -080042 span<const EntryFormat> formats,
Wyatt Hepler7ded6da2020-03-11 18:24:43 -070043 const Options& options,
44 size_t redundancy,
45 Vector<SectorDescriptor>& sector_descriptor_list,
46 const SectorDescriptor** temp_sectors_to_skip,
47 Vector<KeyDescriptor>& key_descriptor_list,
48 Address* addresses)
Wyatt Heplerad0a7932020-02-06 08:20:38 -080049 : partition_(*partition),
Wyatt Hepler22d0d9f2020-03-05 14:57:11 -080050 formats_(formats),
Wyatt Heplerc84393f2020-03-20 11:23:24 -070051 sectors_(sector_descriptor_list, *partition, temp_sectors_to_skip),
Wyatt Hepler7ded6da2020-03-11 18:24:43 -070052 entry_cache_(key_descriptor_list, addresses, redundancy),
David Rogers49766d92020-03-20 10:55:54 -070053 options_(options),
David Rogers9abe3c72020-03-24 19:03:13 -070054 initialized_(InitializationState::kNotInitialized),
David Rogers49766d92020-03-20 10:55:54 -070055 error_detected_(false),
David Rogers9abe3c72020-03-24 19:03:13 -070056 error_stats_({}),
David Rogers49766d92020-03-20 10:55:54 -070057 last_transaction_id_(0) {}
Wyatt Heplerad0a7932020-02-06 08:20:38 -080058
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -080059Status KeyValueStore::Init() {
David Rogers9abe3c72020-03-24 19:03:13 -070060 initialized_ = InitializationState::kNotInitialized;
David Rogers49766d92020-03-20 10:55:54 -070061 error_detected_ = false;
Keir Mierlebf904812020-03-11 17:28:22 -070062 last_transaction_id_ = 0;
Wyatt Heplerd2298282020-02-20 17:12:45 -080063
David Rogers2e9e0c82020-02-13 15:06:06 -080064 INF("Initializing key value store");
Wyatt Hepler38ce30f2020-02-19 11:48:31 -080065 if (partition_.sector_count() > sectors_.max_size()) {
David Rogers9fc78b82020-06-12 13:56:12 -070066 ERR("KVS init failed: kMaxUsableSectors (=%u) must be at least as "
67 "large as the number of sectors in the flash partition (=%u)",
68 unsigned(sectors_.max_size()),
69 unsigned(partition_.sector_count()));
Wyatt Heplerad0a7932020-02-06 08:20:38 -080070 return Status::FAILED_PRECONDITION;
71 }
72
Keir Mierle8c352dc2020-02-02 13:58:19 -080073 const size_t sector_size_bytes = partition_.sector_size_bytes();
Keir Mierle8c352dc2020-02-02 13:58:19 -080074
David Rogers49766d92020-03-20 10:55:54 -070075 // TODO: investigate doing this as a static assert/compile-time check.
76 if (sector_size_bytes > SectorDescriptor::max_sector_size()) {
David Rogers9fc78b82020-06-12 13:56:12 -070077 ERR("KVS init failed: sector_size_bytes (=%u) is greater than maximum "
78 "allowed sector size (=%u)",
79 unsigned(sector_size_bytes),
80 unsigned(SectorDescriptor::max_sector_size()));
David Rogers49766d92020-03-20 10:55:54 -070081 return Status::FAILED_PRECONDITION;
82 }
83
David Rogerscd134352020-04-17 19:37:15 -070084 Status metadata_result = InitializeMetadata();
David Rogersfcea3252020-04-07 14:56:35 -070085
86 if (!error_detected_) {
87 initialized_ = InitializationState::kReady;
88 } else {
David Rogers0f8a1bb2020-04-21 18:50:19 -070089 initialized_ = InitializationState::kNeedsMaintenance;
90
David Rogersfcea3252020-04-07 14:56:35 -070091 if (options_.recovery != ErrorRecovery::kManual) {
Armando Montanezf8419ae2020-04-21 10:03:05 -070092 size_t pre_fix_redundancy_errors =
93 error_stats_.missing_redundant_entries_recovered;
David Rogersfcea3252020-04-07 14:56:35 -070094 Status recovery_status = FixErrors();
95
96 if (recovery_status.ok()) {
David Rogerscd134352020-04-17 19:37:15 -070097 if (metadata_result == Status::OUT_OF_RANGE) {
Armando Montanezf8419ae2020-04-21 10:03:05 -070098 error_stats_.missing_redundant_entries_recovered =
99 pre_fix_redundancy_errors;
David Rogerscd134352020-04-17 19:37:15 -0700100 INF("KVS init: Redundancy level successfully updated");
101 } else {
102 WRN("KVS init: Corruption detected and fully repaired");
103 }
David Rogersfcea3252020-04-07 14:56:35 -0700104 initialized_ = InitializationState::kReady;
105 } else if (recovery_status == Status::RESOURCE_EXHAUSTED) {
106 WRN("KVS init: Unable to maintain required free sector");
David Rogersfcea3252020-04-07 14:56:35 -0700107 } else {
108 WRN("KVS init: Corruption detected and unable repair");
David Rogersfcea3252020-04-07 14:56:35 -0700109 }
110 } else {
111 WRN("KVS init: Corruption detected, no repair attempted due to options");
David Rogersfcea3252020-04-07 14:56:35 -0700112 }
113 }
114
David Rogers9fc78b82020-06-12 13:56:12 -0700115 INF("KeyValueStore init complete: active keys %u, deleted keys %u, sectors "
116 "%u, logical sector size %u bytes",
117 unsigned(size()),
118 unsigned(entry_cache_.total_entries() - size()),
119 unsigned(sectors_.size()),
120 unsigned(partition_.sector_size_bytes()));
David Rogersfcea3252020-04-07 14:56:35 -0700121
122 // Report any corruption was not repaired.
123 if (error_detected_) {
124 WRN("KVS init: Corruption found but not repaired, KVS unavailable until "
125 "successful maintenance.");
126 return Status::DATA_LOSS;
127 }
128
129 return Status::OK;
130}
131
David Rogerscd134352020-04-17 19:37:15 -0700132Status KeyValueStore::InitializeMetadata() {
David Rogersfcea3252020-04-07 14:56:35 -0700133 const size_t sector_size_bytes = partition_.sector_size_bytes();
134
135 sectors_.Reset();
136 entry_cache_.Reset();
137
Keir Mierle8c352dc2020-02-02 13:58:19 -0800138 DBG("First pass: Read all entries from all sectors");
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800139 Address sector_address = 0;
Keir Mierle8c352dc2020-02-02 13:58:19 -0800140
Alexei Frolovd4adf912020-02-21 13:29:15 -0800141 size_t total_corrupt_bytes = 0;
David Rogerscd134352020-04-17 19:37:15 -0700142 size_t corrupt_entries = 0;
David Rogers91627482020-02-27 17:38:12 -0800143 bool empty_sector_found = false;
David Rogerscd134352020-04-17 19:37:15 -0700144 size_t entry_copies_missing = 0;
Alexei Frolovd4adf912020-02-21 13:29:15 -0800145
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800146 for (SectorDescriptor& sector : sectors_) {
Keir Mierle8c352dc2020-02-02 13:58:19 -0800147 Address entry_address = sector_address;
148
Alexei Frolovd4adf912020-02-21 13:29:15 -0800149 size_t sector_corrupt_bytes = 0;
150
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800151 for (int num_entries_in_sector = 0; true; num_entries_in_sector++) {
David Rogersfcea3252020-04-07 14:56:35 -0700152 DBG("Load entry: sector=%u, entry#=%d, address=%u",
153 unsigned(sector_address),
Keir Mierle8c352dc2020-02-02 13:58:19 -0800154 num_entries_in_sector,
David Rogersfcea3252020-04-07 14:56:35 -0700155 unsigned(entry_address));
Keir Mierle8c352dc2020-02-02 13:58:19 -0800156
Wyatt Heplerc84393f2020-03-20 11:23:24 -0700157 if (!sectors_.AddressInSector(sector, entry_address)) {
Keir Mierle8c352dc2020-02-02 13:58:19 -0800158 DBG("Fell off end of sector; moving to the next sector");
159 break;
160 }
161
162 Address next_entry_address;
163 Status status = LoadEntry(entry_address, &next_entry_address);
164 if (status == Status::NOT_FOUND) {
165 DBG("Hit un-written data in sector; moving to the next sector");
166 break;
David Rogersfcea3252020-04-07 14:56:35 -0700167 } else if (!status.ok()) {
168 // The entry could not be read, indicating likely data corruption within
169 // the sector. Try to scan the remainder of the sector for other
170 // entries.
Alexei Frolovd4adf912020-02-21 13:29:15 -0800171
David Rogers49766d92020-03-20 10:55:54 -0700172 error_detected_ = true;
Alexei Frolovd4adf912020-02-21 13:29:15 -0800173 corrupt_entries++;
174
175 status = ScanForEntry(sector,
176 entry_address + Entry::kMinAlignmentBytes,
177 &next_entry_address);
David Rogersfcea3252020-04-07 14:56:35 -0700178 if (!status.ok()) {
Alexei Frolovd4adf912020-02-21 13:29:15 -0800179 // No further entries in this sector. Mark the remaining bytes in the
180 // sector as corrupt (since we can't reliably know the size of the
181 // corrupt entry).
182 sector_corrupt_bytes +=
183 sector_size_bytes - (entry_address - sector_address);
184 break;
185 }
186
Alexei Frolovd4adf912020-02-21 13:29:15 -0800187 sector_corrupt_bytes += next_entry_address - entry_address;
Keir Mierle8c352dc2020-02-02 13:58:19 -0800188 }
Keir Mierle8c352dc2020-02-02 13:58:19 -0800189
190 // Entry loaded successfully; so get ready to load the next one.
191 entry_address = next_entry_address;
192
193 // Update of the number of writable bytes in this sector.
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800194 sector.set_writable_bytes(sector_size_bytes -
195 (entry_address - sector_address));
Keir Mierle8c352dc2020-02-02 13:58:19 -0800196 }
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800197
Alexei Frolovd4adf912020-02-21 13:29:15 -0800198 if (sector_corrupt_bytes > 0) {
199 // If the sector contains corrupt data, prevent any further entries from
200 // being written to it by indicating that it has no space. This should
201 // also make it a decent GC candidate. Valid keys in the sector are still
202 // readable as normal.
David Rogers49766d92020-03-20 10:55:54 -0700203 sector.mark_corrupt();
204 error_detected_ = true;
Alexei Frolovd4adf912020-02-21 13:29:15 -0800205
David Rogers9fc78b82020-06-12 13:56:12 -0700206 WRN("Sector %u contains %uB of corrupt data",
Wyatt Heplerc84393f2020-03-20 11:23:24 -0700207 sectors_.Index(sector),
David Rogers9fc78b82020-06-12 13:56:12 -0700208 unsigned(sector_corrupt_bytes));
Alexei Frolovd4adf912020-02-21 13:29:15 -0800209 }
210
David Rogers91627482020-02-27 17:38:12 -0800211 if (sector.Empty(sector_size_bytes)) {
212 empty_sector_found = true;
213 }
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800214 sector_address += sector_size_bytes;
Alexei Frolovd4adf912020-02-21 13:29:15 -0800215 total_corrupt_bytes += sector_corrupt_bytes;
Keir Mierle8c352dc2020-02-02 13:58:19 -0800216 }
217
218 DBG("Second pass: Count valid bytes in each sector");
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700219 Address newest_key = 0;
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800220
David Rogers98fea472020-04-01 15:43:48 -0700221 // For every valid entry, for each address, count the valid bytes in that
222 // sector. If the address fails to read, remove the address and mark the
223 // sector as corrupt. Track which entry has the newest transaction ID for
224 // initializing last_new_sector_.
225 for (EntryMetadata& metadata : entry_cache_) {
David Rogers49766d92020-03-20 10:55:54 -0700226 if (metadata.addresses().size() < redundancy()) {
David Rogers31b358b2020-04-15 05:00:50 -0700227 DBG("Key 0x%08x missing copies, has %u, needs %u",
228 unsigned(metadata.hash()),
229 unsigned(metadata.addresses().size()),
230 unsigned(redundancy()));
David Rogerscd134352020-04-17 19:37:15 -0700231 entry_copies_missing++;
David Rogers49766d92020-03-20 10:55:54 -0700232 }
David Rogers98fea472020-04-01 15:43:48 -0700233 size_t index = 0;
234 while (index < metadata.addresses().size()) {
235 Address address = metadata.addresses()[index];
David Rogersf56131c2020-03-04 10:19:22 -0800236 Entry entry;
David Rogers98fea472020-04-01 15:43:48 -0700237
238 Status read_result = Entry::Read(partition_, address, formats_, &entry);
239
240 SectorDescriptor& sector = sectors_.FromAddress(address);
241
242 if (read_result.ok()) {
243 sector.AddValidBytes(entry.size());
244 index++;
245 } else {
246 corrupt_entries++;
247 total_corrupt_bytes += sector.writable_bytes();
248 error_detected_ = true;
249 sector.mark_corrupt();
250
251 // Remove the bad address and stay at this index. The removal
252 // replaces out the removed address with the back address so
253 // this index needs to be rechecked with the new address.
254 metadata.RemoveAddress(address);
255 }
David Rogersf56131c2020-03-04 10:19:22 -0800256 }
David Rogers98fea472020-04-01 15:43:48 -0700257
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700258 if (metadata.IsNewerThan(last_transaction_id_)) {
259 last_transaction_id_ = metadata.transaction_id();
260 newest_key = metadata.addresses().back();
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800261 }
Keir Mierle8c352dc2020-02-02 13:58:19 -0800262 }
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800263
Wyatt Heplerc84393f2020-03-20 11:23:24 -0700264 sectors_.set_last_new_sector(newest_key);
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800265
David Rogers91627482020-02-27 17:38:12 -0800266 if (!empty_sector_found) {
David Rogers31b358b2020-04-15 05:00:50 -0700267 DBG("No empty sector found");
David Rogers9abe3c72020-03-24 19:03:13 -0700268 error_detected_ = true;
David Rogers91627482020-02-27 17:38:12 -0800269 }
270
David Rogerscd134352020-04-17 19:37:15 -0700271 if (entry_copies_missing > 0) {
272 bool other_errors = error_detected_;
273 error_detected_ = true;
274
Armando Montanez344814b2020-04-24 15:05:42 -0700275 if (!other_errors && entry_copies_missing == entry_cache_.total_entries()) {
David Rogers9fc78b82020-06-12 13:56:12 -0700276 INF("KVS configuration changed to redundancy of %u total copies per key",
277 unsigned(redundancy()));
David Rogerscd134352020-04-17 19:37:15 -0700278 return Status::OUT_OF_RANGE;
279 }
David Rogers9abe3c72020-03-24 19:03:13 -0700280 }
David Rogerscd134352020-04-17 19:37:15 -0700281
282 if (error_detected_) {
David Rogers9fc78b82020-06-12 13:56:12 -0700283 WRN("Corruption detected. Found %u corrupt bytes, %u corrupt entries, "
284 "and %u keys missing redundant copies.",
285 unsigned(total_corrupt_bytes),
286 unsigned(corrupt_entries),
287 unsigned(entry_copies_missing));
David Rogerscd134352020-04-17 19:37:15 -0700288 return Status::FAILED_PRECONDITION;
289 }
290 return Status::OK;
Keir Mierle8c352dc2020-02-02 13:58:19 -0800291}
292
Alexei Frolov9e235832020-02-24 12:44:45 -0800293KeyValueStore::StorageStats KeyValueStore::GetStorageStats() const {
David Rogers9abe3c72020-03-24 19:03:13 -0700294 StorageStats stats{};
Alexei Frolov9e235832020-02-24 12:44:45 -0800295 const size_t sector_size = partition_.sector_size_bytes();
296 bool found_empty_sector = false;
David Rogers9abe3c72020-03-24 19:03:13 -0700297 stats.corrupt_sectors_recovered = error_stats_.corrupt_sectors_recovered;
298 stats.missing_redundant_entries_recovered =
299 error_stats_.missing_redundant_entries_recovered;
Alexei Frolov9e235832020-02-24 12:44:45 -0800300
301 for (const SectorDescriptor& sector : sectors_) {
302 stats.in_use_bytes += sector.valid_bytes();
303 stats.reclaimable_bytes += sector.RecoverableBytes(sector_size);
304
305 if (!found_empty_sector && sector.Empty(sector_size)) {
306 // The KVS tries to always keep an empty sector for GC, so don't count
307 // the first empty sector seen as writable space. However, a free sector
308 // cannot always be assumed to exist; if a GC operation fails, all sectors
309 // may be partially written, in which case the space reported might be
310 // inaccurate.
311 found_empty_sector = true;
312 continue;
313 }
314
315 stats.writable_bytes += sector.writable_bytes();
316 }
317
318 return stats;
319}
320
David Rogers98fea472020-04-01 15:43:48 -0700321// Check KVS for any error conditions. Primarily intended for test and
322// internal use.
David Rogers9abe3c72020-03-24 19:03:13 -0700323bool KeyValueStore::CheckForErrors() {
324 // Check for corrupted sectors
325 for (SectorDescriptor& sector : sectors_) {
326 if (sector.corrupt()) {
327 error_detected_ = true;
David Rogers98fea472020-04-01 15:43:48 -0700328 return error_detected();
David Rogers9abe3c72020-03-24 19:03:13 -0700329 }
330 }
331
332 // Check for missing redundancy.
333 if (redundancy() > 1) {
334 for (const EntryMetadata& metadata : entry_cache_) {
335 if (metadata.addresses().size() < redundancy()) {
336 error_detected_ = true;
David Rogers98fea472020-04-01 15:43:48 -0700337 return error_detected();
David Rogers9abe3c72020-03-24 19:03:13 -0700338 }
339 }
340 }
341
342 return error_detected();
343}
344
Keir Mierle8c352dc2020-02-02 13:58:19 -0800345Status KeyValueStore::LoadEntry(Address entry_address,
346 Address* next_entry_address) {
Wyatt Heplere541e072020-02-14 09:10:53 -0800347 Entry entry;
Wyatt Hepler22d0d9f2020-03-05 14:57:11 -0800348 TRY(Entry::Read(partition_, entry_address, formats_, &entry));
Keir Mierle8c352dc2020-02-02 13:58:19 -0800349
350 // Read the key from flash & validate the entry (which reads the value).
Wyatt Heplera00d1ef2020-02-14 14:31:26 -0800351 Entry::KeyBuffer key_buffer;
Wyatt Heplere541e072020-02-14 09:10:53 -0800352 TRY_ASSIGN(size_t key_length, entry.ReadKey(key_buffer));
353 const string_view key(key_buffer.data(), key_length);
Wyatt Heplerbab0e202020-02-04 07:40:08 -0800354
Wyatt Hepler22d0d9f2020-03-05 14:57:11 -0800355 TRY(entry.VerifyChecksumInFlash());
David Rogersf56131c2020-03-04 10:19:22 -0800356
357 // A valid entry was found, so update the next entry address before doing any
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700358 // of the checks that happen in AddNewOrUpdateExisting.
David Rogersf56131c2020-03-04 10:19:22 -0800359 *next_entry_address = entry.next_address();
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700360 return entry_cache_.AddNewOrUpdateExisting(
361 entry.descriptor(key), entry.address(), partition_.sector_size_bytes());
Keir Mierle8c352dc2020-02-02 13:58:19 -0800362}
363
Alexei Frolovd4adf912020-02-21 13:29:15 -0800364// Scans flash memory within a sector to find a KVS entry magic.
Alexei Frolovd4adf912020-02-21 13:29:15 -0800365Status KeyValueStore::ScanForEntry(const SectorDescriptor& sector,
366 Address start_address,
367 Address* next_entry_address) {
David Rogersfcea3252020-04-07 14:56:35 -0700368 DBG("Scanning sector %u for entries starting from address %u",
Wyatt Heplerc84393f2020-03-20 11:23:24 -0700369 sectors_.Index(sector),
David Rogersfcea3252020-04-07 14:56:35 -0700370 unsigned(start_address));
Alexei Frolovd4adf912020-02-21 13:29:15 -0800371
372 // Entries must start at addresses which are aligned on a multiple of
373 // Entry::kMinAlignmentBytes. However, that multiple can vary between entries.
374 // When scanning, we don't have an entry to tell us what the current alignment
375 // is, so the minimum alignment is used to be exhaustive.
376 for (Address address = AlignUp(start_address, Entry::kMinAlignmentBytes);
Wyatt Heplerc84393f2020-03-20 11:23:24 -0700377 sectors_.AddressInSector(sector, address);
Alexei Frolovd4adf912020-02-21 13:29:15 -0800378 address += Entry::kMinAlignmentBytes) {
Alexei Frolovd4adf912020-02-21 13:29:15 -0800379 uint32_t magic;
David Rogersfcea3252020-04-07 14:56:35 -0700380 StatusWithSize read_result =
381 partition_.Read(address, as_writable_bytes(span(&magic, 1)));
382 if (!read_result.ok()) {
383 continue;
384 }
Wyatt Hepler22d0d9f2020-03-05 14:57:11 -0800385 if (formats_.KnownMagic(magic)) {
David Rogersfcea3252020-04-07 14:56:35 -0700386 DBG("Found entry magic at address %u", unsigned(address));
Alexei Frolovd4adf912020-02-21 13:29:15 -0800387 *next_entry_address = address;
388 return Status::OK;
389 }
390 }
391
392 return Status::NOT_FOUND;
393}
394
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800395StatusWithSize KeyValueStore::Get(string_view key,
Wyatt Hepler5f6efc02020-02-18 16:54:31 -0800396 span<byte> value_buffer,
397 size_t offset_bytes) const {
David Rogers9abe3c72020-03-24 19:03:13 -0700398 TRY_WITH_SIZE(CheckReadOperation(key));
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800399
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700400 EntryMetadata metadata;
David Rogers98fea472020-04-01 15:43:48 -0700401 TRY_WITH_SIZE(FindExisting(key, &metadata));
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800402
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700403 return Get(key, metadata, value_buffer, offset_bytes);
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800404}
405
Wyatt Heplerfac81132020-02-27 17:26:33 -0800406Status KeyValueStore::PutBytes(string_view key, span<const byte> value) {
David Rogers9abe3c72020-03-24 19:03:13 -0700407 TRY(CheckWriteOperation(key));
David Rogers9fc78b82020-06-12 13:56:12 -0700408 DBG("Writing key/value; key length=%u, value length=%u",
409 unsigned(key.size()),
410 unsigned(value.size()));
Wyatt Hepler729f28c2020-02-05 09:46:00 -0800411
Wyatt Hepler5406a672020-02-18 15:42:38 -0800412 if (Entry::size(partition_, key, value) > partition_.sector_size_bytes()) {
David Rogers9fc78b82020-06-12 13:56:12 -0700413 DBG("%u B value with %u B key cannot fit in one sector",
414 unsigned(value.size()),
415 unsigned(key.size()));
Wyatt Hepler5406a672020-02-18 15:42:38 -0800416 return Status::INVALID_ARGUMENT;
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800417 }
418
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700419 EntryMetadata metadata;
David Rogers98fea472020-04-01 15:43:48 -0700420 Status status = FindEntry(key, &metadata);
Wyatt Hepler2d401692020-02-13 16:01:23 -0800421
422 if (status.ok()) {
David Rogersf56131c2020-03-04 10:19:22 -0800423 // TODO: figure out logging how to support multiple addresses.
David Rogers9fc78b82020-06-12 13:56:12 -0700424 DBG("Overwriting entry for key 0x%08x in %u sectors including %u",
425 unsigned(metadata.hash()),
426 unsigned(metadata.addresses().size()),
Wyatt Heplerc84393f2020-03-20 11:23:24 -0700427 sectors_.Index(metadata.first_address()));
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700428 return WriteEntryForExistingKey(metadata, EntryState::kValid, key, value);
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800429 }
David Rogers2761aeb2020-01-31 17:09:00 -0800430
Wyatt Hepler2d401692020-02-13 16:01:23 -0800431 if (status == Status::NOT_FOUND) {
432 return WriteEntryForNewKey(key, value);
433 }
434
435 return status;
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800436}
437
438Status KeyValueStore::Delete(string_view key) {
David Rogers9abe3c72020-03-24 19:03:13 -0700439 TRY(CheckWriteOperation(key));
Wyatt Hepler729f28c2020-02-05 09:46:00 -0800440
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700441 EntryMetadata metadata;
David Rogers98fea472020-04-01 15:43:48 -0700442 TRY(FindExisting(key, &metadata));
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800443
David Rogersf56131c2020-03-04 10:19:22 -0800444 // TODO: figure out logging how to support multiple addresses.
David Rogers9fc78b82020-06-12 13:56:12 -0700445 DBG("Writing tombstone for key 0x%08x in %u sectors including %u",
446 unsigned(metadata.hash()),
447 unsigned(metadata.addresses().size()),
Wyatt Heplerc84393f2020-03-20 11:23:24 -0700448 sectors_.Index(metadata.first_address()));
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700449 return WriteEntryForExistingKey(metadata, EntryState::kDeleted, key, {});
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800450}
451
Wyatt Hepler08d37d82020-02-27 15:45:37 -0800452void KeyValueStore::Item::ReadKey() {
453 key_buffer_.fill('\0');
454
455 Entry entry;
David Rogers98fea472020-04-01 15:43:48 -0700456 if (kvs_.ReadEntry(*iterator_, entry).ok()) {
Wyatt Hepler08d37d82020-02-27 15:45:37 -0800457 entry.ReadKey(key_buffer_);
458 }
459}
460
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800461KeyValueStore::iterator& KeyValueStore::iterator::operator++() {
462 // Skip to the next entry that is valid (not deleted).
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700463 while (++item_.iterator_ != item_.kvs_.entry_cache_.end() &&
Wyatt Hepler02946272020-03-18 10:36:22 -0700464 item_.iterator_->state() != EntryState::kValid) {
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800465 }
466 return *this;
467}
468
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800469KeyValueStore::iterator KeyValueStore::begin() const {
Wyatt Heplerbfc6a522020-04-01 16:30:24 -0700470 internal::EntryCache::const_iterator cache_iterator = entry_cache_.begin();
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800471 // Skip over any deleted entries at the start of the descriptor list.
Wyatt Hepler02946272020-03-18 10:36:22 -0700472 while (cache_iterator != entry_cache_.end() &&
473 cache_iterator->state() != EntryState::kValid) {
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700474 ++cache_iterator;
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800475 }
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700476 return iterator(*this, cache_iterator);
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800477}
478
Wyatt Heplerab3b2492020-03-11 16:15:16 -0700479StatusWithSize KeyValueStore::ValueSize(string_view key) const {
David Rogers9abe3c72020-03-24 19:03:13 -0700480 TRY_WITH_SIZE(CheckReadOperation(key));
Wyatt Heplered163b02020-02-03 17:49:32 -0800481
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700482 EntryMetadata metadata;
David Rogers98fea472020-04-01 15:43:48 -0700483 TRY_WITH_SIZE(FindExisting(key, &metadata));
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800484
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700485 return ValueSize(metadata);
Wyatt Heplerfac81132020-02-27 17:26:33 -0800486}
Wyatt Heplered163b02020-02-03 17:49:32 -0800487
David Rogers98fea472020-04-01 15:43:48 -0700488Status KeyValueStore::ReadEntry(const EntryMetadata& metadata,
489 Entry& entry) const {
490 // Try to read an entry
491 Status read_result = Status::DATA_LOSS;
492 for (Address address : metadata.addresses()) {
493 read_result = Entry::Read(partition_, address, formats_, &entry);
494 if (read_result.ok()) {
495 return read_result;
496 }
497
498 // Found a bad address. Set the sector as corrupt.
499 error_detected_ = true;
500 sectors_.FromAddress(address).mark_corrupt();
501 }
502
503 ERR("No valid entries for key. Data has been lost!");
504 return read_result;
505}
506
507Status KeyValueStore::FindEntry(string_view key,
508 EntryMetadata* found_entry) const {
509 StatusWithSize find_result =
510 entry_cache_.Find(partition_, sectors_, formats_, key, found_entry);
511
512 if (find_result.size() > 0u) {
513 error_detected_ = true;
514 }
515 return find_result.status();
516}
517
518Status KeyValueStore::FindExisting(string_view key,
519 EntryMetadata* metadata) const {
520 Status status = FindEntry(key, metadata);
521
522 // If the key's hash collides with an existing key or if the key is deleted,
523 // treat it as if it is not in the KVS.
524 if (status == Status::ALREADY_EXISTS ||
525 (status.ok() && metadata->state() == EntryState::kDeleted)) {
526 return Status::NOT_FOUND;
527 }
528 return status;
529}
530
Wyatt Heplerfac81132020-02-27 17:26:33 -0800531StatusWithSize KeyValueStore::Get(string_view key,
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700532 const EntryMetadata& metadata,
Wyatt Heplerfac81132020-02-27 17:26:33 -0800533 span<std::byte> value_buffer,
534 size_t offset_bytes) const {
535 Entry entry;
David Rogers98fea472020-04-01 15:43:48 -0700536
537 TRY_WITH_SIZE(ReadEntry(metadata, entry));
Wyatt Heplerfac81132020-02-27 17:26:33 -0800538
539 StatusWithSize result = entry.ReadValue(value_buffer, offset_bytes);
540 if (result.ok() && options_.verify_on_read && offset_bytes == 0u) {
Wyatt Hepler22d0d9f2020-03-05 14:57:11 -0800541 Status verify_result =
542 entry.VerifyChecksum(key, value_buffer.first(result.size()));
Wyatt Heplerfac81132020-02-27 17:26:33 -0800543 if (!verify_result.ok()) {
544 std::memset(value_buffer.data(), 0, result.size());
545 return StatusWithSize(verify_result, 0);
546 }
547
548 return StatusWithSize(verify_result, result.size());
549 }
550 return result;
Wyatt Heplered163b02020-02-03 17:49:32 -0800551}
552
Wyatt Hepler6e3a83b2020-02-04 07:36:45 -0800553Status KeyValueStore::FixedSizeGet(std::string_view key,
Wyatt Heplerfac81132020-02-27 17:26:33 -0800554 void* value,
555 size_t size_bytes) const {
David Rogers9abe3c72020-03-24 19:03:13 -0700556 TRY(CheckWriteOperation(key));
Wyatt Heplerfac81132020-02-27 17:26:33 -0800557
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700558 EntryMetadata metadata;
David Rogers98fea472020-04-01 15:43:48 -0700559 TRY(FindExisting(key, &metadata));
Wyatt Heplerfac81132020-02-27 17:26:33 -0800560
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700561 return FixedSizeGet(key, metadata, value, size_bytes);
Wyatt Heplerfac81132020-02-27 17:26:33 -0800562}
563
564Status KeyValueStore::FixedSizeGet(std::string_view key,
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700565 const EntryMetadata& metadata,
Wyatt Heplerfac81132020-02-27 17:26:33 -0800566 void* value,
Wyatt Hepler6e3a83b2020-02-04 07:36:45 -0800567 size_t size_bytes) const {
568 // Ensure that the size of the stored value matches the size of the type.
569 // Otherwise, report error. This check avoids potential memory corruption.
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700570 TRY_ASSIGN(const size_t actual_size, ValueSize(metadata));
Wyatt Heplerfac81132020-02-27 17:26:33 -0800571
572 if (actual_size != size_bytes) {
David Rogers9fc78b82020-06-12 13:56:12 -0700573 DBG("Requested %u B read, but value is %u B",
574 unsigned(size_bytes),
575 unsigned(actual_size));
Wyatt Hepler6e3a83b2020-02-04 07:36:45 -0800576 return Status::INVALID_ARGUMENT;
Wyatt Heplerbab0e202020-02-04 07:40:08 -0800577 }
Wyatt Heplerfac81132020-02-27 17:26:33 -0800578
579 StatusWithSize result =
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700580 Get(key, metadata, span(static_cast<byte*>(value), size_bytes), 0);
Wyatt Heplerfac81132020-02-27 17:26:33 -0800581
582 return result.status();
583}
584
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700585StatusWithSize KeyValueStore::ValueSize(const EntryMetadata& metadata) const {
Wyatt Heplerfac81132020-02-27 17:26:33 -0800586 Entry entry;
David Rogers98fea472020-04-01 15:43:48 -0700587 TRY_WITH_SIZE(ReadEntry(metadata, entry));
Wyatt Heplerfac81132020-02-27 17:26:33 -0800588
589 return StatusWithSize(entry.value_size());
Keir Mierle8c352dc2020-02-02 13:58:19 -0800590}
591
David Rogers9abe3c72020-03-24 19:03:13 -0700592Status KeyValueStore::CheckWriteOperation(string_view key) const {
Wyatt Hepleracaacf92020-01-24 10:58:30 -0800593 if (InvalidKey(key)) {
Wyatt Heplerb7609542020-01-24 10:29:54 -0800594 return Status::INVALID_ARGUMENT;
595 }
David Rogers9abe3c72020-03-24 19:03:13 -0700596
597 // For normal write operation the KVS must be fully ready.
Wyatt Heplerd2298282020-02-20 17:12:45 -0800598 if (!initialized()) {
Wyatt Heplerb7609542020-01-24 10:29:54 -0800599 return Status::FAILED_PRECONDITION;
600 }
Wyatt Heplerb7609542020-01-24 10:29:54 -0800601 return Status::OK;
602}
603
David Rogers9abe3c72020-03-24 19:03:13 -0700604Status KeyValueStore::CheckReadOperation(string_view key) const {
605 if (InvalidKey(key)) {
606 return Status::INVALID_ARGUMENT;
607 }
608
609 // Operations that are explicitly read-only can be done after init() has been
610 // called but not fully ready (when needing maintenance).
611 if (initialized_ == InitializationState::kNotInitialized) {
612 return Status::FAILED_PRECONDITION;
613 }
614 return Status::OK;
615}
616
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700617Status KeyValueStore::WriteEntryForExistingKey(EntryMetadata& metadata,
618 EntryState new_state,
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800619 string_view key,
620 span<const byte> value) {
Wyatt Heplerab3b2492020-03-11 16:15:16 -0700621 // Read the original entry to get the size for sector accounting purposes.
622 Entry entry;
David Rogers98fea472020-04-01 15:43:48 -0700623 TRY(ReadEntry(metadata, entry));
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800624
David Rogersc0104462020-05-08 15:50:23 -0700625 return WriteEntry(key, value, new_state, &metadata, &entry);
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800626}
627
628Status KeyValueStore::WriteEntryForNewKey(string_view key,
629 span<const byte> value) {
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700630 if (entry_cache_.full()) {
David Rogers9fc78b82020-06-12 13:56:12 -0700631 WRN("KVS full: trying to store a new entry, but can't. Have %u entries",
632 unsigned(entry_cache_.total_entries()));
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800633 return Status::RESOURCE_EXHAUSTED;
634 }
635
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700636 return WriteEntry(key, value, EntryState::kValid);
Wyatt Heplerab3b2492020-03-11 16:15:16 -0700637}
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800638
Wyatt Heplerab3b2492020-03-11 16:15:16 -0700639Status KeyValueStore::WriteEntry(string_view key,
640 span<const byte> value,
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700641 EntryState new_state,
642 EntryMetadata* prior_metadata,
David Rogersc0104462020-05-08 15:50:23 -0700643 const Entry* prior_entry) {
David Rogersc0104462020-05-08 15:50:23 -0700644 // If new entry and prior entry have matching value size, state, and checksum,
645 // check if the values match. Directly compare the prior and new values
646 // because the checksum can not be depended on to establish equality, it can
647 // only be depended on to establish inequality.
David Rogersd50eb1c2020-05-12 17:46:36 -0700648 if (prior_entry != nullptr && prior_entry->value_size() == value.size() &&
David Rogersc0104462020-05-08 15:50:23 -0700649 prior_metadata->state() == new_state &&
David Rogersc0104462020-05-08 15:50:23 -0700650 prior_entry->ValueMatches(value).ok()) {
David Rogersd50eb1c2020-05-12 17:46:36 -0700651 // The new value matches the prior value, don't need to write anything. Just
652 // keep the existing entry.
David Rogersc0104462020-05-08 15:50:23 -0700653 DBG("Write for key 0x%08x with matching value skipped",
654 unsigned(prior_metadata->hash()));
655 return Status::OK;
656 }
Wyatt Heplerab3b2492020-03-11 16:15:16 -0700657
658 // List of addresses for sectors with space for this entry.
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700659 Address* reserved_addresses = entry_cache_.TempReservedAddressesForWrite();
Wyatt Heplerab3b2492020-03-11 16:15:16 -0700660
David Rogers31b358b2020-04-15 05:00:50 -0700661 // Find addresses to write the entry to. This may involve garbage collecting
662 // one or more sectors.
David Rogersc0104462020-05-08 15:50:23 -0700663 const size_t entry_size = Entry::size(partition_, key, value);
David Rogers31b358b2020-04-15 05:00:50 -0700664 TRY(GetAddressesForWrite(reserved_addresses, entry_size));
Wyatt Heplerab3b2492020-03-11 16:15:16 -0700665
666 // Write the entry at the first address that was found.
David Rogersd50eb1c2020-05-12 17:46:36 -0700667 Entry entry = CreateEntry(reserved_addresses[0], key, value, new_state);
Wyatt Heplerab3b2492020-03-11 16:15:16 -0700668 TRY(AppendEntry(entry, key, value));
669
670 // After writing the first entry successfully, update the key descriptors.
671 // Once a single new the entry is written, the old entries are invalidated.
David Rogersc0104462020-05-08 15:50:23 -0700672 size_t prior_size = prior_entry != nullptr ? prior_entry->size() : 0;
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700673 EntryMetadata new_metadata =
David Rogers31b358b2020-04-15 05:00:50 -0700674 CreateOrUpdateKeyDescriptor(entry, key, prior_metadata, prior_size);
Wyatt Heplerab3b2492020-03-11 16:15:16 -0700675
676 // Write the additional copies of the entry, if redundancy is greater than 1.
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700677 for (size_t i = 1; i < redundancy(); ++i) {
678 entry.set_address(reserved_addresses[i]);
Wyatt Heplerab3b2492020-03-11 16:15:16 -0700679 TRY(AppendEntry(entry, key, value));
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700680 new_metadata.AddNewAddress(reserved_addresses[i]);
Wyatt Heplerab3b2492020-03-11 16:15:16 -0700681 }
Wyatt Heplerb7609542020-01-24 10:29:54 -0800682 return Status::OK;
683}
684
David Rogers31b358b2020-04-15 05:00:50 -0700685KeyValueStore::EntryMetadata KeyValueStore::CreateOrUpdateKeyDescriptor(
Wyatt Heplerab3b2492020-03-11 16:15:16 -0700686 const Entry& entry,
687 string_view key,
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700688 EntryMetadata* prior_metadata,
Wyatt Heplerab3b2492020-03-11 16:15:16 -0700689 size_t prior_size) {
690 // If there is no prior descriptor, create a new one.
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700691 if (prior_metadata == nullptr) {
692 return entry_cache_.AddNew(entry.descriptor(key), entry.address());
David Rogersa2562b52020-03-05 15:30:05 -0800693 }
694
David Rogers31b358b2020-04-15 05:00:50 -0700695 return UpdateKeyDescriptor(
696 entry, entry.address(), prior_metadata, prior_size);
697}
698
699KeyValueStore::EntryMetadata KeyValueStore::UpdateKeyDescriptor(
700 const Entry& entry,
701 Address new_address,
702 EntryMetadata* prior_metadata,
703 size_t prior_size) {
Wyatt Heplerab3b2492020-03-11 16:15:16 -0700704 // Remove valid bytes for the old entry and its copies, which are now stale.
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700705 for (Address address : prior_metadata->addresses()) {
Wyatt Heplerc84393f2020-03-20 11:23:24 -0700706 sectors_.FromAddress(address).RemoveValidBytes(prior_size);
David Rogersa2562b52020-03-05 15:30:05 -0800707 }
708
David Rogers31b358b2020-04-15 05:00:50 -0700709 prior_metadata->Reset(entry.descriptor(prior_metadata->hash()), new_address);
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700710 return *prior_metadata;
David Rogersa2562b52020-03-05 15:30:05 -0800711}
712
David Rogers31b358b2020-04-15 05:00:50 -0700713Status KeyValueStore::GetAddressesForWrite(Address* write_addresses,
714 size_t write_size) {
715 for (size_t i = 0; i < redundancy(); i++) {
716 SectorDescriptor* sector;
717 TRY(GetSectorForWrite(&sector, write_size, span(write_addresses, i)));
718 write_addresses[i] = sectors_.NextWritableAddress(*sector);
719
720 DBG("Found space for entry in sector %u at address %u",
721 sectors_.Index(sector),
722 unsigned(write_addresses[i]));
723 }
724
725 return Status::OK;
726}
727
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700728// Finds a sector to use for writing a new entry to. Does automatic garbage
David Rogersa2562b52020-03-05 15:30:05 -0800729// collection if needed and allowed.
730//
731// OK: Sector found with needed space.
732// RESOURCE_EXHAUSTED: No sector available with the needed space.
733Status KeyValueStore::GetSectorForWrite(SectorDescriptor** sector,
734 size_t entry_size,
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700735 span<const Address> reserved) {
Wyatt Heplerc84393f2020-03-20 11:23:24 -0700736 Status result = sectors_.FindSpace(sector, entry_size, reserved);
David Rogersa2562b52020-03-05 15:30:05 -0800737
David Rogersf3884eb2020-03-08 19:21:40 -0700738 size_t gc_sector_count = 0;
David Rogersa2562b52020-03-05 15:30:05 -0800739 bool do_auto_gc = options_.gc_on_write != GargbageCollectOnWrite::kDisabled;
740
741 // Do garbage collection as needed, so long as policy allows.
742 while (result == Status::RESOURCE_EXHAUSTED && do_auto_gc) {
743 if (options_.gc_on_write == GargbageCollectOnWrite::kOneSector) {
744 // If GC config option is kOneSector clear the flag to not do any more
745 // GC after this try.
746 do_auto_gc = false;
747 }
748 // Garbage collect and then try again to find the best sector.
David Rogers9abe3c72020-03-24 19:03:13 -0700749 Status gc_status = GarbageCollect(reserved);
David Rogersa2562b52020-03-05 15:30:05 -0800750 if (!gc_status.ok()) {
751 if (gc_status == Status::NOT_FOUND) {
752 // Not enough space, and no reclaimable bytes, this KVS is full!
753 return Status::RESOURCE_EXHAUSTED;
754 }
755 return gc_status;
756 }
757
Wyatt Heplerc84393f2020-03-20 11:23:24 -0700758 result = sectors_.FindSpace(sector, entry_size, reserved);
David Rogersf3884eb2020-03-08 19:21:40 -0700759
760 gc_sector_count++;
761 // Allow total sectors + 2 number of GC cycles so that once reclaimable
762 // bytes in all the sectors have been reclaimed can try and free up space by
763 // moving entries for keys other than the one being worked on in to sectors
764 // that have copies of the key trying to be written.
765 if (gc_sector_count > (partition_.sector_count() + 2)) {
766 ERR("Did more GC sectors than total sectors!!!!");
767 return Status::RESOURCE_EXHAUSTED;
768 }
David Rogersa2562b52020-03-05 15:30:05 -0800769 }
770
771 if (!result.ok()) {
David Rogers9fc78b82020-06-12 13:56:12 -0700772 WRN("Unable to find sector to write %u B", unsigned(entry_size));
David Rogersa2562b52020-03-05 15:30:05 -0800773 }
774 return result;
775}
776
David Rogers9abe3c72020-03-24 19:03:13 -0700777Status KeyValueStore::MarkSectorCorruptIfNotOk(Status status,
778 SectorDescriptor* sector) {
779 if (!status.ok()) {
780 DBG(" Sector %u corrupt", sectors_.Index(sector));
781 sector->mark_corrupt();
782 error_detected_ = true;
783 }
784 return status;
785}
786
Wyatt Heplerab3b2492020-03-11 16:15:16 -0700787Status KeyValueStore::AppendEntry(const Entry& entry,
David Rogersa2562b52020-03-05 15:30:05 -0800788 string_view key,
789 span<const byte> value) {
Wyatt Heplerab3b2492020-03-11 16:15:16 -0700790 const StatusWithSize result = entry.Write(key, value);
David Rogersa2562b52020-03-05 15:30:05 -0800791
Wyatt Heplerc84393f2020-03-20 11:23:24 -0700792 SectorDescriptor& sector = sectors_.FromAddress(entry.address());
David Rogersa2562b52020-03-05 15:30:05 -0800793
794 if (!result.ok()) {
David Rogers9fc78b82020-06-12 13:56:12 -0700795 ERR("Failed to write %u bytes at %#x. %u actually written",
796 unsigned(entry.size()),
797 unsigned(entry.address()),
798 unsigned(result.size()));
David Rogers9abe3c72020-03-24 19:03:13 -0700799 TRY(MarkSectorCorruptIfNotOk(result.status(), &sector));
David Rogersa2562b52020-03-05 15:30:05 -0800800 }
801
802 if (options_.verify_on_write) {
David Rogers9abe3c72020-03-24 19:03:13 -0700803 TRY(MarkSectorCorruptIfNotOk(entry.VerifyChecksumInFlash(), &sector));
David Rogersa2562b52020-03-05 15:30:05 -0800804 }
805
David Rogers98fea472020-04-01 15:43:48 -0700806 sector.RemoveWritableBytes(result.size());
Wyatt Heplerc84393f2020-03-20 11:23:24 -0700807 sector.AddValidBytes(result.size());
David Rogersa2562b52020-03-05 15:30:05 -0800808 return Status::OK;
809}
810
David Rogers98fea472020-04-01 15:43:48 -0700811StatusWithSize KeyValueStore::CopyEntryToSector(Entry& entry,
812 SectorDescriptor* new_sector,
David Rogers31b358b2020-04-15 05:00:50 -0700813 Address new_address) {
David Rogers98fea472020-04-01 15:43:48 -0700814 const StatusWithSize result = entry.Copy(new_address);
815
816 TRY_WITH_SIZE(MarkSectorCorruptIfNotOk(result.status(), new_sector));
817
818 if (options_.verify_on_write) {
David Rogers31b358b2020-04-15 05:00:50 -0700819 Entry new_entry;
820 TRY_WITH_SIZE(MarkSectorCorruptIfNotOk(
821 Entry::Read(partition_, new_address, formats_, &new_entry),
822 new_sector));
823 // TODO: add test that catches doing the verify on the old entry.
824 TRY_WITH_SIZE(MarkSectorCorruptIfNotOk(new_entry.VerifyChecksumInFlash(),
825 new_sector));
David Rogers98fea472020-04-01 15:43:48 -0700826 }
827 // Entry was written successfully; update descriptor's address and the sector
828 // descriptors to reflect the new entry.
829 new_sector->RemoveWritableBytes(result.size());
830 new_sector->AddValidBytes(result.size());
831
832 return result;
833}
834
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700835Status KeyValueStore::RelocateEntry(const EntryMetadata& metadata,
Wyatt Heplerab3b2492020-03-11 16:15:16 -0700836 KeyValueStore::Address& address,
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700837 span<const Address> reserved_addresses) {
David Rogersa2562b52020-03-05 15:30:05 -0800838 Entry entry;
David Rogers98fea472020-04-01 15:43:48 -0700839 TRY(ReadEntry(metadata, entry));
David Rogersa2562b52020-03-05 15:30:05 -0800840
841 // Find a new sector for the entry and write it to the new location. For
842 // relocation the find should not not be a sector already containing the key
843 // but can be the always empty sector, since this is part of the GC process
844 // that will result in a new empty sector. Also find a sector that does not
845 // have reclaimable space (mostly for the full GC, where that would result in
846 // an immediate extra relocation).
847 SectorDescriptor* new_sector;
848
Wyatt Heplerc84393f2020-03-20 11:23:24 -0700849 TRY(sectors_.FindSpaceDuringGarbageCollection(
850 &new_sector, entry.size(), metadata.addresses(), reserved_addresses));
Wyatt Heplerab3b2492020-03-11 16:15:16 -0700851
David Rogers31b358b2020-04-15 05:00:50 -0700852 Address new_address = sectors_.NextWritableAddress(*new_sector);
David Rogers98fea472020-04-01 15:43:48 -0700853 TRY_ASSIGN(const size_t result_size,
854 CopyEntryToSector(entry, new_sector, new_address));
855 sectors_.FromAddress(address).RemoveValidBytes(result_size);
Wyatt Heplerab3b2492020-03-11 16:15:16 -0700856 address = new_address;
David Rogersa2562b52020-03-05 15:30:05 -0800857
858 return Status::OK;
859}
860
David Rogers9abe3c72020-03-24 19:03:13 -0700861Status KeyValueStore::FullMaintenance() {
862 if (initialized_ == InitializationState::kNotInitialized) {
863 return Status::FAILED_PRECONDITION;
864 }
865
Armando Montanez17083bb2020-04-24 10:18:26 -0700866 // Full maintenance can be a potentially heavy operation, and should be
867 // relatively infrequent, so log start/end at INFO level.
868 INF("Beginning full maintenance");
David Rogers98fea472020-04-01 15:43:48 -0700869 CheckForErrors();
David Rogers9abe3c72020-03-24 19:03:13 -0700870
871 if (error_detected_) {
872 TRY(Repair());
873 }
David Rogers35c3f842020-04-22 15:34:05 -0700874 StatusWithSize update_status = UpdateEntriesToPrimaryFormat();
875 Status overall_status = update_status.status();
876
David Rogers31b358b2020-04-15 05:00:50 -0700877 // Make sure all the entries are on the primary format.
Armando Montanez17083bb2020-04-24 10:18:26 -0700878 if (!overall_status.ok()) {
879 ERR("Failed to update all entries to the primary format");
880 }
David Rogers31b358b2020-04-15 05:00:50 -0700881
Wyatt Heplerc84393f2020-03-20 11:23:24 -0700882 SectorDescriptor* sector = sectors_.last_new();
David Rogerscd87c322020-02-27 14:04:08 -0800883
David Rogers35c3f842020-04-22 15:34:05 -0700884 // Calculate number of bytes for the threshold.
885 size_t threshold_bytes =
886 (partition_.size_bytes() * kGcUsageThresholdPercentage) / 100;
887
888 // Is bytes in use over the threshold.
889 StorageStats stats = GetStorageStats();
890 bool over_usage_threshold = stats.in_use_bytes > threshold_bytes;
891 bool force_gc = over_usage_threshold || (update_status.size() > 0);
892
David Rogerscd87c322020-02-27 14:04:08 -0800893 // TODO: look in to making an iterator method for cycling through sectors
894 // starting from last_new_sector_.
Armando Montanez17083bb2020-04-24 10:18:26 -0700895 Status gc_status;
David Rogerscd87c322020-02-27 14:04:08 -0800896 for (size_t j = 0; j < sectors_.size(); j++) {
897 sector += 1;
898 if (sector == sectors_.end()) {
899 sector = sectors_.begin();
900 }
901
David Rogers35c3f842020-04-22 15:34:05 -0700902 if (sector->RecoverableBytes(partition_.sector_size_bytes()) > 0 &&
903 (force_gc || sector->valid_bytes() == 0)) {
Armando Montanez17083bb2020-04-24 10:18:26 -0700904 gc_status = GarbageCollectSector(*sector, {});
905 if (!gc_status.ok()) {
906 ERR("Failed to garbage collect all sectors");
907 break;
908 }
David Rogerscd87c322020-02-27 14:04:08 -0800909 }
910 }
Armando Montanez17083bb2020-04-24 10:18:26 -0700911 if (overall_status.ok()) {
912 overall_status = gc_status;
913 }
David Rogerscd87c322020-02-27 14:04:08 -0800914
Armando Montanez17083bb2020-04-24 10:18:26 -0700915 if (overall_status.ok()) {
916 INF("Full maintenance complete");
917 } else {
918 ERR("Full maintenance finished with some errors");
919 }
920 return overall_status;
David Rogerscd87c322020-02-27 14:04:08 -0800921}
922
David Rogers0f8a1bb2020-04-21 18:50:19 -0700923Status KeyValueStore::PartialMaintenance() {
David Rogers9abe3c72020-03-24 19:03:13 -0700924 if (initialized_ == InitializationState::kNotInitialized) {
925 return Status::FAILED_PRECONDITION;
926 }
927
David Rogers0f8a1bb2020-04-21 18:50:19 -0700928 CheckForErrors();
David Rogersfcea3252020-04-07 14:56:35 -0700929 // Do automatic repair, if KVS options allow for it.
930 if (error_detected_ && options_.recovery != ErrorRecovery::kManual) {
931 TRY(Repair());
932 }
David Rogers0f8a1bb2020-04-21 18:50:19 -0700933 return GarbageCollect(span<const Address>());
934}
935
936Status KeyValueStore::GarbageCollect(span<const Address> reserved_addresses) {
937 DBG("Garbage Collect a single sector");
938 for (Address address : reserved_addresses) {
939 DBG(" Avoid address %u", unsigned(address));
940 }
David Rogersfcea3252020-04-07 14:56:35 -0700941
David Rogersa12786b2020-01-31 16:02:33 -0800942 // Step 1: Find the sector to garbage collect
David Rogersc9d545e2020-03-11 17:47:43 -0700943 SectorDescriptor* sector_to_gc =
Wyatt Heplerc84393f2020-03-20 11:23:24 -0700944 sectors_.FindSectorToGarbageCollect(reserved_addresses);
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800945
David Rogersa12786b2020-01-31 16:02:33 -0800946 if (sector_to_gc == nullptr) {
David Rogersa2562b52020-03-05 15:30:05 -0800947 // Nothing to GC.
948 return Status::NOT_FOUND;
David Rogersa12786b2020-01-31 16:02:33 -0800949 }
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800950
David Rogersc9d545e2020-03-11 17:47:43 -0700951 // Step 2: Garbage collect the selected sector.
Wyatt Heplerc84393f2020-03-20 11:23:24 -0700952 return GarbageCollectSector(*sector_to_gc, reserved_addresses);
David Rogerscd87c322020-02-27 14:04:08 -0800953}
954
David Rogersf3884eb2020-03-08 19:21:40 -0700955Status KeyValueStore::RelocateKeyAddressesInSector(
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700956 SectorDescriptor& sector_to_gc,
David Rogersfcea3252020-04-07 14:56:35 -0700957 const EntryMetadata& metadata,
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700958 span<const Address> reserved_addresses) {
959 for (FlashPartition::Address& address : metadata.addresses()) {
Wyatt Heplerc84393f2020-03-20 11:23:24 -0700960 if (sectors_.AddressInSector(sector_to_gc, address)) {
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700961 DBG(" Relocate entry for Key 0x%08" PRIx32 ", sector %u",
962 metadata.hash(),
Wyatt Heplerc84393f2020-03-20 11:23:24 -0700963 sectors_.Index(sectors_.FromAddress(address)));
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700964 TRY(RelocateEntry(metadata, address, reserved_addresses));
David Rogersf3884eb2020-03-08 19:21:40 -0700965 }
966 }
Wyatt Heplerab3b2492020-03-11 16:15:16 -0700967
David Rogersf3884eb2020-03-08 19:21:40 -0700968 return Status::OK;
969};
970
Wyatt Heplerab3b2492020-03-11 16:15:16 -0700971Status KeyValueStore::GarbageCollectSector(
Wyatt Heplerc84393f2020-03-20 11:23:24 -0700972 SectorDescriptor& sector_to_gc, span<const Address> reserved_addresses) {
David Rogers9abe3c72020-03-24 19:03:13 -0700973 DBG(" Garbage Collect sector %u", sectors_.Index(sector_to_gc));
David Rogersf3884eb2020-03-08 19:21:40 -0700974 // Step 1: Move any valid entries in the GC sector to other sectors
Wyatt Heplerc84393f2020-03-20 11:23:24 -0700975 if (sector_to_gc.valid_bytes() != 0) {
David Rogers98fea472020-04-01 15:43:48 -0700976 for (EntryMetadata& metadata : entry_cache_) {
Wyatt Heplerab3b2492020-03-11 16:15:16 -0700977 TRY(RelocateKeyAddressesInSector(
Wyatt Heplerc84393f2020-03-20 11:23:24 -0700978 sector_to_gc, metadata, reserved_addresses));
David Rogersf3884eb2020-03-08 19:21:40 -0700979 }
980 }
981
Wyatt Heplerc84393f2020-03-20 11:23:24 -0700982 if (sector_to_gc.valid_bytes() != 0) {
David Rogers67f4b6c2020-02-06 16:17:09 -0800983 ERR(" Failed to relocate valid entries from sector being garbage "
David Rogers9fc78b82020-06-12 13:56:12 -0700984 "collected, %u valid bytes remain",
985 unsigned(sector_to_gc.valid_bytes()));
Wyatt Heplerb7609542020-01-24 10:29:54 -0800986 return Status::INTERNAL;
987 }
988
David Rogerscd87c322020-02-27 14:04:08 -0800989 // Step 2: Reinitialize the sector
David Rogers9abe3c72020-03-24 19:03:13 -0700990 sector_to_gc.mark_corrupt();
Wyatt Heplerc84393f2020-03-20 11:23:24 -0700991 TRY(partition_.Erase(sectors_.BaseAddress(sector_to_gc), 1));
992 sector_to_gc.set_writable_bytes(partition_.sector_size_bytes());
Wyatt Heplerb7609542020-01-24 10:29:54 -0800993
Wyatt Heplerc84393f2020-03-20 11:23:24 -0700994 DBG(" Garbage Collect sector %u complete", sectors_.Index(sector_to_gc));
David Rogersa12786b2020-01-31 16:02:33 -0800995 return Status::OK;
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800996}
997
David Rogers35c3f842020-04-22 15:34:05 -0700998StatusWithSize KeyValueStore::UpdateEntriesToPrimaryFormat() {
999 size_t entries_updated = 0;
David Rogers31b358b2020-04-15 05:00:50 -07001000 for (EntryMetadata& prior_metadata : entry_cache_) {
1001 Entry entry;
David Rogers35c3f842020-04-22 15:34:05 -07001002 TRY_WITH_SIZE(ReadEntry(prior_metadata, entry));
David Rogers31b358b2020-04-15 05:00:50 -07001003 if (formats_.primary().magic == entry.magic()) {
1004 // Ignore entries that are already on the primary format.
1005 continue;
1006 }
1007
1008 DBG("Updating entry 0x%08x from old format [0x%08x] to new format "
1009 "[0x%08x]",
1010 unsigned(prior_metadata.hash()),
1011 unsigned(entry.magic()),
1012 unsigned(formats_.primary().magic));
1013
David Rogers35c3f842020-04-22 15:34:05 -07001014 entries_updated++;
1015
David Rogers31b358b2020-04-15 05:00:50 -07001016 last_transaction_id_ += 1;
David Rogers35c3f842020-04-22 15:34:05 -07001017 TRY_WITH_SIZE(entry.Update(formats_.primary(), last_transaction_id_));
David Rogers31b358b2020-04-15 05:00:50 -07001018
1019 // List of addresses for sectors with space for this entry.
1020 Address* reserved_addresses = entry_cache_.TempReservedAddressesForWrite();
1021
1022 // Find addresses to write the entry to. This may involve garbage collecting
1023 // one or more sectors.
David Rogers35c3f842020-04-22 15:34:05 -07001024 TRY_WITH_SIZE(GetAddressesForWrite(reserved_addresses, entry.size()));
David Rogers31b358b2020-04-15 05:00:50 -07001025
David Rogers35c3f842020-04-22 15:34:05 -07001026 TRY_WITH_SIZE(
1027 CopyEntryToSector(entry,
David Rogers31b358b2020-04-15 05:00:50 -07001028 &sectors_.FromAddress(reserved_addresses[0]),
1029 reserved_addresses[0]));
1030
1031 // After writing the first entry successfully, update the key descriptors.
1032 // Once a single new the entry is written, the old entries are invalidated.
1033 EntryMetadata new_metadata = UpdateKeyDescriptor(
1034 entry, reserved_addresses[0], &prior_metadata, entry.size());
1035
1036 // Write the additional copies of the entry, if redundancy is greater
1037 // than 1.
1038 for (size_t i = 1; i < redundancy(); ++i) {
David Rogers35c3f842020-04-22 15:34:05 -07001039 TRY_WITH_SIZE(
1040 CopyEntryToSector(entry,
David Rogers31b358b2020-04-15 05:00:50 -07001041 &sectors_.FromAddress(reserved_addresses[i]),
1042 reserved_addresses[i]));
1043 new_metadata.AddNewAddress(reserved_addresses[i]);
1044 }
1045 }
David Rogers35c3f842020-04-22 15:34:05 -07001046
1047 return StatusWithSize(entries_updated);
David Rogers31b358b2020-04-15 05:00:50 -07001048}
1049
David Rogers9abe3c72020-03-24 19:03:13 -07001050// Add any missing redundant entries/copies for a key.
1051Status KeyValueStore::AddRedundantEntries(EntryMetadata& metadata) {
David Rogers9abe3c72020-03-24 19:03:13 -07001052 Entry entry;
David Rogers98fea472020-04-01 15:43:48 -07001053 TRY(ReadEntry(metadata, entry));
David Rogers9abe3c72020-03-24 19:03:13 -07001054 TRY(entry.VerifyChecksumInFlash());
1055
David Rogers0f8a1bb2020-04-21 18:50:19 -07001056 while (metadata.addresses().size() < redundancy()) {
1057 SectorDescriptor* new_sector;
1058 TRY(GetSectorForWrite(&new_sector, entry.size(), metadata.addresses()));
David Rogers9abe3c72020-03-24 19:03:13 -07001059
David Rogers31b358b2020-04-15 05:00:50 -07001060 Address new_address = sectors_.NextWritableAddress(*new_sector);
David Rogers98fea472020-04-01 15:43:48 -07001061 TRY(CopyEntryToSector(entry, new_sector, new_address));
David Rogers9abe3c72020-03-24 19:03:13 -07001062
1063 metadata.AddNewAddress(new_address);
1064 }
1065 return Status::OK;
1066}
1067
1068Status KeyValueStore::RepairCorruptSectors() {
1069 // Try to GC each corrupt sector, even if previous sectors fail. If GC of a
1070 // sector failed on the first pass, then do a second pass, since a later
1071 // sector might have cleared up space or otherwise unblocked the earlier
1072 // failed sector.
1073 Status repair_status = Status::OK;
1074
1075 size_t loop_count = 0;
1076 do {
1077 loop_count++;
1078 // Error of RESOURCE_EXHAUSTED indicates no space found for relocation.
1079 // Reset back to OK for the next pass.
1080 if (repair_status == Status::RESOURCE_EXHAUSTED) {
1081 repair_status = Status::OK;
1082 }
1083
1084 DBG(" Pass %u", unsigned(loop_count));
1085 for (SectorDescriptor& sector : sectors_) {
1086 if (sector.corrupt()) {
1087 DBG(" Found sector %u with corruption", sectors_.Index(sector));
1088 Status sector_status = GarbageCollectSector(sector, {});
1089 if (sector_status.ok()) {
1090 error_stats_.corrupt_sectors_recovered += 1;
1091 } else if (repair_status.ok() ||
1092 repair_status == Status::RESOURCE_EXHAUSTED) {
1093 repair_status = sector_status;
1094 }
1095 }
1096 }
1097 DBG(" Pass %u complete", unsigned(loop_count));
1098 } while (!repair_status.ok() && loop_count < 2);
1099
1100 return repair_status;
1101}
1102
1103Status KeyValueStore::EnsureFreeSectorExists() {
1104 Status repair_status = Status::OK;
1105 bool empty_sector_found = false;
1106
1107 DBG(" Find empty sector");
1108 for (SectorDescriptor& sector : sectors_) {
1109 if (sector.Empty(partition_.sector_size_bytes())) {
1110 empty_sector_found = true;
1111 DBG(" Empty sector found");
1112 break;
1113 }
1114 }
1115 if (empty_sector_found == false) {
1116 DBG(" No empty sector found, attempting to GC a free sector");
1117 Status sector_status = GarbageCollect(span<const Address, 0>());
1118 if (repair_status.ok() && !sector_status.ok()) {
1119 DBG(" Unable to free an empty sector");
1120 repair_status = sector_status;
1121 }
1122 }
1123
1124 return repair_status;
1125}
1126
1127Status KeyValueStore::EnsureEntryRedundancy() {
1128 Status repair_status = Status::OK;
1129
1130 if (redundancy() == 1) {
David Rogers98fea472020-04-01 15:43:48 -07001131 DBG(" Redundancy not in use, nothting to check");
David Rogers9abe3c72020-03-24 19:03:13 -07001132 return Status::OK;
1133 }
1134
David Rogers98fea472020-04-01 15:43:48 -07001135 DBG(" Write any needed additional duplicate copies of keys to fulfill %u"
1136 " redundancy",
David Rogers9abe3c72020-03-24 19:03:13 -07001137 unsigned(redundancy()));
David Rogers98fea472020-04-01 15:43:48 -07001138 for (EntryMetadata& metadata : entry_cache_) {
David Rogers9abe3c72020-03-24 19:03:13 -07001139 if (metadata.addresses().size() >= redundancy()) {
1140 continue;
1141 }
1142
1143 DBG(" Key with %u of %u copies found, adding missing copies",
1144 unsigned(metadata.addresses().size()),
1145 unsigned(redundancy()));
David Rogers98fea472020-04-01 15:43:48 -07001146 Status fill_status = AddRedundantEntries(metadata);
David Rogers9abe3c72020-03-24 19:03:13 -07001147 if (fill_status.ok()) {
1148 error_stats_.missing_redundant_entries_recovered += 1;
1149 DBG(" Key missing copies added");
1150 } else {
1151 DBG(" Failed to add key missing copies");
1152 if (repair_status.ok()) {
1153 repair_status = fill_status;
1154 }
1155 }
1156 }
1157
1158 return repair_status;
1159}
1160
David Rogersfcea3252020-04-07 14:56:35 -07001161Status KeyValueStore::FixErrors() {
1162 DBG("Fixing KVS errors");
David Rogers9abe3c72020-03-24 19:03:13 -07001163
1164 // Step 1: Garbage collect any sectors marked as corrupt.
David Rogersfcea3252020-04-07 14:56:35 -07001165 Status overall_status = RepairCorruptSectors();
David Rogers9abe3c72020-03-24 19:03:13 -07001166
1167 // Step 2: Make sure there is at least 1 empty sector. This needs to be a
1168 // seperate check of sectors from step 1, because a found empty sector might
1169 // get written to by a later GC that fails and does not result in a free
1170 // sector.
David Rogersfcea3252020-04-07 14:56:35 -07001171 Status repair_status = EnsureFreeSectorExists();
David Rogers9abe3c72020-03-24 19:03:13 -07001172 if (overall_status.ok()) {
1173 overall_status = repair_status;
1174 }
1175
1176 // Step 3: Make sure each stored key has the full number of redundant
1177 // entries.
1178 repair_status = EnsureEntryRedundancy();
1179 if (overall_status.ok()) {
1180 overall_status = repair_status;
1181 }
1182
1183 if (overall_status.ok()) {
1184 error_detected_ = false;
1185 initialized_ = InitializationState::kReady;
1186 }
1187 return overall_status;
1188}
1189
David Rogersfcea3252020-04-07 14:56:35 -07001190Status KeyValueStore::Repair() {
1191 // If errors have been detected, just reinit the KVS metadata. This does a
1192 // full deep error check and any needed repairs. Then repair any errors.
1193 INF("Starting KVS repair");
1194
1195 DBG("Reinitialize KVS metadata");
1196 InitializeMetadata();
1197
1198 return FixErrors();
1199}
1200
David Rogersd50eb1c2020-05-12 17:46:36 -07001201KeyValueStore::Entry KeyValueStore::CreateEntry(Address address,
1202 string_view key,
Wyatt Heplerbdd8e5a2020-02-20 19:27:26 -08001203 span<const byte> value,
Wyatt Hepler7ded6da2020-03-11 18:24:43 -07001204 EntryState state) {
Keir Mierle9e38b402020-02-21 13:06:21 -08001205 // Always bump the transaction ID when creating a new entry.
1206 //
1207 // Burning transaction IDs prevents inconsistencies between flash and memory
1208 // that which could happen if a write succeeds, but for some reason the read
1209 // and verify step fails. Here's how this would happen:
1210 //
1211 // 1. The entry is written but for some reason the flash reports failure OR
1212 // The write succeeds, but the read / verify operation fails.
1213 // 2. The transaction ID is NOT incremented, because of the failure
1214 // 3. (later) A new entry is written, re-using the transaction ID (oops)
1215 //
David Rogersd50eb1c2020-05-12 17:46:36 -07001216 // By always burning transaction IDs, the above problem can't happen.
1217 last_transaction_id_ += 1;
Keir Mierle9e38b402020-02-21 13:06:21 -08001218
Wyatt Hepler7ded6da2020-03-11 18:24:43 -07001219 if (state == EntryState::kDeleted) {
Wyatt Hepler7465be32020-02-21 15:30:53 -08001220 return Entry::Tombstone(
David Rogersd50eb1c2020-05-12 17:46:36 -07001221 partition_, address, formats_.primary(), key, last_transaction_id_);
Wyatt Hepler1fc11042020-02-19 17:17:51 -08001222 }
David Rogersd50eb1c2020-05-12 17:46:36 -07001223 return Entry::Valid(partition_,
1224 address,
1225 formats_.primary(),
1226 key,
1227 value,
1228 last_transaction_id_);
Wyatt Heplerd2298282020-02-20 17:12:45 -08001229}
1230
Wyatt Hepler7ded6da2020-03-11 18:24:43 -07001231void KeyValueStore::LogDebugInfo() const {
Keir Mierle8c352dc2020-02-02 13:58:19 -08001232 const size_t sector_size_bytes = partition_.sector_size_bytes();
1233 DBG("====================== KEY VALUE STORE DUMP =========================");
1234 DBG(" ");
1235 DBG("Flash partition:");
David Rogers9fc78b82020-06-12 13:56:12 -07001236 DBG(" Sector count = %u", unsigned(partition_.sector_count()));
1237 DBG(" Sector max count = %u", unsigned(sectors_.max_size()));
1238 DBG(" Sectors in use = %u", unsigned(sectors_.size()));
1239 DBG(" Sector size = %u", unsigned(sector_size_bytes));
1240 DBG(" Total size = %u", unsigned(partition_.size_bytes()));
1241 DBG(" Alignment = %u", unsigned(partition_.alignment_bytes()));
Keir Mierle8c352dc2020-02-02 13:58:19 -08001242 DBG(" ");
1243 DBG("Key descriptors:");
David Rogers9fc78b82020-06-12 13:56:12 -07001244 DBG(" Entry count = %u", unsigned(entry_cache_.total_entries()));
1245 DBG(" Max entry count = %u", unsigned(entry_cache_.max_entries()));
Keir Mierle8c352dc2020-02-02 13:58:19 -08001246 DBG(" ");
1247 DBG(" # hash version address address (hex)");
Armando Montanez888370d2020-05-01 18:29:22 -07001248 size_t count = 0;
Wyatt Hepler7ded6da2020-03-11 18:24:43 -07001249 for (const EntryMetadata& metadata : entry_cache_) {
Keir Mierle8c352dc2020-02-02 13:58:19 -08001250 DBG(" |%3zu: | %8zx |%8zu | %8zu | %8zx",
Armando Montanez888370d2020-05-01 18:29:22 -07001251 count++,
Wyatt Hepler7ded6da2020-03-11 18:24:43 -07001252 size_t(metadata.hash()),
1253 size_t(metadata.transaction_id()),
1254 size_t(metadata.first_address()),
1255 size_t(metadata.first_address()));
Keir Mierle8c352dc2020-02-02 13:58:19 -08001256 }
1257 DBG(" ");
1258
1259 DBG("Sector descriptors:");
1260 DBG(" # tail free valid has_space");
Wyatt Heplerc84393f2020-03-20 11:23:24 -07001261 for (const SectorDescriptor& sd : sectors_) {
1262 DBG(" |%3u: | %8zu |%8zu | %s",
1263 sectors_.Index(sd),
Wyatt Hepler2c7eca02020-02-18 16:01:42 -08001264 size_t(sd.writable_bytes()),
1265 sd.valid_bytes(),
1266 sd.writable_bytes() ? "YES" : "");
Keir Mierle8c352dc2020-02-02 13:58:19 -08001267 }
1268 DBG(" ");
1269
1270 // TODO: This should stop logging after some threshold.
1271 // size_t dumped_bytes = 0;
1272 DBG("Sector raw data:");
Wyatt Hepler1c329ca2020-02-07 18:07:23 -08001273 for (size_t sector_id = 0; sector_id < sectors_.size(); ++sector_id) {
Keir Mierle8c352dc2020-02-02 13:58:19 -08001274 // Read sector data. Yes, this will blow the stack on embedded.
Wyatt Hepler1c329ca2020-02-07 18:07:23 -08001275 std::array<byte, 500> raw_sector_data; // TODO!!!
Keir Mierle8c352dc2020-02-02 13:58:19 -08001276 StatusWithSize sws =
1277 partition_.Read(sector_id * sector_size_bytes, raw_sector_data);
David Rogers9fc78b82020-06-12 13:56:12 -07001278 DBG("Read: %u bytes", unsigned(sws.size()));
Keir Mierle8c352dc2020-02-02 13:58:19 -08001279
1280 DBG(" base addr offs 0 1 2 3 4 5 6 7");
1281 for (size_t i = 0; i < sector_size_bytes; i += 8) {
1282 DBG(" %3zu %8zx %5zu | %02x %02x %02x %02x %02x %02x %02x %02x",
1283 sector_id,
1284 (sector_id * sector_size_bytes) + i,
1285 i,
1286 static_cast<unsigned int>(raw_sector_data[i + 0]),
1287 static_cast<unsigned int>(raw_sector_data[i + 1]),
1288 static_cast<unsigned int>(raw_sector_data[i + 2]),
1289 static_cast<unsigned int>(raw_sector_data[i + 3]),
1290 static_cast<unsigned int>(raw_sector_data[i + 4]),
1291 static_cast<unsigned int>(raw_sector_data[i + 5]),
1292 static_cast<unsigned int>(raw_sector_data[i + 6]),
1293 static_cast<unsigned int>(raw_sector_data[i + 7]));
1294
1295 // TODO: Fix exit condition.
1296 if (i > 128) {
1297 break;
1298 }
1299 }
1300 DBG(" ");
1301 }
1302
1303 DBG("////////////////////// KEY VALUE STORE DUMP END /////////////////////");
1304}
1305
David Rogerscf680ab2020-02-12 23:28:32 -08001306void KeyValueStore::LogSectors() const {
David Rogers9fc78b82020-06-12 13:56:12 -07001307 DBG("Sector descriptors: count %u", unsigned(sectors_.size()));
Wyatt Hepler1c329ca2020-02-07 18:07:23 -08001308 for (auto& sector : sectors_) {
David Rogers9fc78b82020-06-12 13:56:12 -07001309 DBG(" - Sector %u: valid %u, recoverable %u, free %u",
Wyatt Heplerc84393f2020-03-20 11:23:24 -07001310 sectors_.Index(sector),
David Rogers9fc78b82020-06-12 13:56:12 -07001311 unsigned(sector.valid_bytes()),
1312 unsigned(sector.RecoverableBytes(partition_.sector_size_bytes())),
1313 unsigned(sector.writable_bytes()));
David Rogers50185ad2020-02-07 00:02:46 -08001314 }
1315}
1316
David Rogerscf680ab2020-02-12 23:28:32 -08001317void KeyValueStore::LogKeyDescriptor() const {
David Rogers9fc78b82020-06-12 13:56:12 -07001318 DBG("Key descriptors: count %u", unsigned(entry_cache_.total_entries()));
David Rogers9abe3c72020-03-24 19:03:13 -07001319 for (const EntryMetadata& metadata : entry_cache_) {
David Rogers9fc78b82020-06-12 13:56:12 -07001320 DBG(" - Key: %s, hash %#x, transaction ID %u, first address %#x",
Wyatt Hepler02946272020-03-18 10:36:22 -07001321 metadata.state() == EntryState::kDeleted ? "Deleted" : "Valid",
David Rogers9fc78b82020-06-12 13:56:12 -07001322 unsigned(metadata.hash()),
1323 unsigned(metadata.transaction_id()),
1324 unsigned(metadata.first_address()));
David Rogerscf680ab2020-02-12 23:28:32 -08001325 }
1326}
1327
Wyatt Hepler2ad60672020-01-21 08:00:16 -08001328} // namespace pw::kvs