blob: 56d706c0ad6e911a3b95e986b396ea0463c162c5 [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"
Wyatt Heplerae222dc2020-10-14 10:46:27 -070016#define PW_LOG_LEVEL PW_KVS_LOG_LEVEL
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
Wyatt Heplerf298de42021-03-19 15:06:36 -070025#include "pw_assert/check.h"
Wyatt Heplerae222dc2020-10-14 10:46:27 -070026#include "pw_kvs_private/config.h"
Wyatt Hepler0cdb1a32021-03-05 14:16:13 -080027#include "pw_log/shorter.h"
David Rogersb6b14b82020-09-11 16:27:27 -070028#include "pw_status/try.h"
Wyatt Heplerb7609542020-01-24 10:29:54 -080029
Wyatt Hepler2ad60672020-01-21 08:00:16 -080030namespace pw::kvs {
Wyatt Heplera00d1ef2020-02-14 14:31:26 -080031namespace {
Wyatt Heplerb7609542020-01-24 10:29:54 -080032
Wyatt Hepleracaacf92020-01-24 10:58:30 -080033using std::byte;
34
Rob Olivere64daf42020-11-24 11:50:03 -050035constexpr bool InvalidKey(Key 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 Heplerf276c6b2020-11-11 21:13:38 -0800104 if (metadata_result.IsOutOfRange()) {
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 Heplerf276c6b2020-11-11 21:13:38 -0800112 } else if (recovery_status.IsResourceExhausted()) {
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 Hepler1b3da3a2021-01-07 13:26:57 -0800136 return OkStatus();
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 Heplerf276c6b2020-11-11 21:13:38 -0800171 if (status.IsNotFound()) {
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 Hepler1b3da3a2021-01-07 13:26:57 -0800297 return OkStatus();
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));
Rob Olivere64daf42020-11-24 11:50:03 -0500361 const Key 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 Hepler1b3da3a2021-01-07 13:26:57 -0800396 return OkStatus();
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
Rob Olivere64daf42020-11-24 11:50:03 -0500403StatusWithSize KeyValueStore::Get(Key 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
Rob Olivere64daf42020-11-24 11:50:03 -0500414Status KeyValueStore::PutBytes(Key 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 Heplerf276c6b2020-11-11 21:13:38 -0800439 if (status.IsNotFound()) {
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
Rob Olivere64daf42020-11-24 11:50:03 -0500446Status KeyValueStore::Delete(Key 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
Rob Olivere64daf42020-11-24 11:50:03 -0500487StatusWithSize KeyValueStore::ValueSize(Key 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
Rob Olivere64daf42020-11-24 11:50:03 -0500515Status KeyValueStore::FindEntry(Key key, EntryMetadata* found_entry) const {
David Rogers98fea472020-04-01 15:43:48 -0700516 StatusWithSize find_result =
517 entry_cache_.Find(partition_, sectors_, formats_, key, found_entry);
518
519 if (find_result.size() > 0u) {
520 error_detected_ = true;
521 }
522 return find_result.status();
523}
524
Rob Olivere64daf42020-11-24 11:50:03 -0500525Status KeyValueStore::FindExisting(Key key, EntryMetadata* metadata) const {
David Rogers98fea472020-04-01 15:43:48 -0700526 Status status = FindEntry(key, metadata);
527
528 // If the key's hash collides with an existing key or if the key is deleted,
529 // treat it as if it is not in the KVS.
Wyatt Heplerf276c6b2020-11-11 21:13:38 -0800530 if (status.IsAlreadyExists() ||
David Rogers98fea472020-04-01 15:43:48 -0700531 (status.ok() && metadata->state() == EntryState::kDeleted)) {
Wyatt Heplerd78f7c62020-09-28 14:27:32 -0700532 return Status::NotFound();
David Rogers98fea472020-04-01 15:43:48 -0700533 }
534 return status;
535}
536
Rob Olivere64daf42020-11-24 11:50:03 -0500537StatusWithSize KeyValueStore::Get(Key key,
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700538 const EntryMetadata& metadata,
Wyatt Heplere2cbadf2020-06-22 11:21:45 -0700539 std::span<std::byte> value_buffer,
Wyatt Heplerfac81132020-02-27 17:26:33 -0800540 size_t offset_bytes) const {
541 Entry entry;
David Rogers98fea472020-04-01 15:43:48 -0700542
David Rogersc4dc8642020-09-14 10:52:36 -0700543 PW_TRY_WITH_SIZE(ReadEntry(metadata, entry));
Wyatt Heplerfac81132020-02-27 17:26:33 -0800544
545 StatusWithSize result = entry.ReadValue(value_buffer, offset_bytes);
546 if (result.ok() && options_.verify_on_read && offset_bytes == 0u) {
Wyatt Hepler22d0d9f2020-03-05 14:57:11 -0800547 Status verify_result =
548 entry.VerifyChecksum(key, value_buffer.first(result.size()));
Wyatt Heplerfac81132020-02-27 17:26:33 -0800549 if (!verify_result.ok()) {
550 std::memset(value_buffer.data(), 0, result.size());
551 return StatusWithSize(verify_result, 0);
552 }
553
554 return StatusWithSize(verify_result, result.size());
555 }
556 return result;
Wyatt Heplered163b02020-02-03 17:49:32 -0800557}
558
Rob Olivere64daf42020-11-24 11:50:03 -0500559Status KeyValueStore::FixedSizeGet(Key key,
Wyatt Heplerfac81132020-02-27 17:26:33 -0800560 void* value,
561 size_t size_bytes) const {
David Rogersc4dc8642020-09-14 10:52:36 -0700562 PW_TRY(CheckWriteOperation(key));
Wyatt Heplerfac81132020-02-27 17:26:33 -0800563
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700564 EntryMetadata metadata;
David Rogersc4dc8642020-09-14 10:52:36 -0700565 PW_TRY(FindExisting(key, &metadata));
Wyatt Heplerfac81132020-02-27 17:26:33 -0800566
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700567 return FixedSizeGet(key, metadata, value, size_bytes);
Wyatt Heplerfac81132020-02-27 17:26:33 -0800568}
569
Rob Olivere64daf42020-11-24 11:50:03 -0500570Status KeyValueStore::FixedSizeGet(Key key,
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700571 const EntryMetadata& metadata,
Wyatt Heplerfac81132020-02-27 17:26:33 -0800572 void* value,
Wyatt Hepler6e3a83b2020-02-04 07:36:45 -0800573 size_t size_bytes) const {
574 // Ensure that the size of the stored value matches the size of the type.
575 // Otherwise, report error. This check avoids potential memory corruption.
David Rogersc4dc8642020-09-14 10:52:36 -0700576 PW_TRY_ASSIGN(const size_t actual_size, ValueSize(metadata));
Wyatt Heplerfac81132020-02-27 17:26:33 -0800577
578 if (actual_size != size_bytes) {
David Rogers9fc78b82020-06-12 13:56:12 -0700579 DBG("Requested %u B read, but value is %u B",
580 unsigned(size_bytes),
581 unsigned(actual_size));
Wyatt Heplerd78f7c62020-09-28 14:27:32 -0700582 return Status::InvalidArgument();
Wyatt Heplerbab0e202020-02-04 07:40:08 -0800583 }
Wyatt Heplerfac81132020-02-27 17:26:33 -0800584
585 StatusWithSize result =
Wyatt Heplere2cbadf2020-06-22 11:21:45 -0700586 Get(key, metadata, std::span(static_cast<byte*>(value), size_bytes), 0);
Wyatt Heplerfac81132020-02-27 17:26:33 -0800587
588 return result.status();
589}
590
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700591StatusWithSize KeyValueStore::ValueSize(const EntryMetadata& metadata) const {
Wyatt Heplerfac81132020-02-27 17:26:33 -0800592 Entry entry;
David Rogersc4dc8642020-09-14 10:52:36 -0700593 PW_TRY_WITH_SIZE(ReadEntry(metadata, entry));
Wyatt Heplerfac81132020-02-27 17:26:33 -0800594
595 return StatusWithSize(entry.value_size());
Keir Mierle8c352dc2020-02-02 13:58:19 -0800596}
597
Rob Olivere64daf42020-11-24 11:50:03 -0500598Status KeyValueStore::CheckWriteOperation(Key key) const {
Wyatt Hepleracaacf92020-01-24 10:58:30 -0800599 if (InvalidKey(key)) {
Wyatt Heplerd78f7c62020-09-28 14:27:32 -0700600 return Status::InvalidArgument();
Wyatt Heplerb7609542020-01-24 10:29:54 -0800601 }
David Rogers9abe3c72020-03-24 19:03:13 -0700602
603 // For normal write operation the KVS must be fully ready.
Wyatt Heplerd2298282020-02-20 17:12:45 -0800604 if (!initialized()) {
Wyatt Heplerd78f7c62020-09-28 14:27:32 -0700605 return Status::FailedPrecondition();
Wyatt Heplerb7609542020-01-24 10:29:54 -0800606 }
Wyatt Hepler1b3da3a2021-01-07 13:26:57 -0800607 return OkStatus();
Wyatt Heplerb7609542020-01-24 10:29:54 -0800608}
609
Rob Olivere64daf42020-11-24 11:50:03 -0500610Status KeyValueStore::CheckReadOperation(Key key) const {
David Rogers9abe3c72020-03-24 19:03:13 -0700611 if (InvalidKey(key)) {
Wyatt Heplerd78f7c62020-09-28 14:27:32 -0700612 return Status::InvalidArgument();
David Rogers9abe3c72020-03-24 19:03:13 -0700613 }
614
615 // Operations that are explicitly read-only can be done after init() has been
616 // called but not fully ready (when needing maintenance).
617 if (initialized_ == InitializationState::kNotInitialized) {
Wyatt Heplerd78f7c62020-09-28 14:27:32 -0700618 return Status::FailedPrecondition();
David Rogers9abe3c72020-03-24 19:03:13 -0700619 }
Wyatt Hepler1b3da3a2021-01-07 13:26:57 -0800620 return OkStatus();
David Rogers9abe3c72020-03-24 19:03:13 -0700621}
622
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700623Status KeyValueStore::WriteEntryForExistingKey(EntryMetadata& metadata,
624 EntryState new_state,
Rob Olivere64daf42020-11-24 11:50:03 -0500625 Key key,
Wyatt Heplere2cbadf2020-06-22 11:21:45 -0700626 std::span<const byte> value) {
Wyatt Heplerab3b2492020-03-11 16:15:16 -0700627 // Read the original entry to get the size for sector accounting purposes.
628 Entry entry;
David Rogersc4dc8642020-09-14 10:52:36 -0700629 PW_TRY(ReadEntry(metadata, entry));
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800630
David Rogersc0104462020-05-08 15:50:23 -0700631 return WriteEntry(key, value, new_state, &metadata, &entry);
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800632}
633
Rob Olivere64daf42020-11-24 11:50:03 -0500634Status KeyValueStore::WriteEntryForNewKey(Key key,
Wyatt Heplere2cbadf2020-06-22 11:21:45 -0700635 std::span<const byte> value) {
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700636 if (entry_cache_.full()) {
David Rogers9fc78b82020-06-12 13:56:12 -0700637 WRN("KVS full: trying to store a new entry, but can't. Have %u entries",
638 unsigned(entry_cache_.total_entries()));
Wyatt Heplerd78f7c62020-09-28 14:27:32 -0700639 return Status::ResourceExhausted();
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800640 }
641
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700642 return WriteEntry(key, value, EntryState::kValid);
Wyatt Heplerab3b2492020-03-11 16:15:16 -0700643}
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800644
Rob Olivere64daf42020-11-24 11:50:03 -0500645Status KeyValueStore::WriteEntry(Key key,
Wyatt Heplere2cbadf2020-06-22 11:21:45 -0700646 std::span<const byte> value,
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700647 EntryState new_state,
648 EntryMetadata* prior_metadata,
David Rogersc0104462020-05-08 15:50:23 -0700649 const Entry* prior_entry) {
David Rogersc0104462020-05-08 15:50:23 -0700650 // If new entry and prior entry have matching value size, state, and checksum,
651 // check if the values match. Directly compare the prior and new values
652 // because the checksum can not be depended on to establish equality, it can
653 // only be depended on to establish inequality.
David Rogersd50eb1c2020-05-12 17:46:36 -0700654 if (prior_entry != nullptr && prior_entry->value_size() == value.size() &&
David Rogersc0104462020-05-08 15:50:23 -0700655 prior_metadata->state() == new_state &&
David Rogersc0104462020-05-08 15:50:23 -0700656 prior_entry->ValueMatches(value).ok()) {
David Rogersd50eb1c2020-05-12 17:46:36 -0700657 // The new value matches the prior value, don't need to write anything. Just
658 // keep the existing entry.
David Rogersc0104462020-05-08 15:50:23 -0700659 DBG("Write for key 0x%08x with matching value skipped",
660 unsigned(prior_metadata->hash()));
Wyatt Hepler1b3da3a2021-01-07 13:26:57 -0800661 return OkStatus();
David Rogersc0104462020-05-08 15:50:23 -0700662 }
Wyatt Heplerab3b2492020-03-11 16:15:16 -0700663
664 // List of addresses for sectors with space for this entry.
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700665 Address* reserved_addresses = entry_cache_.TempReservedAddressesForWrite();
Wyatt Heplerab3b2492020-03-11 16:15:16 -0700666
David Rogers31b358b2020-04-15 05:00:50 -0700667 // Find addresses to write the entry to. This may involve garbage collecting
668 // one or more sectors.
David Rogersc0104462020-05-08 15:50:23 -0700669 const size_t entry_size = Entry::size(partition_, key, value);
David Rogersc4dc8642020-09-14 10:52:36 -0700670 PW_TRY(GetAddressesForWrite(reserved_addresses, entry_size));
Wyatt Heplerab3b2492020-03-11 16:15:16 -0700671
672 // Write the entry at the first address that was found.
David Rogersd50eb1c2020-05-12 17:46:36 -0700673 Entry entry = CreateEntry(reserved_addresses[0], key, value, new_state);
David Rogersc4dc8642020-09-14 10:52:36 -0700674 PW_TRY(AppendEntry(entry, key, value));
Wyatt Heplerab3b2492020-03-11 16:15:16 -0700675
676 // After writing the first entry successfully, update the key descriptors.
677 // Once a single new the entry is written, the old entries are invalidated.
David Rogersc0104462020-05-08 15:50:23 -0700678 size_t prior_size = prior_entry != nullptr ? prior_entry->size() : 0;
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700679 EntryMetadata new_metadata =
David Rogers31b358b2020-04-15 05:00:50 -0700680 CreateOrUpdateKeyDescriptor(entry, key, prior_metadata, prior_size);
Wyatt Heplerab3b2492020-03-11 16:15:16 -0700681
682 // Write the additional copies of the entry, if redundancy is greater than 1.
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700683 for (size_t i = 1; i < redundancy(); ++i) {
684 entry.set_address(reserved_addresses[i]);
David Rogersc4dc8642020-09-14 10:52:36 -0700685 PW_TRY(AppendEntry(entry, key, value));
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700686 new_metadata.AddNewAddress(reserved_addresses[i]);
Wyatt Heplerab3b2492020-03-11 16:15:16 -0700687 }
Wyatt Hepler1b3da3a2021-01-07 13:26:57 -0800688 return OkStatus();
Wyatt Heplerb7609542020-01-24 10:29:54 -0800689}
690
David Rogers31b358b2020-04-15 05:00:50 -0700691KeyValueStore::EntryMetadata KeyValueStore::CreateOrUpdateKeyDescriptor(
Wyatt Heplerab3b2492020-03-11 16:15:16 -0700692 const Entry& entry,
Rob Olivere64daf42020-11-24 11:50:03 -0500693 Key key,
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700694 EntryMetadata* prior_metadata,
Wyatt Heplerab3b2492020-03-11 16:15:16 -0700695 size_t prior_size) {
696 // If there is no prior descriptor, create a new one.
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700697 if (prior_metadata == nullptr) {
698 return entry_cache_.AddNew(entry.descriptor(key), entry.address());
David Rogersa2562b52020-03-05 15:30:05 -0800699 }
700
David Rogers31b358b2020-04-15 05:00:50 -0700701 return UpdateKeyDescriptor(
702 entry, entry.address(), prior_metadata, prior_size);
703}
704
705KeyValueStore::EntryMetadata KeyValueStore::UpdateKeyDescriptor(
706 const Entry& entry,
707 Address new_address,
708 EntryMetadata* prior_metadata,
709 size_t prior_size) {
Wyatt Heplerab3b2492020-03-11 16:15:16 -0700710 // Remove valid bytes for the old entry and its copies, which are now stale.
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700711 for (Address address : prior_metadata->addresses()) {
Wyatt Heplerc84393f2020-03-20 11:23:24 -0700712 sectors_.FromAddress(address).RemoveValidBytes(prior_size);
David Rogersa2562b52020-03-05 15:30:05 -0800713 }
714
David Rogers31b358b2020-04-15 05:00:50 -0700715 prior_metadata->Reset(entry.descriptor(prior_metadata->hash()), new_address);
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700716 return *prior_metadata;
David Rogersa2562b52020-03-05 15:30:05 -0800717}
718
David Rogers31b358b2020-04-15 05:00:50 -0700719Status KeyValueStore::GetAddressesForWrite(Address* write_addresses,
720 size_t write_size) {
721 for (size_t i = 0; i < redundancy(); i++) {
722 SectorDescriptor* sector;
David Rogersc4dc8642020-09-14 10:52:36 -0700723 PW_TRY(
724 GetSectorForWrite(&sector, write_size, std::span(write_addresses, i)));
David Rogers31b358b2020-04-15 05:00:50 -0700725 write_addresses[i] = sectors_.NextWritableAddress(*sector);
726
727 DBG("Found space for entry in sector %u at address %u",
728 sectors_.Index(sector),
729 unsigned(write_addresses[i]));
730 }
731
Wyatt Hepler1b3da3a2021-01-07 13:26:57 -0800732 return OkStatus();
David Rogers31b358b2020-04-15 05:00:50 -0700733}
734
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700735// Finds a sector to use for writing a new entry to. Does automatic garbage
David Rogersa2562b52020-03-05 15:30:05 -0800736// collection if needed and allowed.
737//
738// OK: Sector found with needed space.
739// RESOURCE_EXHAUSTED: No sector available with the needed space.
740Status KeyValueStore::GetSectorForWrite(SectorDescriptor** sector,
741 size_t entry_size,
Wyatt Heplere2cbadf2020-06-22 11:21:45 -0700742 std::span<const Address> reserved) {
Wyatt Heplerc84393f2020-03-20 11:23:24 -0700743 Status result = sectors_.FindSpace(sector, entry_size, reserved);
David Rogersa2562b52020-03-05 15:30:05 -0800744
David Rogersf3884eb2020-03-08 19:21:40 -0700745 size_t gc_sector_count = 0;
David Rogersa2562b52020-03-05 15:30:05 -0800746 bool do_auto_gc = options_.gc_on_write != GargbageCollectOnWrite::kDisabled;
747
748 // Do garbage collection as needed, so long as policy allows.
Wyatt Heplerf276c6b2020-11-11 21:13:38 -0800749 while (result.IsResourceExhausted() && do_auto_gc) {
David Rogersa2562b52020-03-05 15:30:05 -0800750 if (options_.gc_on_write == GargbageCollectOnWrite::kOneSector) {
751 // If GC config option is kOneSector clear the flag to not do any more
752 // GC after this try.
753 do_auto_gc = false;
754 }
755 // Garbage collect and then try again to find the best sector.
David Rogers9abe3c72020-03-24 19:03:13 -0700756 Status gc_status = GarbageCollect(reserved);
David Rogersa2562b52020-03-05 15:30:05 -0800757 if (!gc_status.ok()) {
Wyatt Heplerf276c6b2020-11-11 21:13:38 -0800758 if (gc_status.IsNotFound()) {
David Rogersa2562b52020-03-05 15:30:05 -0800759 // Not enough space, and no reclaimable bytes, this KVS is full!
Wyatt Heplerd78f7c62020-09-28 14:27:32 -0700760 return Status::ResourceExhausted();
David Rogersa2562b52020-03-05 15:30:05 -0800761 }
762 return gc_status;
763 }
764
Wyatt Heplerc84393f2020-03-20 11:23:24 -0700765 result = sectors_.FindSpace(sector, entry_size, reserved);
David Rogersf3884eb2020-03-08 19:21:40 -0700766
767 gc_sector_count++;
768 // Allow total sectors + 2 number of GC cycles so that once reclaimable
769 // bytes in all the sectors have been reclaimed can try and free up space by
770 // moving entries for keys other than the one being worked on in to sectors
771 // that have copies of the key trying to be written.
772 if (gc_sector_count > (partition_.sector_count() + 2)) {
773 ERR("Did more GC sectors than total sectors!!!!");
Wyatt Heplerd78f7c62020-09-28 14:27:32 -0700774 return Status::ResourceExhausted();
David Rogersf3884eb2020-03-08 19:21:40 -0700775 }
David Rogersa2562b52020-03-05 15:30:05 -0800776 }
777
778 if (!result.ok()) {
David Rogers9fc78b82020-06-12 13:56:12 -0700779 WRN("Unable to find sector to write %u B", unsigned(entry_size));
David Rogersa2562b52020-03-05 15:30:05 -0800780 }
781 return result;
782}
783
David Rogers9abe3c72020-03-24 19:03:13 -0700784Status KeyValueStore::MarkSectorCorruptIfNotOk(Status status,
785 SectorDescriptor* sector) {
786 if (!status.ok()) {
787 DBG(" Sector %u corrupt", sectors_.Index(sector));
788 sector->mark_corrupt();
789 error_detected_ = true;
790 }
791 return status;
792}
793
Wyatt Heplerab3b2492020-03-11 16:15:16 -0700794Status KeyValueStore::AppendEntry(const Entry& entry,
Rob Olivere64daf42020-11-24 11:50:03 -0500795 Key key,
Wyatt Heplere2cbadf2020-06-22 11:21:45 -0700796 std::span<const byte> value) {
Wyatt Heplerab3b2492020-03-11 16:15:16 -0700797 const StatusWithSize result = entry.Write(key, value);
David Rogersa2562b52020-03-05 15:30:05 -0800798
Wyatt Heplerc84393f2020-03-20 11:23:24 -0700799 SectorDescriptor& sector = sectors_.FromAddress(entry.address());
David Rogersa2562b52020-03-05 15:30:05 -0800800
801 if (!result.ok()) {
David Rogers9fc78b82020-06-12 13:56:12 -0700802 ERR("Failed to write %u bytes at %#x. %u actually written",
803 unsigned(entry.size()),
804 unsigned(entry.address()),
805 unsigned(result.size()));
David Rogersc4dc8642020-09-14 10:52:36 -0700806 PW_TRY(MarkSectorCorruptIfNotOk(result.status(), &sector));
David Rogersa2562b52020-03-05 15:30:05 -0800807 }
808
809 if (options_.verify_on_write) {
David Rogersc4dc8642020-09-14 10:52:36 -0700810 PW_TRY(MarkSectorCorruptIfNotOk(entry.VerifyChecksumInFlash(), &sector));
David Rogersa2562b52020-03-05 15:30:05 -0800811 }
812
David Rogers98fea472020-04-01 15:43:48 -0700813 sector.RemoveWritableBytes(result.size());
Wyatt Heplerc84393f2020-03-20 11:23:24 -0700814 sector.AddValidBytes(result.size());
Wyatt Hepler1b3da3a2021-01-07 13:26:57 -0800815 return OkStatus();
David Rogersa2562b52020-03-05 15:30:05 -0800816}
817
David Rogers98fea472020-04-01 15:43:48 -0700818StatusWithSize KeyValueStore::CopyEntryToSector(Entry& entry,
819 SectorDescriptor* new_sector,
David Rogers31b358b2020-04-15 05:00:50 -0700820 Address new_address) {
David Rogers98fea472020-04-01 15:43:48 -0700821 const StatusWithSize result = entry.Copy(new_address);
822
David Rogersc4dc8642020-09-14 10:52:36 -0700823 PW_TRY_WITH_SIZE(MarkSectorCorruptIfNotOk(result.status(), new_sector));
David Rogers98fea472020-04-01 15:43:48 -0700824
825 if (options_.verify_on_write) {
David Rogers31b358b2020-04-15 05:00:50 -0700826 Entry new_entry;
David Rogersc4dc8642020-09-14 10:52:36 -0700827 PW_TRY_WITH_SIZE(MarkSectorCorruptIfNotOk(
David Rogers31b358b2020-04-15 05:00:50 -0700828 Entry::Read(partition_, new_address, formats_, &new_entry),
829 new_sector));
830 // TODO: add test that catches doing the verify on the old entry.
David Rogersc4dc8642020-09-14 10:52:36 -0700831 PW_TRY_WITH_SIZE(MarkSectorCorruptIfNotOk(new_entry.VerifyChecksumInFlash(),
832 new_sector));
David Rogers98fea472020-04-01 15:43:48 -0700833 }
834 // Entry was written successfully; update descriptor's address and the sector
835 // descriptors to reflect the new entry.
836 new_sector->RemoveWritableBytes(result.size());
837 new_sector->AddValidBytes(result.size());
838
839 return result;
840}
841
Wyatt Heplere2cbadf2020-06-22 11:21:45 -0700842Status KeyValueStore::RelocateEntry(
843 const EntryMetadata& metadata,
844 KeyValueStore::Address& address,
845 std::span<const Address> reserved_addresses) {
David Rogersa2562b52020-03-05 15:30:05 -0800846 Entry entry;
David Rogersc4dc8642020-09-14 10:52:36 -0700847 PW_TRY(ReadEntry(metadata, entry));
David Rogersa2562b52020-03-05 15:30:05 -0800848
849 // Find a new sector for the entry and write it to the new location. For
850 // relocation the find should not not be a sector already containing the key
851 // but can be the always empty sector, since this is part of the GC process
852 // that will result in a new empty sector. Also find a sector that does not
853 // have reclaimable space (mostly for the full GC, where that would result in
854 // an immediate extra relocation).
855 SectorDescriptor* new_sector;
856
David Rogersc4dc8642020-09-14 10:52:36 -0700857 PW_TRY(sectors_.FindSpaceDuringGarbageCollection(
Wyatt Heplerc84393f2020-03-20 11:23:24 -0700858 &new_sector, entry.size(), metadata.addresses(), reserved_addresses));
Wyatt Heplerab3b2492020-03-11 16:15:16 -0700859
David Rogers31b358b2020-04-15 05:00:50 -0700860 Address new_address = sectors_.NextWritableAddress(*new_sector);
David Rogersc4dc8642020-09-14 10:52:36 -0700861 PW_TRY_ASSIGN(const size_t result_size,
862 CopyEntryToSector(entry, new_sector, new_address));
David Rogers98fea472020-04-01 15:43:48 -0700863 sectors_.FromAddress(address).RemoveValidBytes(result_size);
Wyatt Heplerab3b2492020-03-11 16:15:16 -0700864 address = new_address;
David Rogersa2562b52020-03-05 15:30:05 -0800865
Wyatt Hepler1b3da3a2021-01-07 13:26:57 -0800866 return OkStatus();
David Rogersa2562b52020-03-05 15:30:05 -0800867}
868
David Rogers3c298372020-10-12 14:15:39 -0700869Status KeyValueStore::FullMaintenanceHelper(MaintenanceType maintenance_type) {
David Rogers9abe3c72020-03-24 19:03:13 -0700870 if (initialized_ == InitializationState::kNotInitialized) {
Wyatt Heplerd78f7c62020-09-28 14:27:32 -0700871 return Status::FailedPrecondition();
David Rogers9abe3c72020-03-24 19:03:13 -0700872 }
873
Armando Montanez17083bb2020-04-24 10:18:26 -0700874 // Full maintenance can be a potentially heavy operation, and should be
875 // relatively infrequent, so log start/end at INFO level.
876 INF("Beginning full maintenance");
David Rogers98fea472020-04-01 15:43:48 -0700877 CheckForErrors();
David Rogers9abe3c72020-03-24 19:03:13 -0700878
879 if (error_detected_) {
David Rogersc4dc8642020-09-14 10:52:36 -0700880 PW_TRY(Repair());
David Rogers9abe3c72020-03-24 19:03:13 -0700881 }
David Rogers35c3f842020-04-22 15:34:05 -0700882 StatusWithSize update_status = UpdateEntriesToPrimaryFormat();
883 Status overall_status = update_status.status();
884
David Rogers31b358b2020-04-15 05:00:50 -0700885 // Make sure all the entries are on the primary format.
Armando Montanez17083bb2020-04-24 10:18:26 -0700886 if (!overall_status.ok()) {
887 ERR("Failed to update all entries to the primary format");
888 }
David Rogers31b358b2020-04-15 05:00:50 -0700889
Wyatt Heplerc84393f2020-03-20 11:23:24 -0700890 SectorDescriptor* sector = sectors_.last_new();
David Rogerscd87c322020-02-27 14:04:08 -0800891
David Rogers35c3f842020-04-22 15:34:05 -0700892 // Calculate number of bytes for the threshold.
893 size_t threshold_bytes =
894 (partition_.size_bytes() * kGcUsageThresholdPercentage) / 100;
895
896 // Is bytes in use over the threshold.
897 StorageStats stats = GetStorageStats();
898 bool over_usage_threshold = stats.in_use_bytes > threshold_bytes;
David Rogers3c298372020-10-12 14:15:39 -0700899 bool heavy = (maintenance_type == MaintenanceType::kHeavy);
900 bool force_gc = heavy || over_usage_threshold || (update_status.size() > 0);
David Rogers35c3f842020-04-22 15:34:05 -0700901
David Rogerscd87c322020-02-27 14:04:08 -0800902 // TODO: look in to making an iterator method for cycling through sectors
903 // starting from last_new_sector_.
Armando Montanez17083bb2020-04-24 10:18:26 -0700904 Status gc_status;
David Rogerscd87c322020-02-27 14:04:08 -0800905 for (size_t j = 0; j < sectors_.size(); j++) {
906 sector += 1;
907 if (sector == sectors_.end()) {
908 sector = sectors_.begin();
909 }
910
David Rogers35c3f842020-04-22 15:34:05 -0700911 if (sector->RecoverableBytes(partition_.sector_size_bytes()) > 0 &&
912 (force_gc || sector->valid_bytes() == 0)) {
Armando Montanez17083bb2020-04-24 10:18:26 -0700913 gc_status = GarbageCollectSector(*sector, {});
914 if (!gc_status.ok()) {
915 ERR("Failed to garbage collect all sectors");
916 break;
917 }
David Rogerscd87c322020-02-27 14:04:08 -0800918 }
919 }
Armando Montanez17083bb2020-04-24 10:18:26 -0700920 if (overall_status.ok()) {
921 overall_status = gc_status;
922 }
David Rogerscd87c322020-02-27 14:04:08 -0800923
Armando Montanez17083bb2020-04-24 10:18:26 -0700924 if (overall_status.ok()) {
925 INF("Full maintenance complete");
926 } else {
927 ERR("Full maintenance finished with some errors");
928 }
929 return overall_status;
David Rogerscd87c322020-02-27 14:04:08 -0800930}
931
David Rogers0f8a1bb2020-04-21 18:50:19 -0700932Status KeyValueStore::PartialMaintenance() {
David Rogers9abe3c72020-03-24 19:03:13 -0700933 if (initialized_ == InitializationState::kNotInitialized) {
Wyatt Heplerd78f7c62020-09-28 14:27:32 -0700934 return Status::FailedPrecondition();
David Rogers9abe3c72020-03-24 19:03:13 -0700935 }
936
David Rogers0f8a1bb2020-04-21 18:50:19 -0700937 CheckForErrors();
David Rogersfcea3252020-04-07 14:56:35 -0700938 // Do automatic repair, if KVS options allow for it.
939 if (error_detected_ && options_.recovery != ErrorRecovery::kManual) {
David Rogersc4dc8642020-09-14 10:52:36 -0700940 PW_TRY(Repair());
David Rogersfcea3252020-04-07 14:56:35 -0700941 }
Wyatt Heplere2cbadf2020-06-22 11:21:45 -0700942 return GarbageCollect(std::span<const Address>());
David Rogers0f8a1bb2020-04-21 18:50:19 -0700943}
944
Wyatt Heplere2cbadf2020-06-22 11:21:45 -0700945Status KeyValueStore::GarbageCollect(
946 std::span<const Address> reserved_addresses) {
David Rogers0f8a1bb2020-04-21 18:50:19 -0700947 DBG("Garbage Collect a single sector");
Prashanth Swaminathanb6d5d7a2021-02-03 12:53:52 -0800948 for ([[maybe_unused]] Address address : reserved_addresses) {
David Rogers0f8a1bb2020-04-21 18:50:19 -0700949 DBG(" Avoid address %u", unsigned(address));
950 }
David Rogersfcea3252020-04-07 14:56:35 -0700951
David Rogersa12786b2020-01-31 16:02:33 -0800952 // Step 1: Find the sector to garbage collect
David Rogersc9d545e2020-03-11 17:47:43 -0700953 SectorDescriptor* sector_to_gc =
Wyatt Heplerc84393f2020-03-20 11:23:24 -0700954 sectors_.FindSectorToGarbageCollect(reserved_addresses);
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800955
David Rogersa12786b2020-01-31 16:02:33 -0800956 if (sector_to_gc == nullptr) {
David Rogersa2562b52020-03-05 15:30:05 -0800957 // Nothing to GC.
Wyatt Heplerd78f7c62020-09-28 14:27:32 -0700958 return Status::NotFound();
David Rogersa12786b2020-01-31 16:02:33 -0800959 }
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800960
David Rogersc9d545e2020-03-11 17:47:43 -0700961 // Step 2: Garbage collect the selected sector.
Wyatt Heplerc84393f2020-03-20 11:23:24 -0700962 return GarbageCollectSector(*sector_to_gc, reserved_addresses);
David Rogerscd87c322020-02-27 14:04:08 -0800963}
964
David Rogersf3884eb2020-03-08 19:21:40 -0700965Status KeyValueStore::RelocateKeyAddressesInSector(
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700966 SectorDescriptor& sector_to_gc,
David Rogersfcea3252020-04-07 14:56:35 -0700967 const EntryMetadata& metadata,
Wyatt Heplere2cbadf2020-06-22 11:21:45 -0700968 std::span<const Address> reserved_addresses) {
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700969 for (FlashPartition::Address& address : metadata.addresses()) {
Wyatt Heplerc84393f2020-03-20 11:23:24 -0700970 if (sectors_.AddressInSector(sector_to_gc, address)) {
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700971 DBG(" Relocate entry for Key 0x%08" PRIx32 ", sector %u",
972 metadata.hash(),
Wyatt Heplerc84393f2020-03-20 11:23:24 -0700973 sectors_.Index(sectors_.FromAddress(address)));
David Rogersc4dc8642020-09-14 10:52:36 -0700974 PW_TRY(RelocateEntry(metadata, address, reserved_addresses));
David Rogersf3884eb2020-03-08 19:21:40 -0700975 }
976 }
Wyatt Heplerab3b2492020-03-11 16:15:16 -0700977
Wyatt Hepler1b3da3a2021-01-07 13:26:57 -0800978 return OkStatus();
David Rogersf3884eb2020-03-08 19:21:40 -0700979};
980
Wyatt Heplerab3b2492020-03-11 16:15:16 -0700981Status KeyValueStore::GarbageCollectSector(
Wyatt Heplere2cbadf2020-06-22 11:21:45 -0700982 SectorDescriptor& sector_to_gc,
983 std::span<const Address> reserved_addresses) {
David Rogers9abe3c72020-03-24 19:03:13 -0700984 DBG(" Garbage Collect sector %u", sectors_.Index(sector_to_gc));
David Rogers3c298372020-10-12 14:15:39 -0700985
David Rogersf3884eb2020-03-08 19:21:40 -0700986 // Step 1: Move any valid entries in the GC sector to other sectors
Wyatt Heplerc84393f2020-03-20 11:23:24 -0700987 if (sector_to_gc.valid_bytes() != 0) {
David Rogers98fea472020-04-01 15:43:48 -0700988 for (EntryMetadata& metadata : entry_cache_) {
David Rogersc4dc8642020-09-14 10:52:36 -0700989 PW_TRY(RelocateKeyAddressesInSector(
Wyatt Heplerc84393f2020-03-20 11:23:24 -0700990 sector_to_gc, metadata, reserved_addresses));
David Rogersf3884eb2020-03-08 19:21:40 -0700991 }
992 }
993
Wyatt Heplerc84393f2020-03-20 11:23:24 -0700994 if (sector_to_gc.valid_bytes() != 0) {
David Rogers67f4b6c2020-02-06 16:17:09 -0800995 ERR(" Failed to relocate valid entries from sector being garbage "
David Rogers9fc78b82020-06-12 13:56:12 -0700996 "collected, %u valid bytes remain",
997 unsigned(sector_to_gc.valid_bytes()));
Wyatt Heplerd78f7c62020-09-28 14:27:32 -0700998 return Status::Internal();
Wyatt Heplerb7609542020-01-24 10:29:54 -0800999 }
1000
David Rogerscd87c322020-02-27 14:04:08 -08001001 // Step 2: Reinitialize the sector
David Rogers3c298372020-10-12 14:15:39 -07001002 if (!sector_to_gc.Empty(partition_.sector_size_bytes())) {
1003 sector_to_gc.mark_corrupt();
1004 internal_stats_.sector_erase_count++;
1005 PW_TRY(partition_.Erase(sectors_.BaseAddress(sector_to_gc), 1));
1006 sector_to_gc.set_writable_bytes(partition_.sector_size_bytes());
1007 }
Wyatt Heplerb7609542020-01-24 10:29:54 -08001008
Wyatt Heplerc84393f2020-03-20 11:23:24 -07001009 DBG(" Garbage Collect sector %u complete", sectors_.Index(sector_to_gc));
Wyatt Hepler1b3da3a2021-01-07 13:26:57 -08001010 return OkStatus();
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -08001011}
1012
David Rogers35c3f842020-04-22 15:34:05 -07001013StatusWithSize KeyValueStore::UpdateEntriesToPrimaryFormat() {
1014 size_t entries_updated = 0;
David Rogers31b358b2020-04-15 05:00:50 -07001015 for (EntryMetadata& prior_metadata : entry_cache_) {
1016 Entry entry;
David Rogersc4dc8642020-09-14 10:52:36 -07001017 PW_TRY_WITH_SIZE(ReadEntry(prior_metadata, entry));
David Rogers31b358b2020-04-15 05:00:50 -07001018 if (formats_.primary().magic == entry.magic()) {
1019 // Ignore entries that are already on the primary format.
1020 continue;
1021 }
1022
1023 DBG("Updating entry 0x%08x from old format [0x%08x] to new format "
1024 "[0x%08x]",
1025 unsigned(prior_metadata.hash()),
1026 unsigned(entry.magic()),
1027 unsigned(formats_.primary().magic));
1028
David Rogers35c3f842020-04-22 15:34:05 -07001029 entries_updated++;
1030
David Rogers31b358b2020-04-15 05:00:50 -07001031 last_transaction_id_ += 1;
David Rogersc4dc8642020-09-14 10:52:36 -07001032 PW_TRY_WITH_SIZE(entry.Update(formats_.primary(), last_transaction_id_));
David Rogers31b358b2020-04-15 05:00:50 -07001033
1034 // List of addresses for sectors with space for this entry.
1035 Address* reserved_addresses = entry_cache_.TempReservedAddressesForWrite();
1036
1037 // Find addresses to write the entry to. This may involve garbage collecting
1038 // one or more sectors.
David Rogersc4dc8642020-09-14 10:52:36 -07001039 PW_TRY_WITH_SIZE(GetAddressesForWrite(reserved_addresses, entry.size()));
David Rogers31b358b2020-04-15 05:00:50 -07001040
David Rogersc4dc8642020-09-14 10:52:36 -07001041 PW_TRY_WITH_SIZE(
David Rogers35c3f842020-04-22 15:34:05 -07001042 CopyEntryToSector(entry,
David Rogers31b358b2020-04-15 05:00:50 -07001043 &sectors_.FromAddress(reserved_addresses[0]),
1044 reserved_addresses[0]));
1045
1046 // After writing the first entry successfully, update the key descriptors.
1047 // Once a single new the entry is written, the old entries are invalidated.
1048 EntryMetadata new_metadata = UpdateKeyDescriptor(
1049 entry, reserved_addresses[0], &prior_metadata, entry.size());
1050
1051 // Write the additional copies of the entry, if redundancy is greater
1052 // than 1.
1053 for (size_t i = 1; i < redundancy(); ++i) {
David Rogersc4dc8642020-09-14 10:52:36 -07001054 PW_TRY_WITH_SIZE(
David Rogers35c3f842020-04-22 15:34:05 -07001055 CopyEntryToSector(entry,
David Rogers31b358b2020-04-15 05:00:50 -07001056 &sectors_.FromAddress(reserved_addresses[i]),
1057 reserved_addresses[i]));
1058 new_metadata.AddNewAddress(reserved_addresses[i]);
1059 }
1060 }
David Rogers35c3f842020-04-22 15:34:05 -07001061
1062 return StatusWithSize(entries_updated);
David Rogers31b358b2020-04-15 05:00:50 -07001063}
1064
David Rogers9abe3c72020-03-24 19:03:13 -07001065// Add any missing redundant entries/copies for a key.
1066Status KeyValueStore::AddRedundantEntries(EntryMetadata& metadata) {
David Rogers9abe3c72020-03-24 19:03:13 -07001067 Entry entry;
David Rogersc4dc8642020-09-14 10:52:36 -07001068 PW_TRY(ReadEntry(metadata, entry));
1069 PW_TRY(entry.VerifyChecksumInFlash());
David Rogers9abe3c72020-03-24 19:03:13 -07001070
David Rogers0f8a1bb2020-04-21 18:50:19 -07001071 while (metadata.addresses().size() < redundancy()) {
1072 SectorDescriptor* new_sector;
David Rogersc4dc8642020-09-14 10:52:36 -07001073 PW_TRY(GetSectorForWrite(&new_sector, entry.size(), metadata.addresses()));
David Rogers9abe3c72020-03-24 19:03:13 -07001074
David Rogers31b358b2020-04-15 05:00:50 -07001075 Address new_address = sectors_.NextWritableAddress(*new_sector);
David Rogersc4dc8642020-09-14 10:52:36 -07001076 PW_TRY(CopyEntryToSector(entry, new_sector, new_address));
David Rogers9abe3c72020-03-24 19:03:13 -07001077
1078 metadata.AddNewAddress(new_address);
1079 }
Wyatt Hepler1b3da3a2021-01-07 13:26:57 -08001080 return OkStatus();
David Rogers9abe3c72020-03-24 19:03:13 -07001081}
1082
1083Status KeyValueStore::RepairCorruptSectors() {
1084 // Try to GC each corrupt sector, even if previous sectors fail. If GC of a
1085 // sector failed on the first pass, then do a second pass, since a later
1086 // sector might have cleared up space or otherwise unblocked the earlier
1087 // failed sector.
Wyatt Hepler1b3da3a2021-01-07 13:26:57 -08001088 Status repair_status = OkStatus();
David Rogers9abe3c72020-03-24 19:03:13 -07001089
1090 size_t loop_count = 0;
1091 do {
1092 loop_count++;
1093 // Error of RESOURCE_EXHAUSTED indicates no space found for relocation.
1094 // Reset back to OK for the next pass.
Wyatt Heplerf276c6b2020-11-11 21:13:38 -08001095 if (repair_status.IsResourceExhausted()) {
Wyatt Hepler1b3da3a2021-01-07 13:26:57 -08001096 repair_status = OkStatus();
David Rogers9abe3c72020-03-24 19:03:13 -07001097 }
1098
1099 DBG(" Pass %u", unsigned(loop_count));
1100 for (SectorDescriptor& sector : sectors_) {
1101 if (sector.corrupt()) {
1102 DBG(" Found sector %u with corruption", sectors_.Index(sector));
1103 Status sector_status = GarbageCollectSector(sector, {});
1104 if (sector_status.ok()) {
David Rogers3c298372020-10-12 14:15:39 -07001105 internal_stats_.corrupt_sectors_recovered += 1;
Wyatt Heplerf276c6b2020-11-11 21:13:38 -08001106 } else if (repair_status.ok() || repair_status.IsResourceExhausted()) {
David Rogers9abe3c72020-03-24 19:03:13 -07001107 repair_status = sector_status;
1108 }
1109 }
1110 }
1111 DBG(" Pass %u complete", unsigned(loop_count));
1112 } while (!repair_status.ok() && loop_count < 2);
1113
1114 return repair_status;
1115}
1116
1117Status KeyValueStore::EnsureFreeSectorExists() {
Wyatt Hepler1b3da3a2021-01-07 13:26:57 -08001118 Status repair_status = OkStatus();
David Rogers9abe3c72020-03-24 19:03:13 -07001119 bool empty_sector_found = false;
1120
1121 DBG(" Find empty sector");
1122 for (SectorDescriptor& sector : sectors_) {
1123 if (sector.Empty(partition_.sector_size_bytes())) {
1124 empty_sector_found = true;
1125 DBG(" Empty sector found");
1126 break;
1127 }
1128 }
1129 if (empty_sector_found == false) {
1130 DBG(" No empty sector found, attempting to GC a free sector");
Wyatt Heplere2cbadf2020-06-22 11:21:45 -07001131 Status sector_status = GarbageCollect(std::span<const Address, 0>());
David Rogers9abe3c72020-03-24 19:03:13 -07001132 if (repair_status.ok() && !sector_status.ok()) {
1133 DBG(" Unable to free an empty sector");
1134 repair_status = sector_status;
1135 }
1136 }
1137
1138 return repair_status;
1139}
1140
1141Status KeyValueStore::EnsureEntryRedundancy() {
Wyatt Hepler1b3da3a2021-01-07 13:26:57 -08001142 Status repair_status = OkStatus();
David Rogers9abe3c72020-03-24 19:03:13 -07001143
1144 if (redundancy() == 1) {
David Rogers98fea472020-04-01 15:43:48 -07001145 DBG(" Redundancy not in use, nothting to check");
Wyatt Hepler1b3da3a2021-01-07 13:26:57 -08001146 return OkStatus();
David Rogers9abe3c72020-03-24 19:03:13 -07001147 }
1148
David Rogers98fea472020-04-01 15:43:48 -07001149 DBG(" Write any needed additional duplicate copies of keys to fulfill %u"
1150 " redundancy",
David Rogers9abe3c72020-03-24 19:03:13 -07001151 unsigned(redundancy()));
David Rogers98fea472020-04-01 15:43:48 -07001152 for (EntryMetadata& metadata : entry_cache_) {
David Rogers9abe3c72020-03-24 19:03:13 -07001153 if (metadata.addresses().size() >= redundancy()) {
1154 continue;
1155 }
1156
1157 DBG(" Key with %u of %u copies found, adding missing copies",
1158 unsigned(metadata.addresses().size()),
1159 unsigned(redundancy()));
David Rogers98fea472020-04-01 15:43:48 -07001160 Status fill_status = AddRedundantEntries(metadata);
David Rogers9abe3c72020-03-24 19:03:13 -07001161 if (fill_status.ok()) {
David Rogers3c298372020-10-12 14:15:39 -07001162 internal_stats_.missing_redundant_entries_recovered += 1;
David Rogers9abe3c72020-03-24 19:03:13 -07001163 DBG(" Key missing copies added");
1164 } else {
1165 DBG(" Failed to add key missing copies");
1166 if (repair_status.ok()) {
1167 repair_status = fill_status;
1168 }
1169 }
1170 }
1171
1172 return repair_status;
1173}
1174
David Rogersfcea3252020-04-07 14:56:35 -07001175Status KeyValueStore::FixErrors() {
1176 DBG("Fixing KVS errors");
David Rogers9abe3c72020-03-24 19:03:13 -07001177
1178 // Step 1: Garbage collect any sectors marked as corrupt.
David Rogersfcea3252020-04-07 14:56:35 -07001179 Status overall_status = RepairCorruptSectors();
David Rogers9abe3c72020-03-24 19:03:13 -07001180
1181 // Step 2: Make sure there is at least 1 empty sector. This needs to be a
1182 // seperate check of sectors from step 1, because a found empty sector might
1183 // get written to by a later GC that fails and does not result in a free
1184 // sector.
David Rogersfcea3252020-04-07 14:56:35 -07001185 Status repair_status = EnsureFreeSectorExists();
David Rogers9abe3c72020-03-24 19:03:13 -07001186 if (overall_status.ok()) {
1187 overall_status = repair_status;
1188 }
1189
1190 // Step 3: Make sure each stored key has the full number of redundant
1191 // entries.
1192 repair_status = EnsureEntryRedundancy();
1193 if (overall_status.ok()) {
1194 overall_status = repair_status;
1195 }
1196
1197 if (overall_status.ok()) {
1198 error_detected_ = false;
1199 initialized_ = InitializationState::kReady;
1200 }
1201 return overall_status;
1202}
1203
David Rogersfcea3252020-04-07 14:56:35 -07001204Status KeyValueStore::Repair() {
1205 // If errors have been detected, just reinit the KVS metadata. This does a
1206 // full deep error check and any needed repairs. Then repair any errors.
1207 INF("Starting KVS repair");
1208
1209 DBG("Reinitialize KVS metadata");
1210 InitializeMetadata();
1211
1212 return FixErrors();
1213}
1214
David Rogersd50eb1c2020-05-12 17:46:36 -07001215KeyValueStore::Entry KeyValueStore::CreateEntry(Address address,
Rob Olivere64daf42020-11-24 11:50:03 -05001216 Key key,
Wyatt Heplere2cbadf2020-06-22 11:21:45 -07001217 std::span<const byte> value,
Wyatt Hepler7ded6da2020-03-11 18:24:43 -07001218 EntryState state) {
Keir Mierle9e38b402020-02-21 13:06:21 -08001219 // Always bump the transaction ID when creating a new entry.
1220 //
1221 // Burning transaction IDs prevents inconsistencies between flash and memory
1222 // that which could happen if a write succeeds, but for some reason the read
1223 // and verify step fails. Here's how this would happen:
1224 //
1225 // 1. The entry is written but for some reason the flash reports failure OR
1226 // The write succeeds, but the read / verify operation fails.
1227 // 2. The transaction ID is NOT incremented, because of the failure
1228 // 3. (later) A new entry is written, re-using the transaction ID (oops)
1229 //
David Rogersd50eb1c2020-05-12 17:46:36 -07001230 // By always burning transaction IDs, the above problem can't happen.
1231 last_transaction_id_ += 1;
Keir Mierle9e38b402020-02-21 13:06:21 -08001232
Wyatt Hepler7ded6da2020-03-11 18:24:43 -07001233 if (state == EntryState::kDeleted) {
Wyatt Hepler7465be32020-02-21 15:30:53 -08001234 return Entry::Tombstone(
David Rogersd50eb1c2020-05-12 17:46:36 -07001235 partition_, address, formats_.primary(), key, last_transaction_id_);
Wyatt Hepler1fc11042020-02-19 17:17:51 -08001236 }
David Rogersd50eb1c2020-05-12 17:46:36 -07001237 return Entry::Valid(partition_,
1238 address,
1239 formats_.primary(),
1240 key,
1241 value,
1242 last_transaction_id_);
Wyatt Heplerd2298282020-02-20 17:12:45 -08001243}
1244
Wyatt Hepler7ded6da2020-03-11 18:24:43 -07001245void KeyValueStore::LogDebugInfo() const {
Keir Mierle8c352dc2020-02-02 13:58:19 -08001246 const size_t sector_size_bytes = partition_.sector_size_bytes();
1247 DBG("====================== KEY VALUE STORE DUMP =========================");
1248 DBG(" ");
1249 DBG("Flash partition:");
David Rogers9fc78b82020-06-12 13:56:12 -07001250 DBG(" Sector count = %u", unsigned(partition_.sector_count()));
1251 DBG(" Sector max count = %u", unsigned(sectors_.max_size()));
1252 DBG(" Sectors in use = %u", unsigned(sectors_.size()));
1253 DBG(" Sector size = %u", unsigned(sector_size_bytes));
1254 DBG(" Total size = %u", unsigned(partition_.size_bytes()));
1255 DBG(" Alignment = %u", unsigned(partition_.alignment_bytes()));
Keir Mierle8c352dc2020-02-02 13:58:19 -08001256 DBG(" ");
1257 DBG("Key descriptors:");
David Rogers9fc78b82020-06-12 13:56:12 -07001258 DBG(" Entry count = %u", unsigned(entry_cache_.total_entries()));
1259 DBG(" Max entry count = %u", unsigned(entry_cache_.max_entries()));
Keir Mierle8c352dc2020-02-02 13:58:19 -08001260 DBG(" ");
1261 DBG(" # hash version address address (hex)");
Armando Montanez888370d2020-05-01 18:29:22 -07001262 size_t count = 0;
Wyatt Hepler7ded6da2020-03-11 18:24:43 -07001263 for (const EntryMetadata& metadata : entry_cache_) {
Keir Mierle8c352dc2020-02-02 13:58:19 -08001264 DBG(" |%3zu: | %8zx |%8zu | %8zu | %8zx",
Armando Montanez888370d2020-05-01 18:29:22 -07001265 count++,
Wyatt Hepler7ded6da2020-03-11 18:24:43 -07001266 size_t(metadata.hash()),
1267 size_t(metadata.transaction_id()),
1268 size_t(metadata.first_address()),
1269 size_t(metadata.first_address()));
Keir Mierle8c352dc2020-02-02 13:58:19 -08001270 }
1271 DBG(" ");
1272
1273 DBG("Sector descriptors:");
1274 DBG(" # tail free valid has_space");
Wyatt Heplerc84393f2020-03-20 11:23:24 -07001275 for (const SectorDescriptor& sd : sectors_) {
1276 DBG(" |%3u: | %8zu |%8zu | %s",
1277 sectors_.Index(sd),
Wyatt Hepler2c7eca02020-02-18 16:01:42 -08001278 size_t(sd.writable_bytes()),
1279 sd.valid_bytes(),
1280 sd.writable_bytes() ? "YES" : "");
Keir Mierle8c352dc2020-02-02 13:58:19 -08001281 }
1282 DBG(" ");
1283
1284 // TODO: This should stop logging after some threshold.
1285 // size_t dumped_bytes = 0;
1286 DBG("Sector raw data:");
Wyatt Hepler1c329ca2020-02-07 18:07:23 -08001287 for (size_t sector_id = 0; sector_id < sectors_.size(); ++sector_id) {
Keir Mierle8c352dc2020-02-02 13:58:19 -08001288 // Read sector data. Yes, this will blow the stack on embedded.
Wyatt Hepler1c329ca2020-02-07 18:07:23 -08001289 std::array<byte, 500> raw_sector_data; // TODO!!!
Prashanth Swaminathanb6d5d7a2021-02-03 12:53:52 -08001290 [[maybe_unused]] StatusWithSize sws =
Keir Mierle8c352dc2020-02-02 13:58:19 -08001291 partition_.Read(sector_id * sector_size_bytes, raw_sector_data);
David Rogers9fc78b82020-06-12 13:56:12 -07001292 DBG("Read: %u bytes", unsigned(sws.size()));
Keir Mierle8c352dc2020-02-02 13:58:19 -08001293
1294 DBG(" base addr offs 0 1 2 3 4 5 6 7");
1295 for (size_t i = 0; i < sector_size_bytes; i += 8) {
1296 DBG(" %3zu %8zx %5zu | %02x %02x %02x %02x %02x %02x %02x %02x",
1297 sector_id,
1298 (sector_id * sector_size_bytes) + i,
1299 i,
1300 static_cast<unsigned int>(raw_sector_data[i + 0]),
1301 static_cast<unsigned int>(raw_sector_data[i + 1]),
1302 static_cast<unsigned int>(raw_sector_data[i + 2]),
1303 static_cast<unsigned int>(raw_sector_data[i + 3]),
1304 static_cast<unsigned int>(raw_sector_data[i + 4]),
1305 static_cast<unsigned int>(raw_sector_data[i + 5]),
1306 static_cast<unsigned int>(raw_sector_data[i + 6]),
1307 static_cast<unsigned int>(raw_sector_data[i + 7]));
1308
1309 // TODO: Fix exit condition.
1310 if (i > 128) {
1311 break;
1312 }
1313 }
1314 DBG(" ");
1315 }
1316
1317 DBG("////////////////////// KEY VALUE STORE DUMP END /////////////////////");
1318}
1319
David Rogerscf680ab2020-02-12 23:28:32 -08001320void KeyValueStore::LogSectors() const {
David Rogers9fc78b82020-06-12 13:56:12 -07001321 DBG("Sector descriptors: count %u", unsigned(sectors_.size()));
Wyatt Hepler1c329ca2020-02-07 18:07:23 -08001322 for (auto& sector : sectors_) {
David Rogers9fc78b82020-06-12 13:56:12 -07001323 DBG(" - Sector %u: valid %u, recoverable %u, free %u",
Wyatt Heplerc84393f2020-03-20 11:23:24 -07001324 sectors_.Index(sector),
David Rogers9fc78b82020-06-12 13:56:12 -07001325 unsigned(sector.valid_bytes()),
1326 unsigned(sector.RecoverableBytes(partition_.sector_size_bytes())),
1327 unsigned(sector.writable_bytes()));
David Rogers50185ad2020-02-07 00:02:46 -08001328 }
1329}
1330
David Rogerscf680ab2020-02-12 23:28:32 -08001331void KeyValueStore::LogKeyDescriptor() const {
David Rogers9fc78b82020-06-12 13:56:12 -07001332 DBG("Key descriptors: count %u", unsigned(entry_cache_.total_entries()));
David Rogers9abe3c72020-03-24 19:03:13 -07001333 for (const EntryMetadata& metadata : entry_cache_) {
David Rogers9fc78b82020-06-12 13:56:12 -07001334 DBG(" - Key: %s, hash %#x, transaction ID %u, first address %#x",
Wyatt Hepler02946272020-03-18 10:36:22 -07001335 metadata.state() == EntryState::kDeleted ? "Deleted" : "Valid",
David Rogers9fc78b82020-06-12 13:56:12 -07001336 unsigned(metadata.hash()),
1337 unsigned(metadata.transaction_id()),
1338 unsigned(metadata.first_address()));
David Rogerscf680ab2020-02-12 23:28:32 -08001339 }
1340}
1341
Wyatt Hepler2ad60672020-01-21 08:00:16 -08001342} // namespace pw::kvs