blob: 752590d58cf4587e394eee21fd392efcea572e30 [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"
Keir Mierled28068e2020-08-14 16:41:44 -070016#define PW_LOG_USE_ULTRA_SHORT_NAMES 1
Armando Montanez28ecccb2020-05-04 15:35:54 -070017
Wyatt Heplerb7609542020-01-24 10:29:54 -080018#include "pw_kvs/key_value_store.h"
19
Wyatt Heplerbab0e202020-02-04 07:40:08 -080020#include <algorithm>
Wyatt Hepler5a33d8c2020-02-06 09:32:58 -080021#include <cinttypes>
Wyatt Heplerb7609542020-01-24 10:29:54 -080022#include <cstring>
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -080023#include <type_traits>
Wyatt Heplerb7609542020-01-24 10:29:54 -080024
David Rogersc0104462020-05-08 15:50:23 -070025#include "pw_assert/assert.h"
Keir Mierle8c352dc2020-02-02 13:58:19 -080026#include "pw_log/log.h"
David Rogersb6b14b82020-09-11 16:27:27 -070027#include "pw_status/try.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 Heplere2cbadf2020-06-22 11:21:45 -070042 std::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 Rogers3c298372020-10-12 14:15:39 -070056 internal_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 Heplerd78f7c62020-09-28 14:27:32 -070070 return Status::FailedPrecondition();
Wyatt Heplerad0a7932020-02-06 08:20:38 -080071 }
72
David Rogers178002a2020-06-16 13:52:54 -070073 if (partition_.sector_count() < 2) {
74 ERR("KVS init failed: FlashParition sector count (=%u) must be at 2. KVS "
75 "requires at least 1 working sector + 1 free/reserved sector",
76 unsigned(partition_.sector_count()));
Wyatt Heplerd78f7c62020-09-28 14:27:32 -070077 return Status::FailedPrecondition();
David Rogers178002a2020-06-16 13:52:54 -070078 }
79
Keir Mierle8c352dc2020-02-02 13:58:19 -080080 const size_t sector_size_bytes = partition_.sector_size_bytes();
Keir Mierle8c352dc2020-02-02 13:58:19 -080081
David Rogers49766d92020-03-20 10:55:54 -070082 // TODO: investigate doing this as a static assert/compile-time check.
83 if (sector_size_bytes > SectorDescriptor::max_sector_size()) {
David Rogers9fc78b82020-06-12 13:56:12 -070084 ERR("KVS init failed: sector_size_bytes (=%u) is greater than maximum "
85 "allowed sector size (=%u)",
86 unsigned(sector_size_bytes),
87 unsigned(SectorDescriptor::max_sector_size()));
Wyatt Heplerd78f7c62020-09-28 14:27:32 -070088 return Status::FailedPrecondition();
David Rogers49766d92020-03-20 10:55:54 -070089 }
90
David Rogerscd134352020-04-17 19:37:15 -070091 Status metadata_result = InitializeMetadata();
David Rogersfcea3252020-04-07 14:56:35 -070092
93 if (!error_detected_) {
94 initialized_ = InitializationState::kReady;
95 } else {
David Rogers0f8a1bb2020-04-21 18:50:19 -070096 initialized_ = InitializationState::kNeedsMaintenance;
97
David Rogersfcea3252020-04-07 14:56:35 -070098 if (options_.recovery != ErrorRecovery::kManual) {
Armando Montanezf8419ae2020-04-21 10:03:05 -070099 size_t pre_fix_redundancy_errors =
David Rogers3c298372020-10-12 14:15:39 -0700100 internal_stats_.missing_redundant_entries_recovered;
David Rogersfcea3252020-04-07 14:56:35 -0700101 Status recovery_status = FixErrors();
102
103 if (recovery_status.ok()) {
Wyatt Heplerd78f7c62020-09-28 14:27:32 -0700104 if (metadata_result == Status::OutOfRange()) {
David Rogers3c298372020-10-12 14:15:39 -0700105 internal_stats_.missing_redundant_entries_recovered =
Armando Montanezf8419ae2020-04-21 10:03:05 -0700106 pre_fix_redundancy_errors;
David Rogerscd134352020-04-17 19:37:15 -0700107 INF("KVS init: Redundancy level successfully updated");
108 } else {
109 WRN("KVS init: Corruption detected and fully repaired");
110 }
David Rogersfcea3252020-04-07 14:56:35 -0700111 initialized_ = InitializationState::kReady;
Wyatt Heplerd78f7c62020-09-28 14:27:32 -0700112 } else if (recovery_status == Status::ResourceExhausted()) {
David Rogersfcea3252020-04-07 14:56:35 -0700113 WRN("KVS init: Unable to maintain required free sector");
David Rogersfcea3252020-04-07 14:56:35 -0700114 } else {
115 WRN("KVS init: Corruption detected and unable repair");
David Rogersfcea3252020-04-07 14:56:35 -0700116 }
117 } else {
118 WRN("KVS init: Corruption detected, no repair attempted due to options");
David Rogersfcea3252020-04-07 14:56:35 -0700119 }
120 }
121
David Rogers9fc78b82020-06-12 13:56:12 -0700122 INF("KeyValueStore init complete: active keys %u, deleted keys %u, sectors "
123 "%u, logical sector size %u bytes",
124 unsigned(size()),
125 unsigned(entry_cache_.total_entries() - size()),
126 unsigned(sectors_.size()),
127 unsigned(partition_.sector_size_bytes()));
David Rogersfcea3252020-04-07 14:56:35 -0700128
129 // Report any corruption was not repaired.
130 if (error_detected_) {
131 WRN("KVS init: Corruption found but not repaired, KVS unavailable until "
132 "successful maintenance.");
Wyatt Heplerd78f7c62020-09-28 14:27:32 -0700133 return Status::DataLoss();
David Rogersfcea3252020-04-07 14:56:35 -0700134 }
135
Wyatt Heplerd78f7c62020-09-28 14:27:32 -0700136 return Status::Ok();
David Rogersfcea3252020-04-07 14:56:35 -0700137}
138
David Rogerscd134352020-04-17 19:37:15 -0700139Status KeyValueStore::InitializeMetadata() {
David Rogersfcea3252020-04-07 14:56:35 -0700140 const size_t sector_size_bytes = partition_.sector_size_bytes();
141
142 sectors_.Reset();
143 entry_cache_.Reset();
144
Keir Mierle8c352dc2020-02-02 13:58:19 -0800145 DBG("First pass: Read all entries from all sectors");
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800146 Address sector_address = 0;
Keir Mierle8c352dc2020-02-02 13:58:19 -0800147
Alexei Frolovd4adf912020-02-21 13:29:15 -0800148 size_t total_corrupt_bytes = 0;
David Rogerscd134352020-04-17 19:37:15 -0700149 size_t corrupt_entries = 0;
David Rogers91627482020-02-27 17:38:12 -0800150 bool empty_sector_found = false;
David Rogerscd134352020-04-17 19:37:15 -0700151 size_t entry_copies_missing = 0;
Alexei Frolovd4adf912020-02-21 13:29:15 -0800152
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800153 for (SectorDescriptor& sector : sectors_) {
Keir Mierle8c352dc2020-02-02 13:58:19 -0800154 Address entry_address = sector_address;
155
Alexei Frolovd4adf912020-02-21 13:29:15 -0800156 size_t sector_corrupt_bytes = 0;
157
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800158 for (int num_entries_in_sector = 0; true; num_entries_in_sector++) {
David Rogersfcea3252020-04-07 14:56:35 -0700159 DBG("Load entry: sector=%u, entry#=%d, address=%u",
160 unsigned(sector_address),
Keir Mierle8c352dc2020-02-02 13:58:19 -0800161 num_entries_in_sector,
David Rogersfcea3252020-04-07 14:56:35 -0700162 unsigned(entry_address));
Keir Mierle8c352dc2020-02-02 13:58:19 -0800163
Wyatt Heplerc84393f2020-03-20 11:23:24 -0700164 if (!sectors_.AddressInSector(sector, entry_address)) {
Keir Mierle8c352dc2020-02-02 13:58:19 -0800165 DBG("Fell off end of sector; moving to the next sector");
166 break;
167 }
168
169 Address next_entry_address;
170 Status status = LoadEntry(entry_address, &next_entry_address);
Wyatt Heplerd78f7c62020-09-28 14:27:32 -0700171 if (status == Status::NotFound()) {
Keir Mierle8c352dc2020-02-02 13:58:19 -0800172 DBG("Hit un-written data in sector; moving to the next sector");
173 break;
David Rogersfcea3252020-04-07 14:56:35 -0700174 } else if (!status.ok()) {
175 // The entry could not be read, indicating likely data corruption within
176 // the sector. Try to scan the remainder of the sector for other
177 // entries.
Alexei Frolovd4adf912020-02-21 13:29:15 -0800178
David Rogers49766d92020-03-20 10:55:54 -0700179 error_detected_ = true;
Alexei Frolovd4adf912020-02-21 13:29:15 -0800180 corrupt_entries++;
181
182 status = ScanForEntry(sector,
183 entry_address + Entry::kMinAlignmentBytes,
184 &next_entry_address);
David Rogersfcea3252020-04-07 14:56:35 -0700185 if (!status.ok()) {
Alexei Frolovd4adf912020-02-21 13:29:15 -0800186 // No further entries in this sector. Mark the remaining bytes in the
187 // sector as corrupt (since we can't reliably know the size of the
188 // corrupt entry).
189 sector_corrupt_bytes +=
190 sector_size_bytes - (entry_address - sector_address);
191 break;
192 }
193
Alexei Frolovd4adf912020-02-21 13:29:15 -0800194 sector_corrupt_bytes += next_entry_address - entry_address;
Keir Mierle8c352dc2020-02-02 13:58:19 -0800195 }
Keir Mierle8c352dc2020-02-02 13:58:19 -0800196
197 // Entry loaded successfully; so get ready to load the next one.
198 entry_address = next_entry_address;
199
200 // Update of the number of writable bytes in this sector.
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800201 sector.set_writable_bytes(sector_size_bytes -
202 (entry_address - sector_address));
Keir Mierle8c352dc2020-02-02 13:58:19 -0800203 }
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800204
Alexei Frolovd4adf912020-02-21 13:29:15 -0800205 if (sector_corrupt_bytes > 0) {
206 // If the sector contains corrupt data, prevent any further entries from
207 // being written to it by indicating that it has no space. This should
208 // also make it a decent GC candidate. Valid keys in the sector are still
209 // readable as normal.
David Rogers49766d92020-03-20 10:55:54 -0700210 sector.mark_corrupt();
211 error_detected_ = true;
Alexei Frolovd4adf912020-02-21 13:29:15 -0800212
David Rogers9fc78b82020-06-12 13:56:12 -0700213 WRN("Sector %u contains %uB of corrupt data",
Wyatt Heplerc84393f2020-03-20 11:23:24 -0700214 sectors_.Index(sector),
David Rogers9fc78b82020-06-12 13:56:12 -0700215 unsigned(sector_corrupt_bytes));
Alexei Frolovd4adf912020-02-21 13:29:15 -0800216 }
217
David Rogers91627482020-02-27 17:38:12 -0800218 if (sector.Empty(sector_size_bytes)) {
219 empty_sector_found = true;
220 }
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800221 sector_address += sector_size_bytes;
Alexei Frolovd4adf912020-02-21 13:29:15 -0800222 total_corrupt_bytes += sector_corrupt_bytes;
Keir Mierle8c352dc2020-02-02 13:58:19 -0800223 }
224
225 DBG("Second pass: Count valid bytes in each sector");
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700226 Address newest_key = 0;
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800227
David Rogers98fea472020-04-01 15:43:48 -0700228 // For every valid entry, for each address, count the valid bytes in that
229 // sector. If the address fails to read, remove the address and mark the
230 // sector as corrupt. Track which entry has the newest transaction ID for
231 // initializing last_new_sector_.
232 for (EntryMetadata& metadata : entry_cache_) {
David Rogers49766d92020-03-20 10:55:54 -0700233 if (metadata.addresses().size() < redundancy()) {
David Rogers31b358b2020-04-15 05:00:50 -0700234 DBG("Key 0x%08x missing copies, has %u, needs %u",
235 unsigned(metadata.hash()),
236 unsigned(metadata.addresses().size()),
237 unsigned(redundancy()));
David Rogerscd134352020-04-17 19:37:15 -0700238 entry_copies_missing++;
David Rogers49766d92020-03-20 10:55:54 -0700239 }
David Rogers98fea472020-04-01 15:43:48 -0700240 size_t index = 0;
241 while (index < metadata.addresses().size()) {
242 Address address = metadata.addresses()[index];
David Rogersf56131c2020-03-04 10:19:22 -0800243 Entry entry;
David Rogers98fea472020-04-01 15:43:48 -0700244
245 Status read_result = Entry::Read(partition_, address, formats_, &entry);
246
247 SectorDescriptor& sector = sectors_.FromAddress(address);
248
249 if (read_result.ok()) {
250 sector.AddValidBytes(entry.size());
251 index++;
252 } else {
253 corrupt_entries++;
254 total_corrupt_bytes += sector.writable_bytes();
255 error_detected_ = true;
256 sector.mark_corrupt();
257
258 // Remove the bad address and stay at this index. The removal
259 // replaces out the removed address with the back address so
260 // this index needs to be rechecked with the new address.
261 metadata.RemoveAddress(address);
262 }
David Rogersf56131c2020-03-04 10:19:22 -0800263 }
David Rogers98fea472020-04-01 15:43:48 -0700264
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700265 if (metadata.IsNewerThan(last_transaction_id_)) {
266 last_transaction_id_ = metadata.transaction_id();
267 newest_key = metadata.addresses().back();
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800268 }
Keir Mierle8c352dc2020-02-02 13:58:19 -0800269 }
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800270
Wyatt Heplerc84393f2020-03-20 11:23:24 -0700271 sectors_.set_last_new_sector(newest_key);
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800272
David Rogers91627482020-02-27 17:38:12 -0800273 if (!empty_sector_found) {
David Rogers31b358b2020-04-15 05:00:50 -0700274 DBG("No empty sector found");
David Rogers9abe3c72020-03-24 19:03:13 -0700275 error_detected_ = true;
David Rogers91627482020-02-27 17:38:12 -0800276 }
277
David Rogerscd134352020-04-17 19:37:15 -0700278 if (entry_copies_missing > 0) {
279 bool other_errors = error_detected_;
280 error_detected_ = true;
281
Armando Montanez344814b2020-04-24 15:05:42 -0700282 if (!other_errors && entry_copies_missing == entry_cache_.total_entries()) {
David Rogers9fc78b82020-06-12 13:56:12 -0700283 INF("KVS configuration changed to redundancy of %u total copies per key",
284 unsigned(redundancy()));
Wyatt Heplerd78f7c62020-09-28 14:27:32 -0700285 return Status::OutOfRange();
David Rogerscd134352020-04-17 19:37:15 -0700286 }
David Rogers9abe3c72020-03-24 19:03:13 -0700287 }
David Rogerscd134352020-04-17 19:37:15 -0700288
289 if (error_detected_) {
David Rogers9fc78b82020-06-12 13:56:12 -0700290 WRN("Corruption detected. Found %u corrupt bytes, %u corrupt entries, "
291 "and %u keys missing redundant copies.",
292 unsigned(total_corrupt_bytes),
293 unsigned(corrupt_entries),
294 unsigned(entry_copies_missing));
Wyatt Heplerd78f7c62020-09-28 14:27:32 -0700295 return Status::FailedPrecondition();
David Rogerscd134352020-04-17 19:37:15 -0700296 }
Wyatt Heplerd78f7c62020-09-28 14:27:32 -0700297 return Status::Ok();
Keir Mierle8c352dc2020-02-02 13:58:19 -0800298}
299
Alexei Frolov9e235832020-02-24 12:44:45 -0800300KeyValueStore::StorageStats KeyValueStore::GetStorageStats() const {
David Rogers9abe3c72020-03-24 19:03:13 -0700301 StorageStats stats{};
Alexei Frolov9e235832020-02-24 12:44:45 -0800302 const size_t sector_size = partition_.sector_size_bytes();
303 bool found_empty_sector = false;
David Rogers3c298372020-10-12 14:15:39 -0700304 stats.sector_erase_count = internal_stats_.sector_erase_count;
305 stats.corrupt_sectors_recovered = internal_stats_.corrupt_sectors_recovered;
David Rogers9abe3c72020-03-24 19:03:13 -0700306 stats.missing_redundant_entries_recovered =
David Rogers3c298372020-10-12 14:15:39 -0700307 internal_stats_.missing_redundant_entries_recovered;
Alexei Frolov9e235832020-02-24 12:44:45 -0800308
309 for (const SectorDescriptor& sector : sectors_) {
310 stats.in_use_bytes += sector.valid_bytes();
311 stats.reclaimable_bytes += sector.RecoverableBytes(sector_size);
312
313 if (!found_empty_sector && sector.Empty(sector_size)) {
314 // The KVS tries to always keep an empty sector for GC, so don't count
315 // the first empty sector seen as writable space. However, a free sector
316 // cannot always be assumed to exist; if a GC operation fails, all sectors
317 // may be partially written, in which case the space reported might be
318 // inaccurate.
319 found_empty_sector = true;
320 continue;
321 }
322
323 stats.writable_bytes += sector.writable_bytes();
324 }
325
326 return stats;
327}
328
David Rogers98fea472020-04-01 15:43:48 -0700329// Check KVS for any error conditions. Primarily intended for test and
330// internal use.
David Rogers9abe3c72020-03-24 19:03:13 -0700331bool KeyValueStore::CheckForErrors() {
332 // Check for corrupted sectors
333 for (SectorDescriptor& sector : sectors_) {
334 if (sector.corrupt()) {
335 error_detected_ = true;
David Rogers98fea472020-04-01 15:43:48 -0700336 return error_detected();
David Rogers9abe3c72020-03-24 19:03:13 -0700337 }
338 }
339
340 // Check for missing redundancy.
341 if (redundancy() > 1) {
342 for (const EntryMetadata& metadata : entry_cache_) {
343 if (metadata.addresses().size() < redundancy()) {
344 error_detected_ = true;
David Rogers98fea472020-04-01 15:43:48 -0700345 return error_detected();
David Rogers9abe3c72020-03-24 19:03:13 -0700346 }
347 }
348 }
349
350 return error_detected();
351}
352
Keir Mierle8c352dc2020-02-02 13:58:19 -0800353Status KeyValueStore::LoadEntry(Address entry_address,
354 Address* next_entry_address) {
Wyatt Heplere541e072020-02-14 09:10:53 -0800355 Entry entry;
David Rogersc4dc8642020-09-14 10:52:36 -0700356 PW_TRY(Entry::Read(partition_, entry_address, formats_, &entry));
Keir Mierle8c352dc2020-02-02 13:58:19 -0800357
358 // Read the key from flash & validate the entry (which reads the value).
Wyatt Heplera00d1ef2020-02-14 14:31:26 -0800359 Entry::KeyBuffer key_buffer;
David Rogersc4dc8642020-09-14 10:52:36 -0700360 PW_TRY_ASSIGN(size_t key_length, entry.ReadKey(key_buffer));
Wyatt Heplere541e072020-02-14 09:10:53 -0800361 const string_view key(key_buffer.data(), key_length);
Wyatt Heplerbab0e202020-02-04 07:40:08 -0800362
David Rogersc4dc8642020-09-14 10:52:36 -0700363 PW_TRY(entry.VerifyChecksumInFlash());
David Rogersf56131c2020-03-04 10:19:22 -0800364
365 // A valid entry was found, so update the next entry address before doing any
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700366 // of the checks that happen in AddNewOrUpdateExisting.
David Rogersf56131c2020-03-04 10:19:22 -0800367 *next_entry_address = entry.next_address();
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700368 return entry_cache_.AddNewOrUpdateExisting(
369 entry.descriptor(key), entry.address(), partition_.sector_size_bytes());
Keir Mierle8c352dc2020-02-02 13:58:19 -0800370}
371
Alexei Frolovd4adf912020-02-21 13:29:15 -0800372// Scans flash memory within a sector to find a KVS entry magic.
Alexei Frolovd4adf912020-02-21 13:29:15 -0800373Status KeyValueStore::ScanForEntry(const SectorDescriptor& sector,
374 Address start_address,
375 Address* next_entry_address) {
David Rogersfcea3252020-04-07 14:56:35 -0700376 DBG("Scanning sector %u for entries starting from address %u",
Wyatt Heplerc84393f2020-03-20 11:23:24 -0700377 sectors_.Index(sector),
David Rogersfcea3252020-04-07 14:56:35 -0700378 unsigned(start_address));
Alexei Frolovd4adf912020-02-21 13:29:15 -0800379
380 // Entries must start at addresses which are aligned on a multiple of
381 // Entry::kMinAlignmentBytes. However, that multiple can vary between entries.
382 // When scanning, we don't have an entry to tell us what the current alignment
383 // is, so the minimum alignment is used to be exhaustive.
384 for (Address address = AlignUp(start_address, Entry::kMinAlignmentBytes);
Wyatt Heplerc84393f2020-03-20 11:23:24 -0700385 sectors_.AddressInSector(sector, address);
Alexei Frolovd4adf912020-02-21 13:29:15 -0800386 address += Entry::kMinAlignmentBytes) {
Alexei Frolovd4adf912020-02-21 13:29:15 -0800387 uint32_t magic;
David Rogersfcea3252020-04-07 14:56:35 -0700388 StatusWithSize read_result =
Wyatt Heplere2cbadf2020-06-22 11:21:45 -0700389 partition_.Read(address, std::as_writable_bytes(std::span(&magic, 1)));
David Rogersfcea3252020-04-07 14:56:35 -0700390 if (!read_result.ok()) {
391 continue;
392 }
Wyatt Hepler22d0d9f2020-03-05 14:57:11 -0800393 if (formats_.KnownMagic(magic)) {
David Rogersfcea3252020-04-07 14:56:35 -0700394 DBG("Found entry magic at address %u", unsigned(address));
Alexei Frolovd4adf912020-02-21 13:29:15 -0800395 *next_entry_address = address;
Wyatt Heplerd78f7c62020-09-28 14:27:32 -0700396 return Status::Ok();
Alexei Frolovd4adf912020-02-21 13:29:15 -0800397 }
398 }
399
Wyatt Heplerd78f7c62020-09-28 14:27:32 -0700400 return Status::NotFound();
Alexei Frolovd4adf912020-02-21 13:29:15 -0800401}
402
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800403StatusWithSize KeyValueStore::Get(string_view key,
Wyatt Heplere2cbadf2020-06-22 11:21:45 -0700404 std::span<byte> value_buffer,
Wyatt Hepler5f6efc02020-02-18 16:54:31 -0800405 size_t offset_bytes) const {
David Rogersc4dc8642020-09-14 10:52:36 -0700406 PW_TRY_WITH_SIZE(CheckReadOperation(key));
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800407
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700408 EntryMetadata metadata;
David Rogersc4dc8642020-09-14 10:52:36 -0700409 PW_TRY_WITH_SIZE(FindExisting(key, &metadata));
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800410
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700411 return Get(key, metadata, value_buffer, offset_bytes);
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800412}
413
Wyatt Heplere2cbadf2020-06-22 11:21:45 -0700414Status KeyValueStore::PutBytes(string_view key, std::span<const byte> value) {
David Rogersc4dc8642020-09-14 10:52:36 -0700415 PW_TRY(CheckWriteOperation(key));
David Rogers9fc78b82020-06-12 13:56:12 -0700416 DBG("Writing key/value; key length=%u, value length=%u",
417 unsigned(key.size()),
418 unsigned(value.size()));
Wyatt Hepler729f28c2020-02-05 09:46:00 -0800419
Wyatt Hepler5406a672020-02-18 15:42:38 -0800420 if (Entry::size(partition_, key, value) > partition_.sector_size_bytes()) {
David Rogers9fc78b82020-06-12 13:56:12 -0700421 DBG("%u B value with %u B key cannot fit in one sector",
422 unsigned(value.size()),
423 unsigned(key.size()));
Wyatt Heplerd78f7c62020-09-28 14:27:32 -0700424 return Status::InvalidArgument();
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800425 }
426
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700427 EntryMetadata metadata;
David Rogers98fea472020-04-01 15:43:48 -0700428 Status status = FindEntry(key, &metadata);
Wyatt Hepler2d401692020-02-13 16:01:23 -0800429
430 if (status.ok()) {
David Rogersf56131c2020-03-04 10:19:22 -0800431 // TODO: figure out logging how to support multiple addresses.
David Rogers9fc78b82020-06-12 13:56:12 -0700432 DBG("Overwriting entry for key 0x%08x in %u sectors including %u",
433 unsigned(metadata.hash()),
434 unsigned(metadata.addresses().size()),
Wyatt Heplerc84393f2020-03-20 11:23:24 -0700435 sectors_.Index(metadata.first_address()));
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700436 return WriteEntryForExistingKey(metadata, EntryState::kValid, key, value);
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800437 }
David Rogers2761aeb2020-01-31 17:09:00 -0800438
Wyatt Heplerd78f7c62020-09-28 14:27:32 -0700439 if (status == Status::NotFound()) {
Wyatt Hepler2d401692020-02-13 16:01:23 -0800440 return WriteEntryForNewKey(key, value);
441 }
442
443 return status;
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800444}
445
446Status KeyValueStore::Delete(string_view key) {
David Rogersc4dc8642020-09-14 10:52:36 -0700447 PW_TRY(CheckWriteOperation(key));
Wyatt Hepler729f28c2020-02-05 09:46:00 -0800448
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700449 EntryMetadata metadata;
David Rogersc4dc8642020-09-14 10:52:36 -0700450 PW_TRY(FindExisting(key, &metadata));
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800451
David Rogersf56131c2020-03-04 10:19:22 -0800452 // TODO: figure out logging how to support multiple addresses.
David Rogers9fc78b82020-06-12 13:56:12 -0700453 DBG("Writing tombstone for key 0x%08x in %u sectors including %u",
454 unsigned(metadata.hash()),
455 unsigned(metadata.addresses().size()),
Wyatt Heplerc84393f2020-03-20 11:23:24 -0700456 sectors_.Index(metadata.first_address()));
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700457 return WriteEntryForExistingKey(metadata, EntryState::kDeleted, key, {});
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800458}
459
Wyatt Hepler08d37d82020-02-27 15:45:37 -0800460void KeyValueStore::Item::ReadKey() {
461 key_buffer_.fill('\0');
462
463 Entry entry;
David Rogers98fea472020-04-01 15:43:48 -0700464 if (kvs_.ReadEntry(*iterator_, entry).ok()) {
Wyatt Hepler08d37d82020-02-27 15:45:37 -0800465 entry.ReadKey(key_buffer_);
466 }
467}
468
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800469KeyValueStore::iterator& KeyValueStore::iterator::operator++() {
470 // Skip to the next entry that is valid (not deleted).
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700471 while (++item_.iterator_ != item_.kvs_.entry_cache_.end() &&
Wyatt Hepler02946272020-03-18 10:36:22 -0700472 item_.iterator_->state() != EntryState::kValid) {
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800473 }
474 return *this;
475}
476
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800477KeyValueStore::iterator KeyValueStore::begin() const {
Wyatt Heplerbfc6a522020-04-01 16:30:24 -0700478 internal::EntryCache::const_iterator cache_iterator = entry_cache_.begin();
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800479 // Skip over any deleted entries at the start of the descriptor list.
Wyatt Hepler02946272020-03-18 10:36:22 -0700480 while (cache_iterator != entry_cache_.end() &&
481 cache_iterator->state() != EntryState::kValid) {
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700482 ++cache_iterator;
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800483 }
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700484 return iterator(*this, cache_iterator);
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800485}
486
Wyatt Heplerab3b2492020-03-11 16:15:16 -0700487StatusWithSize KeyValueStore::ValueSize(string_view key) const {
David Rogersc4dc8642020-09-14 10:52:36 -0700488 PW_TRY_WITH_SIZE(CheckReadOperation(key));
Wyatt Heplered163b02020-02-03 17:49:32 -0800489
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700490 EntryMetadata metadata;
David Rogersc4dc8642020-09-14 10:52:36 -0700491 PW_TRY_WITH_SIZE(FindExisting(key, &metadata));
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800492
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700493 return ValueSize(metadata);
Wyatt Heplerfac81132020-02-27 17:26:33 -0800494}
Wyatt Heplered163b02020-02-03 17:49:32 -0800495
David Rogers98fea472020-04-01 15:43:48 -0700496Status KeyValueStore::ReadEntry(const EntryMetadata& metadata,
497 Entry& entry) const {
498 // Try to read an entry
Wyatt Heplerd78f7c62020-09-28 14:27:32 -0700499 Status read_result = Status::DataLoss();
David Rogers98fea472020-04-01 15:43:48 -0700500 for (Address address : metadata.addresses()) {
501 read_result = Entry::Read(partition_, address, formats_, &entry);
502 if (read_result.ok()) {
503 return read_result;
504 }
505
506 // Found a bad address. Set the sector as corrupt.
507 error_detected_ = true;
508 sectors_.FromAddress(address).mark_corrupt();
509 }
510
511 ERR("No valid entries for key. Data has been lost!");
512 return read_result;
513}
514
515Status KeyValueStore::FindEntry(string_view key,
516 EntryMetadata* found_entry) const {
517 StatusWithSize find_result =
518 entry_cache_.Find(partition_, sectors_, formats_, key, found_entry);
519
520 if (find_result.size() > 0u) {
521 error_detected_ = true;
522 }
523 return find_result.status();
524}
525
526Status KeyValueStore::FindExisting(string_view key,
527 EntryMetadata* metadata) const {
528 Status status = FindEntry(key, metadata);
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.
Wyatt Heplerd78f7c62020-09-28 14:27:32 -0700532 if (status == Status::AlreadyExists() ||
David Rogers98fea472020-04-01 15:43:48 -0700533 (status.ok() && metadata->state() == EntryState::kDeleted)) {
Wyatt Heplerd78f7c62020-09-28 14:27:32 -0700534 return Status::NotFound();
David Rogers98fea472020-04-01 15:43:48 -0700535 }
536 return status;
537}
538
Wyatt Heplerfac81132020-02-27 17:26:33 -0800539StatusWithSize KeyValueStore::Get(string_view key,
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700540 const EntryMetadata& metadata,
Wyatt Heplere2cbadf2020-06-22 11:21:45 -0700541 std::span<std::byte> value_buffer,
Wyatt Heplerfac81132020-02-27 17:26:33 -0800542 size_t offset_bytes) const {
543 Entry entry;
David Rogers98fea472020-04-01 15:43:48 -0700544
David Rogersc4dc8642020-09-14 10:52:36 -0700545 PW_TRY_WITH_SIZE(ReadEntry(metadata, entry));
Wyatt Heplerfac81132020-02-27 17:26:33 -0800546
547 StatusWithSize result = entry.ReadValue(value_buffer, offset_bytes);
548 if (result.ok() && options_.verify_on_read && offset_bytes == 0u) {
Wyatt Hepler22d0d9f2020-03-05 14:57:11 -0800549 Status verify_result =
550 entry.VerifyChecksum(key, value_buffer.first(result.size()));
Wyatt Heplerfac81132020-02-27 17:26:33 -0800551 if (!verify_result.ok()) {
552 std::memset(value_buffer.data(), 0, result.size());
553 return StatusWithSize(verify_result, 0);
554 }
555
556 return StatusWithSize(verify_result, result.size());
557 }
558 return result;
Wyatt Heplered163b02020-02-03 17:49:32 -0800559}
560
Wyatt Hepler6e3a83b2020-02-04 07:36:45 -0800561Status KeyValueStore::FixedSizeGet(std::string_view key,
Wyatt Heplerfac81132020-02-27 17:26:33 -0800562 void* value,
563 size_t size_bytes) const {
David Rogersc4dc8642020-09-14 10:52:36 -0700564 PW_TRY(CheckWriteOperation(key));
Wyatt Heplerfac81132020-02-27 17:26:33 -0800565
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700566 EntryMetadata metadata;
David Rogersc4dc8642020-09-14 10:52:36 -0700567 PW_TRY(FindExisting(key, &metadata));
Wyatt Heplerfac81132020-02-27 17:26:33 -0800568
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700569 return FixedSizeGet(key, metadata, value, size_bytes);
Wyatt Heplerfac81132020-02-27 17:26:33 -0800570}
571
572Status KeyValueStore::FixedSizeGet(std::string_view key,
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700573 const EntryMetadata& metadata,
Wyatt Heplerfac81132020-02-27 17:26:33 -0800574 void* value,
Wyatt Hepler6e3a83b2020-02-04 07:36:45 -0800575 size_t size_bytes) const {
576 // Ensure that the size of the stored value matches the size of the type.
577 // Otherwise, report error. This check avoids potential memory corruption.
David Rogersc4dc8642020-09-14 10:52:36 -0700578 PW_TRY_ASSIGN(const size_t actual_size, ValueSize(metadata));
Wyatt Heplerfac81132020-02-27 17:26:33 -0800579
580 if (actual_size != size_bytes) {
David Rogers9fc78b82020-06-12 13:56:12 -0700581 DBG("Requested %u B read, but value is %u B",
582 unsigned(size_bytes),
583 unsigned(actual_size));
Wyatt Heplerd78f7c62020-09-28 14:27:32 -0700584 return Status::InvalidArgument();
Wyatt Heplerbab0e202020-02-04 07:40:08 -0800585 }
Wyatt Heplerfac81132020-02-27 17:26:33 -0800586
587 StatusWithSize result =
Wyatt Heplere2cbadf2020-06-22 11:21:45 -0700588 Get(key, metadata, std::span(static_cast<byte*>(value), size_bytes), 0);
Wyatt Heplerfac81132020-02-27 17:26:33 -0800589
590 return result.status();
591}
592
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700593StatusWithSize KeyValueStore::ValueSize(const EntryMetadata& metadata) const {
Wyatt Heplerfac81132020-02-27 17:26:33 -0800594 Entry entry;
David Rogersc4dc8642020-09-14 10:52:36 -0700595 PW_TRY_WITH_SIZE(ReadEntry(metadata, entry));
Wyatt Heplerfac81132020-02-27 17:26:33 -0800596
597 return StatusWithSize(entry.value_size());
Keir Mierle8c352dc2020-02-02 13:58:19 -0800598}
599
David Rogers9abe3c72020-03-24 19:03:13 -0700600Status KeyValueStore::CheckWriteOperation(string_view key) const {
Wyatt Hepleracaacf92020-01-24 10:58:30 -0800601 if (InvalidKey(key)) {
Wyatt Heplerd78f7c62020-09-28 14:27:32 -0700602 return Status::InvalidArgument();
Wyatt Heplerb7609542020-01-24 10:29:54 -0800603 }
David Rogers9abe3c72020-03-24 19:03:13 -0700604
605 // For normal write operation the KVS must be fully ready.
Wyatt Heplerd2298282020-02-20 17:12:45 -0800606 if (!initialized()) {
Wyatt Heplerd78f7c62020-09-28 14:27:32 -0700607 return Status::FailedPrecondition();
Wyatt Heplerb7609542020-01-24 10:29:54 -0800608 }
Wyatt Heplerd78f7c62020-09-28 14:27:32 -0700609 return Status::Ok();
Wyatt Heplerb7609542020-01-24 10:29:54 -0800610}
611
David Rogers9abe3c72020-03-24 19:03:13 -0700612Status KeyValueStore::CheckReadOperation(string_view key) const {
613 if (InvalidKey(key)) {
Wyatt Heplerd78f7c62020-09-28 14:27:32 -0700614 return Status::InvalidArgument();
David Rogers9abe3c72020-03-24 19:03:13 -0700615 }
616
617 // Operations that are explicitly read-only can be done after init() has been
618 // called but not fully ready (when needing maintenance).
619 if (initialized_ == InitializationState::kNotInitialized) {
Wyatt Heplerd78f7c62020-09-28 14:27:32 -0700620 return Status::FailedPrecondition();
David Rogers9abe3c72020-03-24 19:03:13 -0700621 }
Wyatt Heplerd78f7c62020-09-28 14:27:32 -0700622 return Status::Ok();
David Rogers9abe3c72020-03-24 19:03:13 -0700623}
624
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700625Status KeyValueStore::WriteEntryForExistingKey(EntryMetadata& metadata,
626 EntryState new_state,
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800627 string_view key,
Wyatt Heplere2cbadf2020-06-22 11:21:45 -0700628 std::span<const byte> value) {
Wyatt Heplerab3b2492020-03-11 16:15:16 -0700629 // Read the original entry to get the size for sector accounting purposes.
630 Entry entry;
David Rogersc4dc8642020-09-14 10:52:36 -0700631 PW_TRY(ReadEntry(metadata, entry));
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800632
David Rogersc0104462020-05-08 15:50:23 -0700633 return WriteEntry(key, value, new_state, &metadata, &entry);
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800634}
635
636Status KeyValueStore::WriteEntryForNewKey(string_view key,
Wyatt Heplere2cbadf2020-06-22 11:21:45 -0700637 std::span<const byte> value) {
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700638 if (entry_cache_.full()) {
David Rogers9fc78b82020-06-12 13:56:12 -0700639 WRN("KVS full: trying to store a new entry, but can't. Have %u entries",
640 unsigned(entry_cache_.total_entries()));
Wyatt Heplerd78f7c62020-09-28 14:27:32 -0700641 return Status::ResourceExhausted();
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800642 }
643
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700644 return WriteEntry(key, value, EntryState::kValid);
Wyatt Heplerab3b2492020-03-11 16:15:16 -0700645}
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800646
Wyatt Heplerab3b2492020-03-11 16:15:16 -0700647Status KeyValueStore::WriteEntry(string_view key,
Wyatt Heplere2cbadf2020-06-22 11:21:45 -0700648 std::span<const byte> value,
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700649 EntryState new_state,
650 EntryMetadata* prior_metadata,
David Rogersc0104462020-05-08 15:50:23 -0700651 const Entry* prior_entry) {
David Rogersc0104462020-05-08 15:50:23 -0700652 // If new entry and prior entry have matching value size, state, and checksum,
653 // check if the values match. Directly compare the prior and new values
654 // because the checksum can not be depended on to establish equality, it can
655 // only be depended on to establish inequality.
David Rogersd50eb1c2020-05-12 17:46:36 -0700656 if (prior_entry != nullptr && prior_entry->value_size() == value.size() &&
David Rogersc0104462020-05-08 15:50:23 -0700657 prior_metadata->state() == new_state &&
David Rogersc0104462020-05-08 15:50:23 -0700658 prior_entry->ValueMatches(value).ok()) {
David Rogersd50eb1c2020-05-12 17:46:36 -0700659 // The new value matches the prior value, don't need to write anything. Just
660 // keep the existing entry.
David Rogersc0104462020-05-08 15:50:23 -0700661 DBG("Write for key 0x%08x with matching value skipped",
662 unsigned(prior_metadata->hash()));
Wyatt Heplerd78f7c62020-09-28 14:27:32 -0700663 return Status::Ok();
David Rogersc0104462020-05-08 15:50:23 -0700664 }
Wyatt Heplerab3b2492020-03-11 16:15:16 -0700665
666 // List of addresses for sectors with space for this entry.
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700667 Address* reserved_addresses = entry_cache_.TempReservedAddressesForWrite();
Wyatt Heplerab3b2492020-03-11 16:15:16 -0700668
David Rogers31b358b2020-04-15 05:00:50 -0700669 // Find addresses to write the entry to. This may involve garbage collecting
670 // one or more sectors.
David Rogersc0104462020-05-08 15:50:23 -0700671 const size_t entry_size = Entry::size(partition_, key, value);
David Rogersc4dc8642020-09-14 10:52:36 -0700672 PW_TRY(GetAddressesForWrite(reserved_addresses, entry_size));
Wyatt Heplerab3b2492020-03-11 16:15:16 -0700673
674 // Write the entry at the first address that was found.
David Rogersd50eb1c2020-05-12 17:46:36 -0700675 Entry entry = CreateEntry(reserved_addresses[0], key, value, new_state);
David Rogersc4dc8642020-09-14 10:52:36 -0700676 PW_TRY(AppendEntry(entry, key, value));
Wyatt Heplerab3b2492020-03-11 16:15:16 -0700677
678 // After writing the first entry successfully, update the key descriptors.
679 // Once a single new the entry is written, the old entries are invalidated.
David Rogersc0104462020-05-08 15:50:23 -0700680 size_t prior_size = prior_entry != nullptr ? prior_entry->size() : 0;
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700681 EntryMetadata new_metadata =
David Rogers31b358b2020-04-15 05:00:50 -0700682 CreateOrUpdateKeyDescriptor(entry, key, prior_metadata, prior_size);
Wyatt Heplerab3b2492020-03-11 16:15:16 -0700683
684 // Write the additional copies of the entry, if redundancy is greater than 1.
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700685 for (size_t i = 1; i < redundancy(); ++i) {
686 entry.set_address(reserved_addresses[i]);
David Rogersc4dc8642020-09-14 10:52:36 -0700687 PW_TRY(AppendEntry(entry, key, value));
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700688 new_metadata.AddNewAddress(reserved_addresses[i]);
Wyatt Heplerab3b2492020-03-11 16:15:16 -0700689 }
Wyatt Heplerd78f7c62020-09-28 14:27:32 -0700690 return Status::Ok();
Wyatt Heplerb7609542020-01-24 10:29:54 -0800691}
692
David Rogers31b358b2020-04-15 05:00:50 -0700693KeyValueStore::EntryMetadata KeyValueStore::CreateOrUpdateKeyDescriptor(
Wyatt Heplerab3b2492020-03-11 16:15:16 -0700694 const Entry& entry,
695 string_view key,
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700696 EntryMetadata* prior_metadata,
Wyatt Heplerab3b2492020-03-11 16:15:16 -0700697 size_t prior_size) {
698 // If there is no prior descriptor, create a new one.
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700699 if (prior_metadata == nullptr) {
700 return entry_cache_.AddNew(entry.descriptor(key), entry.address());
David Rogersa2562b52020-03-05 15:30:05 -0800701 }
702
David Rogers31b358b2020-04-15 05:00:50 -0700703 return UpdateKeyDescriptor(
704 entry, entry.address(), prior_metadata, prior_size);
705}
706
707KeyValueStore::EntryMetadata KeyValueStore::UpdateKeyDescriptor(
708 const Entry& entry,
709 Address new_address,
710 EntryMetadata* prior_metadata,
711 size_t prior_size) {
Wyatt Heplerab3b2492020-03-11 16:15:16 -0700712 // Remove valid bytes for the old entry and its copies, which are now stale.
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700713 for (Address address : prior_metadata->addresses()) {
Wyatt Heplerc84393f2020-03-20 11:23:24 -0700714 sectors_.FromAddress(address).RemoveValidBytes(prior_size);
David Rogersa2562b52020-03-05 15:30:05 -0800715 }
716
David Rogers31b358b2020-04-15 05:00:50 -0700717 prior_metadata->Reset(entry.descriptor(prior_metadata->hash()), new_address);
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700718 return *prior_metadata;
David Rogersa2562b52020-03-05 15:30:05 -0800719}
720
David Rogers31b358b2020-04-15 05:00:50 -0700721Status KeyValueStore::GetAddressesForWrite(Address* write_addresses,
722 size_t write_size) {
723 for (size_t i = 0; i < redundancy(); i++) {
724 SectorDescriptor* sector;
David Rogersc4dc8642020-09-14 10:52:36 -0700725 PW_TRY(
726 GetSectorForWrite(&sector, write_size, std::span(write_addresses, i)));
David Rogers31b358b2020-04-15 05:00:50 -0700727 write_addresses[i] = sectors_.NextWritableAddress(*sector);
728
729 DBG("Found space for entry in sector %u at address %u",
730 sectors_.Index(sector),
731 unsigned(write_addresses[i]));
732 }
733
Wyatt Heplerd78f7c62020-09-28 14:27:32 -0700734 return Status::Ok();
David Rogers31b358b2020-04-15 05:00:50 -0700735}
736
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700737// Finds a sector to use for writing a new entry to. Does automatic garbage
David Rogersa2562b52020-03-05 15:30:05 -0800738// collection if needed and allowed.
739//
740// OK: Sector found with needed space.
741// RESOURCE_EXHAUSTED: No sector available with the needed space.
742Status KeyValueStore::GetSectorForWrite(SectorDescriptor** sector,
743 size_t entry_size,
Wyatt Heplere2cbadf2020-06-22 11:21:45 -0700744 std::span<const Address> reserved) {
Wyatt Heplerc84393f2020-03-20 11:23:24 -0700745 Status result = sectors_.FindSpace(sector, entry_size, reserved);
David Rogersa2562b52020-03-05 15:30:05 -0800746
David Rogersf3884eb2020-03-08 19:21:40 -0700747 size_t gc_sector_count = 0;
David Rogersa2562b52020-03-05 15:30:05 -0800748 bool do_auto_gc = options_.gc_on_write != GargbageCollectOnWrite::kDisabled;
749
750 // Do garbage collection as needed, so long as policy allows.
Wyatt Heplerd78f7c62020-09-28 14:27:32 -0700751 while (result == Status::ResourceExhausted() && do_auto_gc) {
David Rogersa2562b52020-03-05 15:30:05 -0800752 if (options_.gc_on_write == GargbageCollectOnWrite::kOneSector) {
753 // If GC config option is kOneSector clear the flag to not do any more
754 // GC after this try.
755 do_auto_gc = false;
756 }
757 // Garbage collect and then try again to find the best sector.
David Rogers9abe3c72020-03-24 19:03:13 -0700758 Status gc_status = GarbageCollect(reserved);
David Rogersa2562b52020-03-05 15:30:05 -0800759 if (!gc_status.ok()) {
Wyatt Heplerd78f7c62020-09-28 14:27:32 -0700760 if (gc_status == Status::NotFound()) {
David Rogersa2562b52020-03-05 15:30:05 -0800761 // Not enough space, and no reclaimable bytes, this KVS is full!
Wyatt Heplerd78f7c62020-09-28 14:27:32 -0700762 return Status::ResourceExhausted();
David Rogersa2562b52020-03-05 15:30:05 -0800763 }
764 return gc_status;
765 }
766
Wyatt Heplerc84393f2020-03-20 11:23:24 -0700767 result = sectors_.FindSpace(sector, entry_size, reserved);
David Rogersf3884eb2020-03-08 19:21:40 -0700768
769 gc_sector_count++;
770 // Allow total sectors + 2 number of GC cycles so that once reclaimable
771 // bytes in all the sectors have been reclaimed can try and free up space by
772 // moving entries for keys other than the one being worked on in to sectors
773 // that have copies of the key trying to be written.
774 if (gc_sector_count > (partition_.sector_count() + 2)) {
775 ERR("Did more GC sectors than total sectors!!!!");
Wyatt Heplerd78f7c62020-09-28 14:27:32 -0700776 return Status::ResourceExhausted();
David Rogersf3884eb2020-03-08 19:21:40 -0700777 }
David Rogersa2562b52020-03-05 15:30:05 -0800778 }
779
780 if (!result.ok()) {
David Rogers9fc78b82020-06-12 13:56:12 -0700781 WRN("Unable to find sector to write %u B", unsigned(entry_size));
David Rogersa2562b52020-03-05 15:30:05 -0800782 }
783 return result;
784}
785
David Rogers9abe3c72020-03-24 19:03:13 -0700786Status KeyValueStore::MarkSectorCorruptIfNotOk(Status status,
787 SectorDescriptor* sector) {
788 if (!status.ok()) {
789 DBG(" Sector %u corrupt", sectors_.Index(sector));
790 sector->mark_corrupt();
791 error_detected_ = true;
792 }
793 return status;
794}
795
Wyatt Heplerab3b2492020-03-11 16:15:16 -0700796Status KeyValueStore::AppendEntry(const Entry& entry,
David Rogersa2562b52020-03-05 15:30:05 -0800797 string_view key,
Wyatt Heplere2cbadf2020-06-22 11:21:45 -0700798 std::span<const byte> value) {
Wyatt Heplerab3b2492020-03-11 16:15:16 -0700799 const StatusWithSize result = entry.Write(key, value);
David Rogersa2562b52020-03-05 15:30:05 -0800800
Wyatt Heplerc84393f2020-03-20 11:23:24 -0700801 SectorDescriptor& sector = sectors_.FromAddress(entry.address());
David Rogersa2562b52020-03-05 15:30:05 -0800802
803 if (!result.ok()) {
David Rogers9fc78b82020-06-12 13:56:12 -0700804 ERR("Failed to write %u bytes at %#x. %u actually written",
805 unsigned(entry.size()),
806 unsigned(entry.address()),
807 unsigned(result.size()));
David Rogersc4dc8642020-09-14 10:52:36 -0700808 PW_TRY(MarkSectorCorruptIfNotOk(result.status(), &sector));
David Rogersa2562b52020-03-05 15:30:05 -0800809 }
810
811 if (options_.verify_on_write) {
David Rogersc4dc8642020-09-14 10:52:36 -0700812 PW_TRY(MarkSectorCorruptIfNotOk(entry.VerifyChecksumInFlash(), &sector));
David Rogersa2562b52020-03-05 15:30:05 -0800813 }
814
David Rogers98fea472020-04-01 15:43:48 -0700815 sector.RemoveWritableBytes(result.size());
Wyatt Heplerc84393f2020-03-20 11:23:24 -0700816 sector.AddValidBytes(result.size());
Wyatt Heplerd78f7c62020-09-28 14:27:32 -0700817 return Status::Ok();
David Rogersa2562b52020-03-05 15:30:05 -0800818}
819
David Rogers98fea472020-04-01 15:43:48 -0700820StatusWithSize KeyValueStore::CopyEntryToSector(Entry& entry,
821 SectorDescriptor* new_sector,
David Rogers31b358b2020-04-15 05:00:50 -0700822 Address new_address) {
David Rogers98fea472020-04-01 15:43:48 -0700823 const StatusWithSize result = entry.Copy(new_address);
824
David Rogersc4dc8642020-09-14 10:52:36 -0700825 PW_TRY_WITH_SIZE(MarkSectorCorruptIfNotOk(result.status(), new_sector));
David Rogers98fea472020-04-01 15:43:48 -0700826
827 if (options_.verify_on_write) {
David Rogers31b358b2020-04-15 05:00:50 -0700828 Entry new_entry;
David Rogersc4dc8642020-09-14 10:52:36 -0700829 PW_TRY_WITH_SIZE(MarkSectorCorruptIfNotOk(
David Rogers31b358b2020-04-15 05:00:50 -0700830 Entry::Read(partition_, new_address, formats_, &new_entry),
831 new_sector));
832 // TODO: add test that catches doing the verify on the old entry.
David Rogersc4dc8642020-09-14 10:52:36 -0700833 PW_TRY_WITH_SIZE(MarkSectorCorruptIfNotOk(new_entry.VerifyChecksumInFlash(),
834 new_sector));
David Rogers98fea472020-04-01 15:43:48 -0700835 }
836 // Entry was written successfully; update descriptor's address and the sector
837 // descriptors to reflect the new entry.
838 new_sector->RemoveWritableBytes(result.size());
839 new_sector->AddValidBytes(result.size());
840
841 return result;
842}
843
Wyatt Heplere2cbadf2020-06-22 11:21:45 -0700844Status KeyValueStore::RelocateEntry(
845 const EntryMetadata& metadata,
846 KeyValueStore::Address& address,
847 std::span<const Address> reserved_addresses) {
David Rogersa2562b52020-03-05 15:30:05 -0800848 Entry entry;
David Rogersc4dc8642020-09-14 10:52:36 -0700849 PW_TRY(ReadEntry(metadata, entry));
David Rogersa2562b52020-03-05 15:30:05 -0800850
851 // Find a new sector for the entry and write it to the new location. For
852 // relocation the find should not not be a sector already containing the key
853 // but can be the always empty sector, since this is part of the GC process
854 // that will result in a new empty sector. Also find a sector that does not
855 // have reclaimable space (mostly for the full GC, where that would result in
856 // an immediate extra relocation).
857 SectorDescriptor* new_sector;
858
David Rogersc4dc8642020-09-14 10:52:36 -0700859 PW_TRY(sectors_.FindSpaceDuringGarbageCollection(
Wyatt Heplerc84393f2020-03-20 11:23:24 -0700860 &new_sector, entry.size(), metadata.addresses(), reserved_addresses));
Wyatt Heplerab3b2492020-03-11 16:15:16 -0700861
David Rogers31b358b2020-04-15 05:00:50 -0700862 Address new_address = sectors_.NextWritableAddress(*new_sector);
David Rogersc4dc8642020-09-14 10:52:36 -0700863 PW_TRY_ASSIGN(const size_t result_size,
864 CopyEntryToSector(entry, new_sector, new_address));
David Rogers98fea472020-04-01 15:43:48 -0700865 sectors_.FromAddress(address).RemoveValidBytes(result_size);
Wyatt Heplerab3b2492020-03-11 16:15:16 -0700866 address = new_address;
David Rogersa2562b52020-03-05 15:30:05 -0800867
Wyatt Heplerd78f7c62020-09-28 14:27:32 -0700868 return Status::Ok();
David Rogersa2562b52020-03-05 15:30:05 -0800869}
870
David Rogers3c298372020-10-12 14:15:39 -0700871Status KeyValueStore::FullMaintenanceHelper(MaintenanceType maintenance_type) {
David Rogers9abe3c72020-03-24 19:03:13 -0700872 if (initialized_ == InitializationState::kNotInitialized) {
Wyatt Heplerd78f7c62020-09-28 14:27:32 -0700873 return Status::FailedPrecondition();
David Rogers9abe3c72020-03-24 19:03:13 -0700874 }
875
Armando Montanez17083bb2020-04-24 10:18:26 -0700876 // Full maintenance can be a potentially heavy operation, and should be
877 // relatively infrequent, so log start/end at INFO level.
878 INF("Beginning full maintenance");
David Rogers98fea472020-04-01 15:43:48 -0700879 CheckForErrors();
David Rogers9abe3c72020-03-24 19:03:13 -0700880
881 if (error_detected_) {
David Rogersc4dc8642020-09-14 10:52:36 -0700882 PW_TRY(Repair());
David Rogers9abe3c72020-03-24 19:03:13 -0700883 }
David Rogers35c3f842020-04-22 15:34:05 -0700884 StatusWithSize update_status = UpdateEntriesToPrimaryFormat();
885 Status overall_status = update_status.status();
886
David Rogers31b358b2020-04-15 05:00:50 -0700887 // Make sure all the entries are on the primary format.
Armando Montanez17083bb2020-04-24 10:18:26 -0700888 if (!overall_status.ok()) {
889 ERR("Failed to update all entries to the primary format");
890 }
David Rogers31b358b2020-04-15 05:00:50 -0700891
Wyatt Heplerc84393f2020-03-20 11:23:24 -0700892 SectorDescriptor* sector = sectors_.last_new();
David Rogerscd87c322020-02-27 14:04:08 -0800893
David Rogers35c3f842020-04-22 15:34:05 -0700894 // Calculate number of bytes for the threshold.
895 size_t threshold_bytes =
896 (partition_.size_bytes() * kGcUsageThresholdPercentage) / 100;
897
898 // Is bytes in use over the threshold.
899 StorageStats stats = GetStorageStats();
900 bool over_usage_threshold = stats.in_use_bytes > threshold_bytes;
David Rogers3c298372020-10-12 14:15:39 -0700901 bool heavy = (maintenance_type == MaintenanceType::kHeavy);
902 bool force_gc = heavy || over_usage_threshold || (update_status.size() > 0);
David Rogers35c3f842020-04-22 15:34:05 -0700903
David Rogerscd87c322020-02-27 14:04:08 -0800904 // TODO: look in to making an iterator method for cycling through sectors
905 // starting from last_new_sector_.
Armando Montanez17083bb2020-04-24 10:18:26 -0700906 Status gc_status;
David Rogerscd87c322020-02-27 14:04:08 -0800907 for (size_t j = 0; j < sectors_.size(); j++) {
908 sector += 1;
909 if (sector == sectors_.end()) {
910 sector = sectors_.begin();
911 }
912
David Rogers35c3f842020-04-22 15:34:05 -0700913 if (sector->RecoverableBytes(partition_.sector_size_bytes()) > 0 &&
914 (force_gc || sector->valid_bytes() == 0)) {
Armando Montanez17083bb2020-04-24 10:18:26 -0700915 gc_status = GarbageCollectSector(*sector, {});
916 if (!gc_status.ok()) {
917 ERR("Failed to garbage collect all sectors");
918 break;
919 }
David Rogerscd87c322020-02-27 14:04:08 -0800920 }
921 }
Armando Montanez17083bb2020-04-24 10:18:26 -0700922 if (overall_status.ok()) {
923 overall_status = gc_status;
924 }
David Rogerscd87c322020-02-27 14:04:08 -0800925
Armando Montanez17083bb2020-04-24 10:18:26 -0700926 if (overall_status.ok()) {
927 INF("Full maintenance complete");
928 } else {
929 ERR("Full maintenance finished with some errors");
930 }
931 return overall_status;
David Rogerscd87c322020-02-27 14:04:08 -0800932}
933
David Rogers0f8a1bb2020-04-21 18:50:19 -0700934Status KeyValueStore::PartialMaintenance() {
David Rogers9abe3c72020-03-24 19:03:13 -0700935 if (initialized_ == InitializationState::kNotInitialized) {
Wyatt Heplerd78f7c62020-09-28 14:27:32 -0700936 return Status::FailedPrecondition();
David Rogers9abe3c72020-03-24 19:03:13 -0700937 }
938
David Rogers0f8a1bb2020-04-21 18:50:19 -0700939 CheckForErrors();
David Rogersfcea3252020-04-07 14:56:35 -0700940 // Do automatic repair, if KVS options allow for it.
941 if (error_detected_ && options_.recovery != ErrorRecovery::kManual) {
David Rogersc4dc8642020-09-14 10:52:36 -0700942 PW_TRY(Repair());
David Rogersfcea3252020-04-07 14:56:35 -0700943 }
Wyatt Heplere2cbadf2020-06-22 11:21:45 -0700944 return GarbageCollect(std::span<const Address>());
David Rogers0f8a1bb2020-04-21 18:50:19 -0700945}
946
Wyatt Heplere2cbadf2020-06-22 11:21:45 -0700947Status KeyValueStore::GarbageCollect(
948 std::span<const Address> reserved_addresses) {
David Rogers0f8a1bb2020-04-21 18:50:19 -0700949 DBG("Garbage Collect a single sector");
950 for (Address address : reserved_addresses) {
951 DBG(" Avoid address %u", unsigned(address));
952 }
David Rogersfcea3252020-04-07 14:56:35 -0700953
David Rogersa12786b2020-01-31 16:02:33 -0800954 // Step 1: Find the sector to garbage collect
David Rogersc9d545e2020-03-11 17:47:43 -0700955 SectorDescriptor* sector_to_gc =
Wyatt Heplerc84393f2020-03-20 11:23:24 -0700956 sectors_.FindSectorToGarbageCollect(reserved_addresses);
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800957
David Rogersa12786b2020-01-31 16:02:33 -0800958 if (sector_to_gc == nullptr) {
David Rogersa2562b52020-03-05 15:30:05 -0800959 // Nothing to GC.
Wyatt Heplerd78f7c62020-09-28 14:27:32 -0700960 return Status::NotFound();
David Rogersa12786b2020-01-31 16:02:33 -0800961 }
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800962
David Rogersc9d545e2020-03-11 17:47:43 -0700963 // Step 2: Garbage collect the selected sector.
Wyatt Heplerc84393f2020-03-20 11:23:24 -0700964 return GarbageCollectSector(*sector_to_gc, reserved_addresses);
David Rogerscd87c322020-02-27 14:04:08 -0800965}
966
David Rogersf3884eb2020-03-08 19:21:40 -0700967Status KeyValueStore::RelocateKeyAddressesInSector(
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700968 SectorDescriptor& sector_to_gc,
David Rogersfcea3252020-04-07 14:56:35 -0700969 const EntryMetadata& metadata,
Wyatt Heplere2cbadf2020-06-22 11:21:45 -0700970 std::span<const Address> reserved_addresses) {
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700971 for (FlashPartition::Address& address : metadata.addresses()) {
Wyatt Heplerc84393f2020-03-20 11:23:24 -0700972 if (sectors_.AddressInSector(sector_to_gc, address)) {
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700973 DBG(" Relocate entry for Key 0x%08" PRIx32 ", sector %u",
974 metadata.hash(),
Wyatt Heplerc84393f2020-03-20 11:23:24 -0700975 sectors_.Index(sectors_.FromAddress(address)));
David Rogersc4dc8642020-09-14 10:52:36 -0700976 PW_TRY(RelocateEntry(metadata, address, reserved_addresses));
David Rogersf3884eb2020-03-08 19:21:40 -0700977 }
978 }
Wyatt Heplerab3b2492020-03-11 16:15:16 -0700979
Wyatt Heplerd78f7c62020-09-28 14:27:32 -0700980 return Status::Ok();
David Rogersf3884eb2020-03-08 19:21:40 -0700981};
982
Wyatt Heplerab3b2492020-03-11 16:15:16 -0700983Status KeyValueStore::GarbageCollectSector(
Wyatt Heplere2cbadf2020-06-22 11:21:45 -0700984 SectorDescriptor& sector_to_gc,
985 std::span<const Address> reserved_addresses) {
David Rogers9abe3c72020-03-24 19:03:13 -0700986 DBG(" Garbage Collect sector %u", sectors_.Index(sector_to_gc));
David Rogers3c298372020-10-12 14:15:39 -0700987
David Rogersf3884eb2020-03-08 19:21:40 -0700988 // Step 1: Move any valid entries in the GC sector to other sectors
Wyatt Heplerc84393f2020-03-20 11:23:24 -0700989 if (sector_to_gc.valid_bytes() != 0) {
David Rogers98fea472020-04-01 15:43:48 -0700990 for (EntryMetadata& metadata : entry_cache_) {
David Rogersc4dc8642020-09-14 10:52:36 -0700991 PW_TRY(RelocateKeyAddressesInSector(
Wyatt Heplerc84393f2020-03-20 11:23:24 -0700992 sector_to_gc, metadata, reserved_addresses));
David Rogersf3884eb2020-03-08 19:21:40 -0700993 }
994 }
995
Wyatt Heplerc84393f2020-03-20 11:23:24 -0700996 if (sector_to_gc.valid_bytes() != 0) {
David Rogers67f4b6c2020-02-06 16:17:09 -0800997 ERR(" Failed to relocate valid entries from sector being garbage "
David Rogers9fc78b82020-06-12 13:56:12 -0700998 "collected, %u valid bytes remain",
999 unsigned(sector_to_gc.valid_bytes()));
Wyatt Heplerd78f7c62020-09-28 14:27:32 -07001000 return Status::Internal();
Wyatt Heplerb7609542020-01-24 10:29:54 -08001001 }
1002
David Rogerscd87c322020-02-27 14:04:08 -08001003 // Step 2: Reinitialize the sector
David Rogers3c298372020-10-12 14:15:39 -07001004 if (!sector_to_gc.Empty(partition_.sector_size_bytes())) {
1005 sector_to_gc.mark_corrupt();
1006 internal_stats_.sector_erase_count++;
1007 PW_TRY(partition_.Erase(sectors_.BaseAddress(sector_to_gc), 1));
1008 sector_to_gc.set_writable_bytes(partition_.sector_size_bytes());
1009 }
Wyatt Heplerb7609542020-01-24 10:29:54 -08001010
Wyatt Heplerc84393f2020-03-20 11:23:24 -07001011 DBG(" Garbage Collect sector %u complete", sectors_.Index(sector_to_gc));
Wyatt Heplerd78f7c62020-09-28 14:27:32 -07001012 return Status::Ok();
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -08001013}
1014
David Rogers35c3f842020-04-22 15:34:05 -07001015StatusWithSize KeyValueStore::UpdateEntriesToPrimaryFormat() {
1016 size_t entries_updated = 0;
David Rogers31b358b2020-04-15 05:00:50 -07001017 for (EntryMetadata& prior_metadata : entry_cache_) {
1018 Entry entry;
David Rogersc4dc8642020-09-14 10:52:36 -07001019 PW_TRY_WITH_SIZE(ReadEntry(prior_metadata, entry));
David Rogers31b358b2020-04-15 05:00:50 -07001020 if (formats_.primary().magic == entry.magic()) {
1021 // Ignore entries that are already on the primary format.
1022 continue;
1023 }
1024
1025 DBG("Updating entry 0x%08x from old format [0x%08x] to new format "
1026 "[0x%08x]",
1027 unsigned(prior_metadata.hash()),
1028 unsigned(entry.magic()),
1029 unsigned(formats_.primary().magic));
1030
David Rogers35c3f842020-04-22 15:34:05 -07001031 entries_updated++;
1032
David Rogers31b358b2020-04-15 05:00:50 -07001033 last_transaction_id_ += 1;
David Rogersc4dc8642020-09-14 10:52:36 -07001034 PW_TRY_WITH_SIZE(entry.Update(formats_.primary(), last_transaction_id_));
David Rogers31b358b2020-04-15 05:00:50 -07001035
1036 // List of addresses for sectors with space for this entry.
1037 Address* reserved_addresses = entry_cache_.TempReservedAddressesForWrite();
1038
1039 // Find addresses to write the entry to. This may involve garbage collecting
1040 // one or more sectors.
David Rogersc4dc8642020-09-14 10:52:36 -07001041 PW_TRY_WITH_SIZE(GetAddressesForWrite(reserved_addresses, entry.size()));
David Rogers31b358b2020-04-15 05:00:50 -07001042
David Rogersc4dc8642020-09-14 10:52:36 -07001043 PW_TRY_WITH_SIZE(
David Rogers35c3f842020-04-22 15:34:05 -07001044 CopyEntryToSector(entry,
David Rogers31b358b2020-04-15 05:00:50 -07001045 &sectors_.FromAddress(reserved_addresses[0]),
1046 reserved_addresses[0]));
1047
1048 // After writing the first entry successfully, update the key descriptors.
1049 // Once a single new the entry is written, the old entries are invalidated.
1050 EntryMetadata new_metadata = UpdateKeyDescriptor(
1051 entry, reserved_addresses[0], &prior_metadata, entry.size());
1052
1053 // Write the additional copies of the entry, if redundancy is greater
1054 // than 1.
1055 for (size_t i = 1; i < redundancy(); ++i) {
David Rogersc4dc8642020-09-14 10:52:36 -07001056 PW_TRY_WITH_SIZE(
David Rogers35c3f842020-04-22 15:34:05 -07001057 CopyEntryToSector(entry,
David Rogers31b358b2020-04-15 05:00:50 -07001058 &sectors_.FromAddress(reserved_addresses[i]),
1059 reserved_addresses[i]));
1060 new_metadata.AddNewAddress(reserved_addresses[i]);
1061 }
1062 }
David Rogers35c3f842020-04-22 15:34:05 -07001063
1064 return StatusWithSize(entries_updated);
David Rogers31b358b2020-04-15 05:00:50 -07001065}
1066
David Rogers9abe3c72020-03-24 19:03:13 -07001067// Add any missing redundant entries/copies for a key.
1068Status KeyValueStore::AddRedundantEntries(EntryMetadata& metadata) {
David Rogers9abe3c72020-03-24 19:03:13 -07001069 Entry entry;
David Rogersc4dc8642020-09-14 10:52:36 -07001070 PW_TRY(ReadEntry(metadata, entry));
1071 PW_TRY(entry.VerifyChecksumInFlash());
David Rogers9abe3c72020-03-24 19:03:13 -07001072
David Rogers0f8a1bb2020-04-21 18:50:19 -07001073 while (metadata.addresses().size() < redundancy()) {
1074 SectorDescriptor* new_sector;
David Rogersc4dc8642020-09-14 10:52:36 -07001075 PW_TRY(GetSectorForWrite(&new_sector, entry.size(), metadata.addresses()));
David Rogers9abe3c72020-03-24 19:03:13 -07001076
David Rogers31b358b2020-04-15 05:00:50 -07001077 Address new_address = sectors_.NextWritableAddress(*new_sector);
David Rogersc4dc8642020-09-14 10:52:36 -07001078 PW_TRY(CopyEntryToSector(entry, new_sector, new_address));
David Rogers9abe3c72020-03-24 19:03:13 -07001079
1080 metadata.AddNewAddress(new_address);
1081 }
Wyatt Heplerd78f7c62020-09-28 14:27:32 -07001082 return Status::Ok();
David Rogers9abe3c72020-03-24 19:03:13 -07001083}
1084
1085Status KeyValueStore::RepairCorruptSectors() {
1086 // Try to GC each corrupt sector, even if previous sectors fail. If GC of a
1087 // sector failed on the first pass, then do a second pass, since a later
1088 // sector might have cleared up space or otherwise unblocked the earlier
1089 // failed sector.
Wyatt Heplerd78f7c62020-09-28 14:27:32 -07001090 Status repair_status = Status::Ok();
David Rogers9abe3c72020-03-24 19:03:13 -07001091
1092 size_t loop_count = 0;
1093 do {
1094 loop_count++;
1095 // Error of RESOURCE_EXHAUSTED indicates no space found for relocation.
1096 // Reset back to OK for the next pass.
Wyatt Heplerd78f7c62020-09-28 14:27:32 -07001097 if (repair_status == Status::ResourceExhausted()) {
1098 repair_status = Status::Ok();
David Rogers9abe3c72020-03-24 19:03:13 -07001099 }
1100
1101 DBG(" Pass %u", unsigned(loop_count));
1102 for (SectorDescriptor& sector : sectors_) {
1103 if (sector.corrupt()) {
1104 DBG(" Found sector %u with corruption", sectors_.Index(sector));
1105 Status sector_status = GarbageCollectSector(sector, {});
1106 if (sector_status.ok()) {
David Rogers3c298372020-10-12 14:15:39 -07001107 internal_stats_.corrupt_sectors_recovered += 1;
David Rogers9abe3c72020-03-24 19:03:13 -07001108 } else if (repair_status.ok() ||
Wyatt Heplerd78f7c62020-09-28 14:27:32 -07001109 repair_status == Status::ResourceExhausted()) {
David Rogers9abe3c72020-03-24 19:03:13 -07001110 repair_status = sector_status;
1111 }
1112 }
1113 }
1114 DBG(" Pass %u complete", unsigned(loop_count));
1115 } while (!repair_status.ok() && loop_count < 2);
1116
1117 return repair_status;
1118}
1119
1120Status KeyValueStore::EnsureFreeSectorExists() {
Wyatt Heplerd78f7c62020-09-28 14:27:32 -07001121 Status repair_status = Status::Ok();
David Rogers9abe3c72020-03-24 19:03:13 -07001122 bool empty_sector_found = false;
1123
1124 DBG(" Find empty sector");
1125 for (SectorDescriptor& sector : sectors_) {
1126 if (sector.Empty(partition_.sector_size_bytes())) {
1127 empty_sector_found = true;
1128 DBG(" Empty sector found");
1129 break;
1130 }
1131 }
1132 if (empty_sector_found == false) {
1133 DBG(" No empty sector found, attempting to GC a free sector");
Wyatt Heplere2cbadf2020-06-22 11:21:45 -07001134 Status sector_status = GarbageCollect(std::span<const Address, 0>());
David Rogers9abe3c72020-03-24 19:03:13 -07001135 if (repair_status.ok() && !sector_status.ok()) {
1136 DBG(" Unable to free an empty sector");
1137 repair_status = sector_status;
1138 }
1139 }
1140
1141 return repair_status;
1142}
1143
1144Status KeyValueStore::EnsureEntryRedundancy() {
Wyatt Heplerd78f7c62020-09-28 14:27:32 -07001145 Status repair_status = Status::Ok();
David Rogers9abe3c72020-03-24 19:03:13 -07001146
1147 if (redundancy() == 1) {
David Rogers98fea472020-04-01 15:43:48 -07001148 DBG(" Redundancy not in use, nothting to check");
Wyatt Heplerd78f7c62020-09-28 14:27:32 -07001149 return Status::Ok();
David Rogers9abe3c72020-03-24 19:03:13 -07001150 }
1151
David Rogers98fea472020-04-01 15:43:48 -07001152 DBG(" Write any needed additional duplicate copies of keys to fulfill %u"
1153 " redundancy",
David Rogers9abe3c72020-03-24 19:03:13 -07001154 unsigned(redundancy()));
David Rogers98fea472020-04-01 15:43:48 -07001155 for (EntryMetadata& metadata : entry_cache_) {
David Rogers9abe3c72020-03-24 19:03:13 -07001156 if (metadata.addresses().size() >= redundancy()) {
1157 continue;
1158 }
1159
1160 DBG(" Key with %u of %u copies found, adding missing copies",
1161 unsigned(metadata.addresses().size()),
1162 unsigned(redundancy()));
David Rogers98fea472020-04-01 15:43:48 -07001163 Status fill_status = AddRedundantEntries(metadata);
David Rogers9abe3c72020-03-24 19:03:13 -07001164 if (fill_status.ok()) {
David Rogers3c298372020-10-12 14:15:39 -07001165 internal_stats_.missing_redundant_entries_recovered += 1;
David Rogers9abe3c72020-03-24 19:03:13 -07001166 DBG(" Key missing copies added");
1167 } else {
1168 DBG(" Failed to add key missing copies");
1169 if (repair_status.ok()) {
1170 repair_status = fill_status;
1171 }
1172 }
1173 }
1174
1175 return repair_status;
1176}
1177
David Rogersfcea3252020-04-07 14:56:35 -07001178Status KeyValueStore::FixErrors() {
1179 DBG("Fixing KVS errors");
David Rogers9abe3c72020-03-24 19:03:13 -07001180
1181 // Step 1: Garbage collect any sectors marked as corrupt.
David Rogersfcea3252020-04-07 14:56:35 -07001182 Status overall_status = RepairCorruptSectors();
David Rogers9abe3c72020-03-24 19:03:13 -07001183
1184 // Step 2: Make sure there is at least 1 empty sector. This needs to be a
1185 // seperate check of sectors from step 1, because a found empty sector might
1186 // get written to by a later GC that fails and does not result in a free
1187 // sector.
David Rogersfcea3252020-04-07 14:56:35 -07001188 Status repair_status = EnsureFreeSectorExists();
David Rogers9abe3c72020-03-24 19:03:13 -07001189 if (overall_status.ok()) {
1190 overall_status = repair_status;
1191 }
1192
1193 // Step 3: Make sure each stored key has the full number of redundant
1194 // entries.
1195 repair_status = EnsureEntryRedundancy();
1196 if (overall_status.ok()) {
1197 overall_status = repair_status;
1198 }
1199
1200 if (overall_status.ok()) {
1201 error_detected_ = false;
1202 initialized_ = InitializationState::kReady;
1203 }
1204 return overall_status;
1205}
1206
David Rogersfcea3252020-04-07 14:56:35 -07001207Status KeyValueStore::Repair() {
1208 // If errors have been detected, just reinit the KVS metadata. This does a
1209 // full deep error check and any needed repairs. Then repair any errors.
1210 INF("Starting KVS repair");
1211
1212 DBG("Reinitialize KVS metadata");
1213 InitializeMetadata();
1214
1215 return FixErrors();
1216}
1217
David Rogersd50eb1c2020-05-12 17:46:36 -07001218KeyValueStore::Entry KeyValueStore::CreateEntry(Address address,
1219 string_view key,
Wyatt Heplere2cbadf2020-06-22 11:21:45 -07001220 std::span<const byte> value,
Wyatt Hepler7ded6da2020-03-11 18:24:43 -07001221 EntryState state) {
Keir Mierle9e38b402020-02-21 13:06:21 -08001222 // Always bump the transaction ID when creating a new entry.
1223 //
1224 // Burning transaction IDs prevents inconsistencies between flash and memory
1225 // that which could happen if a write succeeds, but for some reason the read
1226 // and verify step fails. Here's how this would happen:
1227 //
1228 // 1. The entry is written but for some reason the flash reports failure OR
1229 // The write succeeds, but the read / verify operation fails.
1230 // 2. The transaction ID is NOT incremented, because of the failure
1231 // 3. (later) A new entry is written, re-using the transaction ID (oops)
1232 //
David Rogersd50eb1c2020-05-12 17:46:36 -07001233 // By always burning transaction IDs, the above problem can't happen.
1234 last_transaction_id_ += 1;
Keir Mierle9e38b402020-02-21 13:06:21 -08001235
Wyatt Hepler7ded6da2020-03-11 18:24:43 -07001236 if (state == EntryState::kDeleted) {
Wyatt Hepler7465be32020-02-21 15:30:53 -08001237 return Entry::Tombstone(
David Rogersd50eb1c2020-05-12 17:46:36 -07001238 partition_, address, formats_.primary(), key, last_transaction_id_);
Wyatt Hepler1fc11042020-02-19 17:17:51 -08001239 }
David Rogersd50eb1c2020-05-12 17:46:36 -07001240 return Entry::Valid(partition_,
1241 address,
1242 formats_.primary(),
1243 key,
1244 value,
1245 last_transaction_id_);
Wyatt Heplerd2298282020-02-20 17:12:45 -08001246}
1247
Wyatt Hepler7ded6da2020-03-11 18:24:43 -07001248void KeyValueStore::LogDebugInfo() const {
Keir Mierle8c352dc2020-02-02 13:58:19 -08001249 const size_t sector_size_bytes = partition_.sector_size_bytes();
1250 DBG("====================== KEY VALUE STORE DUMP =========================");
1251 DBG(" ");
1252 DBG("Flash partition:");
David Rogers9fc78b82020-06-12 13:56:12 -07001253 DBG(" Sector count = %u", unsigned(partition_.sector_count()));
1254 DBG(" Sector max count = %u", unsigned(sectors_.max_size()));
1255 DBG(" Sectors in use = %u", unsigned(sectors_.size()));
1256 DBG(" Sector size = %u", unsigned(sector_size_bytes));
1257 DBG(" Total size = %u", unsigned(partition_.size_bytes()));
1258 DBG(" Alignment = %u", unsigned(partition_.alignment_bytes()));
Keir Mierle8c352dc2020-02-02 13:58:19 -08001259 DBG(" ");
1260 DBG("Key descriptors:");
David Rogers9fc78b82020-06-12 13:56:12 -07001261 DBG(" Entry count = %u", unsigned(entry_cache_.total_entries()));
1262 DBG(" Max entry count = %u", unsigned(entry_cache_.max_entries()));
Keir Mierle8c352dc2020-02-02 13:58:19 -08001263 DBG(" ");
1264 DBG(" # hash version address address (hex)");
Armando Montanez888370d2020-05-01 18:29:22 -07001265 size_t count = 0;
Wyatt Hepler7ded6da2020-03-11 18:24:43 -07001266 for (const EntryMetadata& metadata : entry_cache_) {
Keir Mierle8c352dc2020-02-02 13:58:19 -08001267 DBG(" |%3zu: | %8zx |%8zu | %8zu | %8zx",
Armando Montanez888370d2020-05-01 18:29:22 -07001268 count++,
Wyatt Hepler7ded6da2020-03-11 18:24:43 -07001269 size_t(metadata.hash()),
1270 size_t(metadata.transaction_id()),
1271 size_t(metadata.first_address()),
1272 size_t(metadata.first_address()));
Keir Mierle8c352dc2020-02-02 13:58:19 -08001273 }
1274 DBG(" ");
1275
1276 DBG("Sector descriptors:");
1277 DBG(" # tail free valid has_space");
Wyatt Heplerc84393f2020-03-20 11:23:24 -07001278 for (const SectorDescriptor& sd : sectors_) {
1279 DBG(" |%3u: | %8zu |%8zu | %s",
1280 sectors_.Index(sd),
Wyatt Hepler2c7eca02020-02-18 16:01:42 -08001281 size_t(sd.writable_bytes()),
1282 sd.valid_bytes(),
1283 sd.writable_bytes() ? "YES" : "");
Keir Mierle8c352dc2020-02-02 13:58:19 -08001284 }
1285 DBG(" ");
1286
1287 // TODO: This should stop logging after some threshold.
1288 // size_t dumped_bytes = 0;
1289 DBG("Sector raw data:");
Wyatt Hepler1c329ca2020-02-07 18:07:23 -08001290 for (size_t sector_id = 0; sector_id < sectors_.size(); ++sector_id) {
Keir Mierle8c352dc2020-02-02 13:58:19 -08001291 // Read sector data. Yes, this will blow the stack on embedded.
Wyatt Hepler1c329ca2020-02-07 18:07:23 -08001292 std::array<byte, 500> raw_sector_data; // TODO!!!
Keir Mierle8c352dc2020-02-02 13:58:19 -08001293 StatusWithSize sws =
1294 partition_.Read(sector_id * sector_size_bytes, raw_sector_data);
David Rogers9fc78b82020-06-12 13:56:12 -07001295 DBG("Read: %u bytes", unsigned(sws.size()));
Keir Mierle8c352dc2020-02-02 13:58:19 -08001296
1297 DBG(" base addr offs 0 1 2 3 4 5 6 7");
1298 for (size_t i = 0; i < sector_size_bytes; i += 8) {
1299 DBG(" %3zu %8zx %5zu | %02x %02x %02x %02x %02x %02x %02x %02x",
1300 sector_id,
1301 (sector_id * sector_size_bytes) + i,
1302 i,
1303 static_cast<unsigned int>(raw_sector_data[i + 0]),
1304 static_cast<unsigned int>(raw_sector_data[i + 1]),
1305 static_cast<unsigned int>(raw_sector_data[i + 2]),
1306 static_cast<unsigned int>(raw_sector_data[i + 3]),
1307 static_cast<unsigned int>(raw_sector_data[i + 4]),
1308 static_cast<unsigned int>(raw_sector_data[i + 5]),
1309 static_cast<unsigned int>(raw_sector_data[i + 6]),
1310 static_cast<unsigned int>(raw_sector_data[i + 7]));
1311
1312 // TODO: Fix exit condition.
1313 if (i > 128) {
1314 break;
1315 }
1316 }
1317 DBG(" ");
1318 }
1319
1320 DBG("////////////////////// KEY VALUE STORE DUMP END /////////////////////");
1321}
1322
David Rogerscf680ab2020-02-12 23:28:32 -08001323void KeyValueStore::LogSectors() const {
David Rogers9fc78b82020-06-12 13:56:12 -07001324 DBG("Sector descriptors: count %u", unsigned(sectors_.size()));
Wyatt Hepler1c329ca2020-02-07 18:07:23 -08001325 for (auto& sector : sectors_) {
David Rogers9fc78b82020-06-12 13:56:12 -07001326 DBG(" - Sector %u: valid %u, recoverable %u, free %u",
Wyatt Heplerc84393f2020-03-20 11:23:24 -07001327 sectors_.Index(sector),
David Rogers9fc78b82020-06-12 13:56:12 -07001328 unsigned(sector.valid_bytes()),
1329 unsigned(sector.RecoverableBytes(partition_.sector_size_bytes())),
1330 unsigned(sector.writable_bytes()));
David Rogers50185ad2020-02-07 00:02:46 -08001331 }
1332}
1333
David Rogerscf680ab2020-02-12 23:28:32 -08001334void KeyValueStore::LogKeyDescriptor() const {
David Rogers9fc78b82020-06-12 13:56:12 -07001335 DBG("Key descriptors: count %u", unsigned(entry_cache_.total_entries()));
David Rogers9abe3c72020-03-24 19:03:13 -07001336 for (const EntryMetadata& metadata : entry_cache_) {
David Rogers9fc78b82020-06-12 13:56:12 -07001337 DBG(" - Key: %s, hash %#x, transaction ID %u, first address %#x",
Wyatt Hepler02946272020-03-18 10:36:22 -07001338 metadata.state() == EntryState::kDeleted ? "Deleted" : "Valid",
David Rogers9fc78b82020-06-12 13:56:12 -07001339 unsigned(metadata.hash()),
1340 unsigned(metadata.transaction_id()),
1341 unsigned(metadata.first_address()));
David Rogerscf680ab2020-02-12 23:28:32 -08001342 }
1343}
1344
Wyatt Hepler2ad60672020-01-21 08:00:16 -08001345} // namespace pw::kvs