blob: 9823ae99168ffdc451a695c0976b87cb448bb6a6 [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
Keir Mierled28068e2020-08-14 16:41:44 -070017#define PW_LOG_USE_ULTRA_SHORT_NAMES 1
Armando Montanez28ecccb2020-05-04 15:35:54 -070018
Wyatt Heplerb7609542020-01-24 10:29:54 -080019#include "pw_kvs/key_value_store.h"
20
Wyatt Heplerbab0e202020-02-04 07:40:08 -080021#include <algorithm>
Wyatt Hepler5a33d8c2020-02-06 09:32:58 -080022#include <cinttypes>
Wyatt Heplerb7609542020-01-24 10:29:54 -080023#include <cstring>
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -080024#include <type_traits>
Wyatt Heplerb7609542020-01-24 10:29:54 -080025
David Rogersc0104462020-05-08 15:50:23 -070026#include "pw_assert/assert.h"
Wyatt Heplerae222dc2020-10-14 10:46:27 -070027#include "pw_kvs_private/config.h"
Keir Mierle8c352dc2020-02-02 13:58:19 -080028#include "pw_log/log.h"
David Rogersb6b14b82020-09-11 16:27:27 -070029#include "pw_status/try.h"
Wyatt Heplerb7609542020-01-24 10:29:54 -080030
Wyatt Hepler2ad60672020-01-21 08:00:16 -080031namespace pw::kvs {
Wyatt Heplera00d1ef2020-02-14 14:31:26 -080032namespace {
Wyatt Heplerb7609542020-01-24 10:29:54 -080033
Wyatt Hepleracaacf92020-01-24 10:58:30 -080034using std::byte;
35
Rob Olivere64daf42020-11-24 11:50:03 -050036constexpr bool InvalidKey(Key key) {
Wyatt Heplerbdd8e5a2020-02-20 19:27:26 -080037 return key.empty() || (key.size() > internal::Entry::kMaxKeyLength);
Wyatt Heplera00d1ef2020-02-14 14:31:26 -080038}
39
40} // namespace
41
Wyatt Heplerad0a7932020-02-06 08:20:38 -080042KeyValueStore::KeyValueStore(FlashPartition* partition,
Wyatt Heplere2cbadf2020-06-22 11:21:45 -070043 std::span<const EntryFormat> formats,
Wyatt Hepler7ded6da2020-03-11 18:24:43 -070044 const Options& options,
45 size_t redundancy,
46 Vector<SectorDescriptor>& sector_descriptor_list,
47 const SectorDescriptor** temp_sectors_to_skip,
48 Vector<KeyDescriptor>& key_descriptor_list,
49 Address* addresses)
Wyatt Heplerad0a7932020-02-06 08:20:38 -080050 : partition_(*partition),
Wyatt Hepler22d0d9f2020-03-05 14:57:11 -080051 formats_(formats),
Wyatt Heplerc84393f2020-03-20 11:23:24 -070052 sectors_(sector_descriptor_list, *partition, temp_sectors_to_skip),
Wyatt Hepler7ded6da2020-03-11 18:24:43 -070053 entry_cache_(key_descriptor_list, addresses, redundancy),
David Rogers49766d92020-03-20 10:55:54 -070054 options_(options),
David Rogers9abe3c72020-03-24 19:03:13 -070055 initialized_(InitializationState::kNotInitialized),
David Rogers49766d92020-03-20 10:55:54 -070056 error_detected_(false),
David Rogers3c298372020-10-12 14:15:39 -070057 internal_stats_({}),
David Rogers49766d92020-03-20 10:55:54 -070058 last_transaction_id_(0) {}
Wyatt Heplerad0a7932020-02-06 08:20:38 -080059
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -080060Status KeyValueStore::Init() {
David Rogers9abe3c72020-03-24 19:03:13 -070061 initialized_ = InitializationState::kNotInitialized;
David Rogers49766d92020-03-20 10:55:54 -070062 error_detected_ = false;
Keir Mierlebf904812020-03-11 17:28:22 -070063 last_transaction_id_ = 0;
Wyatt Heplerd2298282020-02-20 17:12:45 -080064
David Rogers2e9e0c82020-02-13 15:06:06 -080065 INF("Initializing key value store");
Wyatt Hepler38ce30f2020-02-19 11:48:31 -080066 if (partition_.sector_count() > sectors_.max_size()) {
David Rogers9fc78b82020-06-12 13:56:12 -070067 ERR("KVS init failed: kMaxUsableSectors (=%u) must be at least as "
68 "large as the number of sectors in the flash partition (=%u)",
69 unsigned(sectors_.max_size()),
70 unsigned(partition_.sector_count()));
Wyatt Heplerd78f7c62020-09-28 14:27:32 -070071 return Status::FailedPrecondition();
Wyatt Heplerad0a7932020-02-06 08:20:38 -080072 }
73
David Rogers178002a2020-06-16 13:52:54 -070074 if (partition_.sector_count() < 2) {
75 ERR("KVS init failed: FlashParition sector count (=%u) must be at 2. KVS "
76 "requires at least 1 working sector + 1 free/reserved sector",
77 unsigned(partition_.sector_count()));
Wyatt Heplerd78f7c62020-09-28 14:27:32 -070078 return Status::FailedPrecondition();
David Rogers178002a2020-06-16 13:52:54 -070079 }
80
Keir Mierle8c352dc2020-02-02 13:58:19 -080081 const size_t sector_size_bytes = partition_.sector_size_bytes();
Keir Mierle8c352dc2020-02-02 13:58:19 -080082
David Rogers49766d92020-03-20 10:55:54 -070083 // TODO: investigate doing this as a static assert/compile-time check.
84 if (sector_size_bytes > SectorDescriptor::max_sector_size()) {
David Rogers9fc78b82020-06-12 13:56:12 -070085 ERR("KVS init failed: sector_size_bytes (=%u) is greater than maximum "
86 "allowed sector size (=%u)",
87 unsigned(sector_size_bytes),
88 unsigned(SectorDescriptor::max_sector_size()));
Wyatt Heplerd78f7c62020-09-28 14:27:32 -070089 return Status::FailedPrecondition();
David Rogers49766d92020-03-20 10:55:54 -070090 }
91
David Rogerscd134352020-04-17 19:37:15 -070092 Status metadata_result = InitializeMetadata();
David Rogersfcea3252020-04-07 14:56:35 -070093
94 if (!error_detected_) {
95 initialized_ = InitializationState::kReady;
96 } else {
David Rogers0f8a1bb2020-04-21 18:50:19 -070097 initialized_ = InitializationState::kNeedsMaintenance;
98
David Rogersfcea3252020-04-07 14:56:35 -070099 if (options_.recovery != ErrorRecovery::kManual) {
Armando Montanezf8419ae2020-04-21 10:03:05 -0700100 size_t pre_fix_redundancy_errors =
David Rogers3c298372020-10-12 14:15:39 -0700101 internal_stats_.missing_redundant_entries_recovered;
David Rogersfcea3252020-04-07 14:56:35 -0700102 Status recovery_status = FixErrors();
103
104 if (recovery_status.ok()) {
Wyatt Heplerf276c6b2020-11-11 21:13:38 -0800105 if (metadata_result.IsOutOfRange()) {
David Rogers3c298372020-10-12 14:15:39 -0700106 internal_stats_.missing_redundant_entries_recovered =
Armando Montanezf8419ae2020-04-21 10:03:05 -0700107 pre_fix_redundancy_errors;
David Rogerscd134352020-04-17 19:37:15 -0700108 INF("KVS init: Redundancy level successfully updated");
109 } else {
110 WRN("KVS init: Corruption detected and fully repaired");
111 }
David Rogersfcea3252020-04-07 14:56:35 -0700112 initialized_ = InitializationState::kReady;
Wyatt Heplerf276c6b2020-11-11 21:13:38 -0800113 } else if (recovery_status.IsResourceExhausted()) {
David Rogersfcea3252020-04-07 14:56:35 -0700114 WRN("KVS init: Unable to maintain required free sector");
David Rogersfcea3252020-04-07 14:56:35 -0700115 } else {
116 WRN("KVS init: Corruption detected and unable repair");
David Rogersfcea3252020-04-07 14:56:35 -0700117 }
118 } else {
119 WRN("KVS init: Corruption detected, no repair attempted due to options");
David Rogersfcea3252020-04-07 14:56:35 -0700120 }
121 }
122
David Rogers9fc78b82020-06-12 13:56:12 -0700123 INF("KeyValueStore init complete: active keys %u, deleted keys %u, sectors "
124 "%u, logical sector size %u bytes",
125 unsigned(size()),
126 unsigned(entry_cache_.total_entries() - size()),
127 unsigned(sectors_.size()),
128 unsigned(partition_.sector_size_bytes()));
David Rogersfcea3252020-04-07 14:56:35 -0700129
130 // Report any corruption was not repaired.
131 if (error_detected_) {
132 WRN("KVS init: Corruption found but not repaired, KVS unavailable until "
133 "successful maintenance.");
Wyatt Heplerd78f7c62020-09-28 14:27:32 -0700134 return Status::DataLoss();
David Rogersfcea3252020-04-07 14:56:35 -0700135 }
136
Wyatt Hepler1b3da3a2021-01-07 13:26:57 -0800137 return OkStatus();
David Rogersfcea3252020-04-07 14:56:35 -0700138}
139
David Rogerscd134352020-04-17 19:37:15 -0700140Status KeyValueStore::InitializeMetadata() {
David Rogersfcea3252020-04-07 14:56:35 -0700141 const size_t sector_size_bytes = partition_.sector_size_bytes();
142
143 sectors_.Reset();
144 entry_cache_.Reset();
145
Keir Mierle8c352dc2020-02-02 13:58:19 -0800146 DBG("First pass: Read all entries from all sectors");
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800147 Address sector_address = 0;
Keir Mierle8c352dc2020-02-02 13:58:19 -0800148
Alexei Frolovd4adf912020-02-21 13:29:15 -0800149 size_t total_corrupt_bytes = 0;
David Rogerscd134352020-04-17 19:37:15 -0700150 size_t corrupt_entries = 0;
David Rogers91627482020-02-27 17:38:12 -0800151 bool empty_sector_found = false;
David Rogerscd134352020-04-17 19:37:15 -0700152 size_t entry_copies_missing = 0;
Alexei Frolovd4adf912020-02-21 13:29:15 -0800153
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800154 for (SectorDescriptor& sector : sectors_) {
Keir Mierle8c352dc2020-02-02 13:58:19 -0800155 Address entry_address = sector_address;
156
Alexei Frolovd4adf912020-02-21 13:29:15 -0800157 size_t sector_corrupt_bytes = 0;
158
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800159 for (int num_entries_in_sector = 0; true; num_entries_in_sector++) {
David Rogersfcea3252020-04-07 14:56:35 -0700160 DBG("Load entry: sector=%u, entry#=%d, address=%u",
161 unsigned(sector_address),
Keir Mierle8c352dc2020-02-02 13:58:19 -0800162 num_entries_in_sector,
David Rogersfcea3252020-04-07 14:56:35 -0700163 unsigned(entry_address));
Keir Mierle8c352dc2020-02-02 13:58:19 -0800164
Wyatt Heplerc84393f2020-03-20 11:23:24 -0700165 if (!sectors_.AddressInSector(sector, entry_address)) {
Keir Mierle8c352dc2020-02-02 13:58:19 -0800166 DBG("Fell off end of sector; moving to the next sector");
167 break;
168 }
169
170 Address next_entry_address;
171 Status status = LoadEntry(entry_address, &next_entry_address);
Wyatt Heplerf276c6b2020-11-11 21:13:38 -0800172 if (status.IsNotFound()) {
Keir Mierle8c352dc2020-02-02 13:58:19 -0800173 DBG("Hit un-written data in sector; moving to the next sector");
174 break;
David Rogersfcea3252020-04-07 14:56:35 -0700175 } else if (!status.ok()) {
176 // The entry could not be read, indicating likely data corruption within
177 // the sector. Try to scan the remainder of the sector for other
178 // entries.
Alexei Frolovd4adf912020-02-21 13:29:15 -0800179
David Rogers49766d92020-03-20 10:55:54 -0700180 error_detected_ = true;
Alexei Frolovd4adf912020-02-21 13:29:15 -0800181 corrupt_entries++;
182
183 status = ScanForEntry(sector,
184 entry_address + Entry::kMinAlignmentBytes,
185 &next_entry_address);
David Rogersfcea3252020-04-07 14:56:35 -0700186 if (!status.ok()) {
Alexei Frolovd4adf912020-02-21 13:29:15 -0800187 // No further entries in this sector. Mark the remaining bytes in the
188 // sector as corrupt (since we can't reliably know the size of the
189 // corrupt entry).
190 sector_corrupt_bytes +=
191 sector_size_bytes - (entry_address - sector_address);
192 break;
193 }
194
Alexei Frolovd4adf912020-02-21 13:29:15 -0800195 sector_corrupt_bytes += next_entry_address - entry_address;
Keir Mierle8c352dc2020-02-02 13:58:19 -0800196 }
Keir Mierle8c352dc2020-02-02 13:58:19 -0800197
198 // Entry loaded successfully; so get ready to load the next one.
199 entry_address = next_entry_address;
200
201 // Update of the number of writable bytes in this sector.
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800202 sector.set_writable_bytes(sector_size_bytes -
203 (entry_address - sector_address));
Keir Mierle8c352dc2020-02-02 13:58:19 -0800204 }
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800205
Alexei Frolovd4adf912020-02-21 13:29:15 -0800206 if (sector_corrupt_bytes > 0) {
207 // If the sector contains corrupt data, prevent any further entries from
208 // being written to it by indicating that it has no space. This should
209 // also make it a decent GC candidate. Valid keys in the sector are still
210 // readable as normal.
David Rogers49766d92020-03-20 10:55:54 -0700211 sector.mark_corrupt();
212 error_detected_ = true;
Alexei Frolovd4adf912020-02-21 13:29:15 -0800213
David Rogers9fc78b82020-06-12 13:56:12 -0700214 WRN("Sector %u contains %uB of corrupt data",
Wyatt Heplerc84393f2020-03-20 11:23:24 -0700215 sectors_.Index(sector),
David Rogers9fc78b82020-06-12 13:56:12 -0700216 unsigned(sector_corrupt_bytes));
Alexei Frolovd4adf912020-02-21 13:29:15 -0800217 }
218
David Rogers91627482020-02-27 17:38:12 -0800219 if (sector.Empty(sector_size_bytes)) {
220 empty_sector_found = true;
221 }
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800222 sector_address += sector_size_bytes;
Alexei Frolovd4adf912020-02-21 13:29:15 -0800223 total_corrupt_bytes += sector_corrupt_bytes;
Keir Mierle8c352dc2020-02-02 13:58:19 -0800224 }
225
226 DBG("Second pass: Count valid bytes in each sector");
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700227 Address newest_key = 0;
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800228
David Rogers98fea472020-04-01 15:43:48 -0700229 // For every valid entry, for each address, count the valid bytes in that
230 // sector. If the address fails to read, remove the address and mark the
231 // sector as corrupt. Track which entry has the newest transaction ID for
232 // initializing last_new_sector_.
233 for (EntryMetadata& metadata : entry_cache_) {
David Rogers49766d92020-03-20 10:55:54 -0700234 if (metadata.addresses().size() < redundancy()) {
David Rogers31b358b2020-04-15 05:00:50 -0700235 DBG("Key 0x%08x missing copies, has %u, needs %u",
236 unsigned(metadata.hash()),
237 unsigned(metadata.addresses().size()),
238 unsigned(redundancy()));
David Rogerscd134352020-04-17 19:37:15 -0700239 entry_copies_missing++;
David Rogers49766d92020-03-20 10:55:54 -0700240 }
David Rogers98fea472020-04-01 15:43:48 -0700241 size_t index = 0;
242 while (index < metadata.addresses().size()) {
243 Address address = metadata.addresses()[index];
David Rogersf56131c2020-03-04 10:19:22 -0800244 Entry entry;
David Rogers98fea472020-04-01 15:43:48 -0700245
246 Status read_result = Entry::Read(partition_, address, formats_, &entry);
247
248 SectorDescriptor& sector = sectors_.FromAddress(address);
249
250 if (read_result.ok()) {
251 sector.AddValidBytes(entry.size());
252 index++;
253 } else {
254 corrupt_entries++;
255 total_corrupt_bytes += sector.writable_bytes();
256 error_detected_ = true;
257 sector.mark_corrupt();
258
259 // Remove the bad address and stay at this index. The removal
260 // replaces out the removed address with the back address so
261 // this index needs to be rechecked with the new address.
262 metadata.RemoveAddress(address);
263 }
David Rogersf56131c2020-03-04 10:19:22 -0800264 }
David Rogers98fea472020-04-01 15:43:48 -0700265
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700266 if (metadata.IsNewerThan(last_transaction_id_)) {
267 last_transaction_id_ = metadata.transaction_id();
268 newest_key = metadata.addresses().back();
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800269 }
Keir Mierle8c352dc2020-02-02 13:58:19 -0800270 }
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800271
Wyatt Heplerc84393f2020-03-20 11:23:24 -0700272 sectors_.set_last_new_sector(newest_key);
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800273
David Rogers91627482020-02-27 17:38:12 -0800274 if (!empty_sector_found) {
David Rogers31b358b2020-04-15 05:00:50 -0700275 DBG("No empty sector found");
David Rogers9abe3c72020-03-24 19:03:13 -0700276 error_detected_ = true;
David Rogers91627482020-02-27 17:38:12 -0800277 }
278
David Rogerscd134352020-04-17 19:37:15 -0700279 if (entry_copies_missing > 0) {
280 bool other_errors = error_detected_;
281 error_detected_ = true;
282
Armando Montanez344814b2020-04-24 15:05:42 -0700283 if (!other_errors && entry_copies_missing == entry_cache_.total_entries()) {
David Rogers9fc78b82020-06-12 13:56:12 -0700284 INF("KVS configuration changed to redundancy of %u total copies per key",
285 unsigned(redundancy()));
Wyatt Heplerd78f7c62020-09-28 14:27:32 -0700286 return Status::OutOfRange();
David Rogerscd134352020-04-17 19:37:15 -0700287 }
David Rogers9abe3c72020-03-24 19:03:13 -0700288 }
David Rogerscd134352020-04-17 19:37:15 -0700289
290 if (error_detected_) {
David Rogers9fc78b82020-06-12 13:56:12 -0700291 WRN("Corruption detected. Found %u corrupt bytes, %u corrupt entries, "
292 "and %u keys missing redundant copies.",
293 unsigned(total_corrupt_bytes),
294 unsigned(corrupt_entries),
295 unsigned(entry_copies_missing));
Wyatt Heplerd78f7c62020-09-28 14:27:32 -0700296 return Status::FailedPrecondition();
David Rogerscd134352020-04-17 19:37:15 -0700297 }
Wyatt Hepler1b3da3a2021-01-07 13:26:57 -0800298 return OkStatus();
Keir Mierle8c352dc2020-02-02 13:58:19 -0800299}
300
Alexei Frolov9e235832020-02-24 12:44:45 -0800301KeyValueStore::StorageStats KeyValueStore::GetStorageStats() const {
David Rogers9abe3c72020-03-24 19:03:13 -0700302 StorageStats stats{};
Alexei Frolov9e235832020-02-24 12:44:45 -0800303 const size_t sector_size = partition_.sector_size_bytes();
304 bool found_empty_sector = false;
David Rogers3c298372020-10-12 14:15:39 -0700305 stats.sector_erase_count = internal_stats_.sector_erase_count;
306 stats.corrupt_sectors_recovered = internal_stats_.corrupt_sectors_recovered;
David Rogers9abe3c72020-03-24 19:03:13 -0700307 stats.missing_redundant_entries_recovered =
David Rogers3c298372020-10-12 14:15:39 -0700308 internal_stats_.missing_redundant_entries_recovered;
Alexei Frolov9e235832020-02-24 12:44:45 -0800309
310 for (const SectorDescriptor& sector : sectors_) {
311 stats.in_use_bytes += sector.valid_bytes();
312 stats.reclaimable_bytes += sector.RecoverableBytes(sector_size);
313
314 if (!found_empty_sector && sector.Empty(sector_size)) {
315 // The KVS tries to always keep an empty sector for GC, so don't count
316 // the first empty sector seen as writable space. However, a free sector
317 // cannot always be assumed to exist; if a GC operation fails, all sectors
318 // may be partially written, in which case the space reported might be
319 // inaccurate.
320 found_empty_sector = true;
321 continue;
322 }
323
324 stats.writable_bytes += sector.writable_bytes();
325 }
326
327 return stats;
328}
329
David Rogers98fea472020-04-01 15:43:48 -0700330// Check KVS for any error conditions. Primarily intended for test and
331// internal use.
David Rogers9abe3c72020-03-24 19:03:13 -0700332bool KeyValueStore::CheckForErrors() {
333 // Check for corrupted sectors
334 for (SectorDescriptor& sector : sectors_) {
335 if (sector.corrupt()) {
336 error_detected_ = true;
David Rogers98fea472020-04-01 15:43:48 -0700337 return error_detected();
David Rogers9abe3c72020-03-24 19:03:13 -0700338 }
339 }
340
341 // Check for missing redundancy.
342 if (redundancy() > 1) {
343 for (const EntryMetadata& metadata : entry_cache_) {
344 if (metadata.addresses().size() < redundancy()) {
345 error_detected_ = true;
David Rogers98fea472020-04-01 15:43:48 -0700346 return error_detected();
David Rogers9abe3c72020-03-24 19:03:13 -0700347 }
348 }
349 }
350
351 return error_detected();
352}
353
Keir Mierle8c352dc2020-02-02 13:58:19 -0800354Status KeyValueStore::LoadEntry(Address entry_address,
355 Address* next_entry_address) {
Wyatt Heplere541e072020-02-14 09:10:53 -0800356 Entry entry;
David Rogersc4dc8642020-09-14 10:52:36 -0700357 PW_TRY(Entry::Read(partition_, entry_address, formats_, &entry));
Keir Mierle8c352dc2020-02-02 13:58:19 -0800358
359 // Read the key from flash & validate the entry (which reads the value).
Wyatt Heplera00d1ef2020-02-14 14:31:26 -0800360 Entry::KeyBuffer key_buffer;
David Rogersc4dc8642020-09-14 10:52:36 -0700361 PW_TRY_ASSIGN(size_t key_length, entry.ReadKey(key_buffer));
Rob Olivere64daf42020-11-24 11:50:03 -0500362 const Key key(key_buffer.data(), key_length);
Wyatt Heplerbab0e202020-02-04 07:40:08 -0800363
David Rogersc4dc8642020-09-14 10:52:36 -0700364 PW_TRY(entry.VerifyChecksumInFlash());
David Rogersf56131c2020-03-04 10:19:22 -0800365
366 // A valid entry was found, so update the next entry address before doing any
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700367 // of the checks that happen in AddNewOrUpdateExisting.
David Rogersf56131c2020-03-04 10:19:22 -0800368 *next_entry_address = entry.next_address();
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700369 return entry_cache_.AddNewOrUpdateExisting(
370 entry.descriptor(key), entry.address(), partition_.sector_size_bytes());
Keir Mierle8c352dc2020-02-02 13:58:19 -0800371}
372
Alexei Frolovd4adf912020-02-21 13:29:15 -0800373// Scans flash memory within a sector to find a KVS entry magic.
Alexei Frolovd4adf912020-02-21 13:29:15 -0800374Status KeyValueStore::ScanForEntry(const SectorDescriptor& sector,
375 Address start_address,
376 Address* next_entry_address) {
David Rogersfcea3252020-04-07 14:56:35 -0700377 DBG("Scanning sector %u for entries starting from address %u",
Wyatt Heplerc84393f2020-03-20 11:23:24 -0700378 sectors_.Index(sector),
David Rogersfcea3252020-04-07 14:56:35 -0700379 unsigned(start_address));
Alexei Frolovd4adf912020-02-21 13:29:15 -0800380
381 // Entries must start at addresses which are aligned on a multiple of
382 // Entry::kMinAlignmentBytes. However, that multiple can vary between entries.
383 // When scanning, we don't have an entry to tell us what the current alignment
384 // is, so the minimum alignment is used to be exhaustive.
385 for (Address address = AlignUp(start_address, Entry::kMinAlignmentBytes);
Wyatt Heplerc84393f2020-03-20 11:23:24 -0700386 sectors_.AddressInSector(sector, address);
Alexei Frolovd4adf912020-02-21 13:29:15 -0800387 address += Entry::kMinAlignmentBytes) {
Alexei Frolovd4adf912020-02-21 13:29:15 -0800388 uint32_t magic;
David Rogersfcea3252020-04-07 14:56:35 -0700389 StatusWithSize read_result =
Wyatt Heplere2cbadf2020-06-22 11:21:45 -0700390 partition_.Read(address, std::as_writable_bytes(std::span(&magic, 1)));
David Rogersfcea3252020-04-07 14:56:35 -0700391 if (!read_result.ok()) {
392 continue;
393 }
Wyatt Hepler22d0d9f2020-03-05 14:57:11 -0800394 if (formats_.KnownMagic(magic)) {
David Rogersfcea3252020-04-07 14:56:35 -0700395 DBG("Found entry magic at address %u", unsigned(address));
Alexei Frolovd4adf912020-02-21 13:29:15 -0800396 *next_entry_address = address;
Wyatt Hepler1b3da3a2021-01-07 13:26:57 -0800397 return OkStatus();
Alexei Frolovd4adf912020-02-21 13:29:15 -0800398 }
399 }
400
Wyatt Heplerd78f7c62020-09-28 14:27:32 -0700401 return Status::NotFound();
Alexei Frolovd4adf912020-02-21 13:29:15 -0800402}
403
Rob Olivere64daf42020-11-24 11:50:03 -0500404StatusWithSize KeyValueStore::Get(Key key,
Wyatt Heplere2cbadf2020-06-22 11:21:45 -0700405 std::span<byte> value_buffer,
Wyatt Hepler5f6efc02020-02-18 16:54:31 -0800406 size_t offset_bytes) const {
David Rogersc4dc8642020-09-14 10:52:36 -0700407 PW_TRY_WITH_SIZE(CheckReadOperation(key));
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800408
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700409 EntryMetadata metadata;
David Rogersc4dc8642020-09-14 10:52:36 -0700410 PW_TRY_WITH_SIZE(FindExisting(key, &metadata));
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800411
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700412 return Get(key, metadata, value_buffer, offset_bytes);
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800413}
414
Rob Olivere64daf42020-11-24 11:50:03 -0500415Status KeyValueStore::PutBytes(Key key, std::span<const byte> value) {
David Rogersc4dc8642020-09-14 10:52:36 -0700416 PW_TRY(CheckWriteOperation(key));
David Rogers9fc78b82020-06-12 13:56:12 -0700417 DBG("Writing key/value; key length=%u, value length=%u",
418 unsigned(key.size()),
419 unsigned(value.size()));
Wyatt Hepler729f28c2020-02-05 09:46:00 -0800420
Wyatt Hepler5406a672020-02-18 15:42:38 -0800421 if (Entry::size(partition_, key, value) > partition_.sector_size_bytes()) {
David Rogers9fc78b82020-06-12 13:56:12 -0700422 DBG("%u B value with %u B key cannot fit in one sector",
423 unsigned(value.size()),
424 unsigned(key.size()));
Wyatt Heplerd78f7c62020-09-28 14:27:32 -0700425 return Status::InvalidArgument();
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800426 }
427
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700428 EntryMetadata metadata;
David Rogers98fea472020-04-01 15:43:48 -0700429 Status status = FindEntry(key, &metadata);
Wyatt Hepler2d401692020-02-13 16:01:23 -0800430
431 if (status.ok()) {
David Rogersf56131c2020-03-04 10:19:22 -0800432 // TODO: figure out logging how to support multiple addresses.
David Rogers9fc78b82020-06-12 13:56:12 -0700433 DBG("Overwriting entry for key 0x%08x in %u sectors including %u",
434 unsigned(metadata.hash()),
435 unsigned(metadata.addresses().size()),
Wyatt Heplerc84393f2020-03-20 11:23:24 -0700436 sectors_.Index(metadata.first_address()));
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700437 return WriteEntryForExistingKey(metadata, EntryState::kValid, key, value);
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800438 }
David Rogers2761aeb2020-01-31 17:09:00 -0800439
Wyatt Heplerf276c6b2020-11-11 21:13:38 -0800440 if (status.IsNotFound()) {
Wyatt Hepler2d401692020-02-13 16:01:23 -0800441 return WriteEntryForNewKey(key, value);
442 }
443
444 return status;
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800445}
446
Rob Olivere64daf42020-11-24 11:50:03 -0500447Status KeyValueStore::Delete(Key key) {
David Rogersc4dc8642020-09-14 10:52:36 -0700448 PW_TRY(CheckWriteOperation(key));
Wyatt Hepler729f28c2020-02-05 09:46:00 -0800449
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700450 EntryMetadata metadata;
David Rogersc4dc8642020-09-14 10:52:36 -0700451 PW_TRY(FindExisting(key, &metadata));
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800452
David Rogersf56131c2020-03-04 10:19:22 -0800453 // TODO: figure out logging how to support multiple addresses.
David Rogers9fc78b82020-06-12 13:56:12 -0700454 DBG("Writing tombstone for key 0x%08x in %u sectors including %u",
455 unsigned(metadata.hash()),
456 unsigned(metadata.addresses().size()),
Wyatt Heplerc84393f2020-03-20 11:23:24 -0700457 sectors_.Index(metadata.first_address()));
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700458 return WriteEntryForExistingKey(metadata, EntryState::kDeleted, key, {});
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800459}
460
Wyatt Hepler08d37d82020-02-27 15:45:37 -0800461void KeyValueStore::Item::ReadKey() {
462 key_buffer_.fill('\0');
463
464 Entry entry;
David Rogers98fea472020-04-01 15:43:48 -0700465 if (kvs_.ReadEntry(*iterator_, entry).ok()) {
Wyatt Hepler08d37d82020-02-27 15:45:37 -0800466 entry.ReadKey(key_buffer_);
467 }
468}
469
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800470KeyValueStore::iterator& KeyValueStore::iterator::operator++() {
471 // Skip to the next entry that is valid (not deleted).
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700472 while (++item_.iterator_ != item_.kvs_.entry_cache_.end() &&
Wyatt Hepler02946272020-03-18 10:36:22 -0700473 item_.iterator_->state() != EntryState::kValid) {
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800474 }
475 return *this;
476}
477
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800478KeyValueStore::iterator KeyValueStore::begin() const {
Wyatt Heplerbfc6a522020-04-01 16:30:24 -0700479 internal::EntryCache::const_iterator cache_iterator = entry_cache_.begin();
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800480 // Skip over any deleted entries at the start of the descriptor list.
Wyatt Hepler02946272020-03-18 10:36:22 -0700481 while (cache_iterator != entry_cache_.end() &&
482 cache_iterator->state() != EntryState::kValid) {
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700483 ++cache_iterator;
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800484 }
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700485 return iterator(*this, cache_iterator);
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800486}
487
Rob Olivere64daf42020-11-24 11:50:03 -0500488StatusWithSize KeyValueStore::ValueSize(Key key) const {
David Rogersc4dc8642020-09-14 10:52:36 -0700489 PW_TRY_WITH_SIZE(CheckReadOperation(key));
Wyatt Heplered163b02020-02-03 17:49:32 -0800490
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700491 EntryMetadata metadata;
David Rogersc4dc8642020-09-14 10:52:36 -0700492 PW_TRY_WITH_SIZE(FindExisting(key, &metadata));
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800493
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700494 return ValueSize(metadata);
Wyatt Heplerfac81132020-02-27 17:26:33 -0800495}
Wyatt Heplered163b02020-02-03 17:49:32 -0800496
David Rogers98fea472020-04-01 15:43:48 -0700497Status KeyValueStore::ReadEntry(const EntryMetadata& metadata,
498 Entry& entry) const {
499 // Try to read an entry
Wyatt Heplerd78f7c62020-09-28 14:27:32 -0700500 Status read_result = Status::DataLoss();
David Rogers98fea472020-04-01 15:43:48 -0700501 for (Address address : metadata.addresses()) {
502 read_result = Entry::Read(partition_, address, formats_, &entry);
503 if (read_result.ok()) {
504 return read_result;
505 }
506
507 // Found a bad address. Set the sector as corrupt.
508 error_detected_ = true;
509 sectors_.FromAddress(address).mark_corrupt();
510 }
511
512 ERR("No valid entries for key. Data has been lost!");
513 return read_result;
514}
515
Rob Olivere64daf42020-11-24 11:50:03 -0500516Status KeyValueStore::FindEntry(Key key, EntryMetadata* found_entry) const {
David Rogers98fea472020-04-01 15:43:48 -0700517 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
Rob Olivere64daf42020-11-24 11:50:03 -0500526Status KeyValueStore::FindExisting(Key key, EntryMetadata* metadata) const {
David Rogers98fea472020-04-01 15:43:48 -0700527 Status status = FindEntry(key, metadata);
528
529 // If the key's hash collides with an existing key or if the key is deleted,
530 // treat it as if it is not in the KVS.
Wyatt Heplerf276c6b2020-11-11 21:13:38 -0800531 if (status.IsAlreadyExists() ||
David Rogers98fea472020-04-01 15:43:48 -0700532 (status.ok() && metadata->state() == EntryState::kDeleted)) {
Wyatt Heplerd78f7c62020-09-28 14:27:32 -0700533 return Status::NotFound();
David Rogers98fea472020-04-01 15:43:48 -0700534 }
535 return status;
536}
537
Rob Olivere64daf42020-11-24 11:50:03 -0500538StatusWithSize KeyValueStore::Get(Key key,
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700539 const EntryMetadata& metadata,
Wyatt Heplere2cbadf2020-06-22 11:21:45 -0700540 std::span<std::byte> value_buffer,
Wyatt Heplerfac81132020-02-27 17:26:33 -0800541 size_t offset_bytes) const {
542 Entry entry;
David Rogers98fea472020-04-01 15:43:48 -0700543
David Rogersc4dc8642020-09-14 10:52:36 -0700544 PW_TRY_WITH_SIZE(ReadEntry(metadata, entry));
Wyatt Heplerfac81132020-02-27 17:26:33 -0800545
546 StatusWithSize result = entry.ReadValue(value_buffer, offset_bytes);
547 if (result.ok() && options_.verify_on_read && offset_bytes == 0u) {
Wyatt Hepler22d0d9f2020-03-05 14:57:11 -0800548 Status verify_result =
549 entry.VerifyChecksum(key, value_buffer.first(result.size()));
Wyatt Heplerfac81132020-02-27 17:26:33 -0800550 if (!verify_result.ok()) {
551 std::memset(value_buffer.data(), 0, result.size());
552 return StatusWithSize(verify_result, 0);
553 }
554
555 return StatusWithSize(verify_result, result.size());
556 }
557 return result;
Wyatt Heplered163b02020-02-03 17:49:32 -0800558}
559
Rob Olivere64daf42020-11-24 11:50:03 -0500560Status KeyValueStore::FixedSizeGet(Key key,
Wyatt Heplerfac81132020-02-27 17:26:33 -0800561 void* value,
562 size_t size_bytes) const {
David Rogersc4dc8642020-09-14 10:52:36 -0700563 PW_TRY(CheckWriteOperation(key));
Wyatt Heplerfac81132020-02-27 17:26:33 -0800564
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700565 EntryMetadata metadata;
David Rogersc4dc8642020-09-14 10:52:36 -0700566 PW_TRY(FindExisting(key, &metadata));
Wyatt Heplerfac81132020-02-27 17:26:33 -0800567
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700568 return FixedSizeGet(key, metadata, value, size_bytes);
Wyatt Heplerfac81132020-02-27 17:26:33 -0800569}
570
Rob Olivere64daf42020-11-24 11:50:03 -0500571Status KeyValueStore::FixedSizeGet(Key key,
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700572 const EntryMetadata& metadata,
Wyatt Heplerfac81132020-02-27 17:26:33 -0800573 void* value,
Wyatt Hepler6e3a83b2020-02-04 07:36:45 -0800574 size_t size_bytes) const {
575 // Ensure that the size of the stored value matches the size of the type.
576 // Otherwise, report error. This check avoids potential memory corruption.
David Rogersc4dc8642020-09-14 10:52:36 -0700577 PW_TRY_ASSIGN(const size_t actual_size, ValueSize(metadata));
Wyatt Heplerfac81132020-02-27 17:26:33 -0800578
579 if (actual_size != size_bytes) {
David Rogers9fc78b82020-06-12 13:56:12 -0700580 DBG("Requested %u B read, but value is %u B",
581 unsigned(size_bytes),
582 unsigned(actual_size));
Wyatt Heplerd78f7c62020-09-28 14:27:32 -0700583 return Status::InvalidArgument();
Wyatt Heplerbab0e202020-02-04 07:40:08 -0800584 }
Wyatt Heplerfac81132020-02-27 17:26:33 -0800585
586 StatusWithSize result =
Wyatt Heplere2cbadf2020-06-22 11:21:45 -0700587 Get(key, metadata, std::span(static_cast<byte*>(value), size_bytes), 0);
Wyatt Heplerfac81132020-02-27 17:26:33 -0800588
589 return result.status();
590}
591
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700592StatusWithSize KeyValueStore::ValueSize(const EntryMetadata& metadata) const {
Wyatt Heplerfac81132020-02-27 17:26:33 -0800593 Entry entry;
David Rogersc4dc8642020-09-14 10:52:36 -0700594 PW_TRY_WITH_SIZE(ReadEntry(metadata, entry));
Wyatt Heplerfac81132020-02-27 17:26:33 -0800595
596 return StatusWithSize(entry.value_size());
Keir Mierle8c352dc2020-02-02 13:58:19 -0800597}
598
Rob Olivere64daf42020-11-24 11:50:03 -0500599Status KeyValueStore::CheckWriteOperation(Key key) const {
Wyatt Hepleracaacf92020-01-24 10:58:30 -0800600 if (InvalidKey(key)) {
Wyatt Heplerd78f7c62020-09-28 14:27:32 -0700601 return Status::InvalidArgument();
Wyatt Heplerb7609542020-01-24 10:29:54 -0800602 }
David Rogers9abe3c72020-03-24 19:03:13 -0700603
604 // For normal write operation the KVS must be fully ready.
Wyatt Heplerd2298282020-02-20 17:12:45 -0800605 if (!initialized()) {
Wyatt Heplerd78f7c62020-09-28 14:27:32 -0700606 return Status::FailedPrecondition();
Wyatt Heplerb7609542020-01-24 10:29:54 -0800607 }
Wyatt Hepler1b3da3a2021-01-07 13:26:57 -0800608 return OkStatus();
Wyatt Heplerb7609542020-01-24 10:29:54 -0800609}
610
Rob Olivere64daf42020-11-24 11:50:03 -0500611Status KeyValueStore::CheckReadOperation(Key key) const {
David Rogers9abe3c72020-03-24 19:03:13 -0700612 if (InvalidKey(key)) {
Wyatt Heplerd78f7c62020-09-28 14:27:32 -0700613 return Status::InvalidArgument();
David Rogers9abe3c72020-03-24 19:03:13 -0700614 }
615
616 // Operations that are explicitly read-only can be done after init() has been
617 // called but not fully ready (when needing maintenance).
618 if (initialized_ == InitializationState::kNotInitialized) {
Wyatt Heplerd78f7c62020-09-28 14:27:32 -0700619 return Status::FailedPrecondition();
David Rogers9abe3c72020-03-24 19:03:13 -0700620 }
Wyatt Hepler1b3da3a2021-01-07 13:26:57 -0800621 return OkStatus();
David Rogers9abe3c72020-03-24 19:03:13 -0700622}
623
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700624Status KeyValueStore::WriteEntryForExistingKey(EntryMetadata& metadata,
625 EntryState new_state,
Rob Olivere64daf42020-11-24 11:50:03 -0500626 Key key,
Wyatt Heplere2cbadf2020-06-22 11:21:45 -0700627 std::span<const byte> value) {
Wyatt Heplerab3b2492020-03-11 16:15:16 -0700628 // Read the original entry to get the size for sector accounting purposes.
629 Entry entry;
David Rogersc4dc8642020-09-14 10:52:36 -0700630 PW_TRY(ReadEntry(metadata, entry));
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800631
David Rogersc0104462020-05-08 15:50:23 -0700632 return WriteEntry(key, value, new_state, &metadata, &entry);
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800633}
634
Rob Olivere64daf42020-11-24 11:50:03 -0500635Status KeyValueStore::WriteEntryForNewKey(Key key,
Wyatt Heplere2cbadf2020-06-22 11:21:45 -0700636 std::span<const byte> value) {
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700637 if (entry_cache_.full()) {
David Rogers9fc78b82020-06-12 13:56:12 -0700638 WRN("KVS full: trying to store a new entry, but can't. Have %u entries",
639 unsigned(entry_cache_.total_entries()));
Wyatt Heplerd78f7c62020-09-28 14:27:32 -0700640 return Status::ResourceExhausted();
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800641 }
642
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700643 return WriteEntry(key, value, EntryState::kValid);
Wyatt Heplerab3b2492020-03-11 16:15:16 -0700644}
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800645
Rob Olivere64daf42020-11-24 11:50:03 -0500646Status KeyValueStore::WriteEntry(Key key,
Wyatt Heplere2cbadf2020-06-22 11:21:45 -0700647 std::span<const byte> value,
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700648 EntryState new_state,
649 EntryMetadata* prior_metadata,
David Rogersc0104462020-05-08 15:50:23 -0700650 const Entry* prior_entry) {
David Rogersc0104462020-05-08 15:50:23 -0700651 // If new entry and prior entry have matching value size, state, and checksum,
652 // check if the values match. Directly compare the prior and new values
653 // because the checksum can not be depended on to establish equality, it can
654 // only be depended on to establish inequality.
David Rogersd50eb1c2020-05-12 17:46:36 -0700655 if (prior_entry != nullptr && prior_entry->value_size() == value.size() &&
David Rogersc0104462020-05-08 15:50:23 -0700656 prior_metadata->state() == new_state &&
David Rogersc0104462020-05-08 15:50:23 -0700657 prior_entry->ValueMatches(value).ok()) {
David Rogersd50eb1c2020-05-12 17:46:36 -0700658 // The new value matches the prior value, don't need to write anything. Just
659 // keep the existing entry.
David Rogersc0104462020-05-08 15:50:23 -0700660 DBG("Write for key 0x%08x with matching value skipped",
661 unsigned(prior_metadata->hash()));
Wyatt Hepler1b3da3a2021-01-07 13:26:57 -0800662 return OkStatus();
David Rogersc0104462020-05-08 15:50:23 -0700663 }
Wyatt Heplerab3b2492020-03-11 16:15:16 -0700664
665 // List of addresses for sectors with space for this entry.
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700666 Address* reserved_addresses = entry_cache_.TempReservedAddressesForWrite();
Wyatt Heplerab3b2492020-03-11 16:15:16 -0700667
David Rogers31b358b2020-04-15 05:00:50 -0700668 // Find addresses to write the entry to. This may involve garbage collecting
669 // one or more sectors.
David Rogersc0104462020-05-08 15:50:23 -0700670 const size_t entry_size = Entry::size(partition_, key, value);
David Rogersc4dc8642020-09-14 10:52:36 -0700671 PW_TRY(GetAddressesForWrite(reserved_addresses, entry_size));
Wyatt Heplerab3b2492020-03-11 16:15:16 -0700672
673 // Write the entry at the first address that was found.
David Rogersd50eb1c2020-05-12 17:46:36 -0700674 Entry entry = CreateEntry(reserved_addresses[0], key, value, new_state);
David Rogersc4dc8642020-09-14 10:52:36 -0700675 PW_TRY(AppendEntry(entry, key, value));
Wyatt Heplerab3b2492020-03-11 16:15:16 -0700676
677 // After writing the first entry successfully, update the key descriptors.
678 // Once a single new the entry is written, the old entries are invalidated.
David Rogersc0104462020-05-08 15:50:23 -0700679 size_t prior_size = prior_entry != nullptr ? prior_entry->size() : 0;
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700680 EntryMetadata new_metadata =
David Rogers31b358b2020-04-15 05:00:50 -0700681 CreateOrUpdateKeyDescriptor(entry, key, prior_metadata, prior_size);
Wyatt Heplerab3b2492020-03-11 16:15:16 -0700682
683 // Write the additional copies of the entry, if redundancy is greater than 1.
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700684 for (size_t i = 1; i < redundancy(); ++i) {
685 entry.set_address(reserved_addresses[i]);
David Rogersc4dc8642020-09-14 10:52:36 -0700686 PW_TRY(AppendEntry(entry, key, value));
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700687 new_metadata.AddNewAddress(reserved_addresses[i]);
Wyatt Heplerab3b2492020-03-11 16:15:16 -0700688 }
Wyatt Hepler1b3da3a2021-01-07 13:26:57 -0800689 return OkStatus();
Wyatt Heplerb7609542020-01-24 10:29:54 -0800690}
691
David Rogers31b358b2020-04-15 05:00:50 -0700692KeyValueStore::EntryMetadata KeyValueStore::CreateOrUpdateKeyDescriptor(
Wyatt Heplerab3b2492020-03-11 16:15:16 -0700693 const Entry& entry,
Rob Olivere64daf42020-11-24 11:50:03 -0500694 Key key,
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700695 EntryMetadata* prior_metadata,
Wyatt Heplerab3b2492020-03-11 16:15:16 -0700696 size_t prior_size) {
697 // If there is no prior descriptor, create a new one.
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700698 if (prior_metadata == nullptr) {
699 return entry_cache_.AddNew(entry.descriptor(key), entry.address());
David Rogersa2562b52020-03-05 15:30:05 -0800700 }
701
David Rogers31b358b2020-04-15 05:00:50 -0700702 return UpdateKeyDescriptor(
703 entry, entry.address(), prior_metadata, prior_size);
704}
705
706KeyValueStore::EntryMetadata KeyValueStore::UpdateKeyDescriptor(
707 const Entry& entry,
708 Address new_address,
709 EntryMetadata* prior_metadata,
710 size_t prior_size) {
Wyatt Heplerab3b2492020-03-11 16:15:16 -0700711 // Remove valid bytes for the old entry and its copies, which are now stale.
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700712 for (Address address : prior_metadata->addresses()) {
Wyatt Heplerc84393f2020-03-20 11:23:24 -0700713 sectors_.FromAddress(address).RemoveValidBytes(prior_size);
David Rogersa2562b52020-03-05 15:30:05 -0800714 }
715
David Rogers31b358b2020-04-15 05:00:50 -0700716 prior_metadata->Reset(entry.descriptor(prior_metadata->hash()), new_address);
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700717 return *prior_metadata;
David Rogersa2562b52020-03-05 15:30:05 -0800718}
719
David Rogers31b358b2020-04-15 05:00:50 -0700720Status KeyValueStore::GetAddressesForWrite(Address* write_addresses,
721 size_t write_size) {
722 for (size_t i = 0; i < redundancy(); i++) {
723 SectorDescriptor* sector;
David Rogersc4dc8642020-09-14 10:52:36 -0700724 PW_TRY(
725 GetSectorForWrite(&sector, write_size, std::span(write_addresses, i)));
David Rogers31b358b2020-04-15 05:00:50 -0700726 write_addresses[i] = sectors_.NextWritableAddress(*sector);
727
728 DBG("Found space for entry in sector %u at address %u",
729 sectors_.Index(sector),
730 unsigned(write_addresses[i]));
731 }
732
Wyatt Hepler1b3da3a2021-01-07 13:26:57 -0800733 return OkStatus();
David Rogers31b358b2020-04-15 05:00:50 -0700734}
735
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700736// Finds a sector to use for writing a new entry to. Does automatic garbage
David Rogersa2562b52020-03-05 15:30:05 -0800737// collection if needed and allowed.
738//
739// OK: Sector found with needed space.
740// RESOURCE_EXHAUSTED: No sector available with the needed space.
741Status KeyValueStore::GetSectorForWrite(SectorDescriptor** sector,
742 size_t entry_size,
Wyatt Heplere2cbadf2020-06-22 11:21:45 -0700743 std::span<const Address> reserved) {
Wyatt Heplerc84393f2020-03-20 11:23:24 -0700744 Status result = sectors_.FindSpace(sector, entry_size, reserved);
David Rogersa2562b52020-03-05 15:30:05 -0800745
David Rogersf3884eb2020-03-08 19:21:40 -0700746 size_t gc_sector_count = 0;
David Rogersa2562b52020-03-05 15:30:05 -0800747 bool do_auto_gc = options_.gc_on_write != GargbageCollectOnWrite::kDisabled;
748
749 // Do garbage collection as needed, so long as policy allows.
Wyatt Heplerf276c6b2020-11-11 21:13:38 -0800750 while (result.IsResourceExhausted() && do_auto_gc) {
David Rogersa2562b52020-03-05 15:30:05 -0800751 if (options_.gc_on_write == GargbageCollectOnWrite::kOneSector) {
752 // If GC config option is kOneSector clear the flag to not do any more
753 // GC after this try.
754 do_auto_gc = false;
755 }
756 // Garbage collect and then try again to find the best sector.
David Rogers9abe3c72020-03-24 19:03:13 -0700757 Status gc_status = GarbageCollect(reserved);
David Rogersa2562b52020-03-05 15:30:05 -0800758 if (!gc_status.ok()) {
Wyatt Heplerf276c6b2020-11-11 21:13:38 -0800759 if (gc_status.IsNotFound()) {
David Rogersa2562b52020-03-05 15:30:05 -0800760 // Not enough space, and no reclaimable bytes, this KVS is full!
Wyatt Heplerd78f7c62020-09-28 14:27:32 -0700761 return Status::ResourceExhausted();
David Rogersa2562b52020-03-05 15:30:05 -0800762 }
763 return gc_status;
764 }
765
Wyatt Heplerc84393f2020-03-20 11:23:24 -0700766 result = sectors_.FindSpace(sector, entry_size, reserved);
David Rogersf3884eb2020-03-08 19:21:40 -0700767
768 gc_sector_count++;
769 // Allow total sectors + 2 number of GC cycles so that once reclaimable
770 // bytes in all the sectors have been reclaimed can try and free up space by
771 // moving entries for keys other than the one being worked on in to sectors
772 // that have copies of the key trying to be written.
773 if (gc_sector_count > (partition_.sector_count() + 2)) {
774 ERR("Did more GC sectors than total sectors!!!!");
Wyatt Heplerd78f7c62020-09-28 14:27:32 -0700775 return Status::ResourceExhausted();
David Rogersf3884eb2020-03-08 19:21:40 -0700776 }
David Rogersa2562b52020-03-05 15:30:05 -0800777 }
778
779 if (!result.ok()) {
David Rogers9fc78b82020-06-12 13:56:12 -0700780 WRN("Unable to find sector to write %u B", unsigned(entry_size));
David Rogersa2562b52020-03-05 15:30:05 -0800781 }
782 return result;
783}
784
David Rogers9abe3c72020-03-24 19:03:13 -0700785Status KeyValueStore::MarkSectorCorruptIfNotOk(Status status,
786 SectorDescriptor* sector) {
787 if (!status.ok()) {
788 DBG(" Sector %u corrupt", sectors_.Index(sector));
789 sector->mark_corrupt();
790 error_detected_ = true;
791 }
792 return status;
793}
794
Wyatt Heplerab3b2492020-03-11 16:15:16 -0700795Status KeyValueStore::AppendEntry(const Entry& entry,
Rob Olivere64daf42020-11-24 11:50:03 -0500796 Key key,
Wyatt Heplere2cbadf2020-06-22 11:21:45 -0700797 std::span<const byte> value) {
Wyatt Heplerab3b2492020-03-11 16:15:16 -0700798 const StatusWithSize result = entry.Write(key, value);
David Rogersa2562b52020-03-05 15:30:05 -0800799
Wyatt Heplerc84393f2020-03-20 11:23:24 -0700800 SectorDescriptor& sector = sectors_.FromAddress(entry.address());
David Rogersa2562b52020-03-05 15:30:05 -0800801
802 if (!result.ok()) {
David Rogers9fc78b82020-06-12 13:56:12 -0700803 ERR("Failed to write %u bytes at %#x. %u actually written",
804 unsigned(entry.size()),
805 unsigned(entry.address()),
806 unsigned(result.size()));
David Rogersc4dc8642020-09-14 10:52:36 -0700807 PW_TRY(MarkSectorCorruptIfNotOk(result.status(), &sector));
David Rogersa2562b52020-03-05 15:30:05 -0800808 }
809
810 if (options_.verify_on_write) {
David Rogersc4dc8642020-09-14 10:52:36 -0700811 PW_TRY(MarkSectorCorruptIfNotOk(entry.VerifyChecksumInFlash(), &sector));
David Rogersa2562b52020-03-05 15:30:05 -0800812 }
813
David Rogers98fea472020-04-01 15:43:48 -0700814 sector.RemoveWritableBytes(result.size());
Wyatt Heplerc84393f2020-03-20 11:23:24 -0700815 sector.AddValidBytes(result.size());
Wyatt Hepler1b3da3a2021-01-07 13:26:57 -0800816 return OkStatus();
David Rogersa2562b52020-03-05 15:30:05 -0800817}
818
David Rogers98fea472020-04-01 15:43:48 -0700819StatusWithSize KeyValueStore::CopyEntryToSector(Entry& entry,
820 SectorDescriptor* new_sector,
David Rogers31b358b2020-04-15 05:00:50 -0700821 Address new_address) {
David Rogers98fea472020-04-01 15:43:48 -0700822 const StatusWithSize result = entry.Copy(new_address);
823
David Rogersc4dc8642020-09-14 10:52:36 -0700824 PW_TRY_WITH_SIZE(MarkSectorCorruptIfNotOk(result.status(), new_sector));
David Rogers98fea472020-04-01 15:43:48 -0700825
826 if (options_.verify_on_write) {
David Rogers31b358b2020-04-15 05:00:50 -0700827 Entry new_entry;
David Rogersc4dc8642020-09-14 10:52:36 -0700828 PW_TRY_WITH_SIZE(MarkSectorCorruptIfNotOk(
David Rogers31b358b2020-04-15 05:00:50 -0700829 Entry::Read(partition_, new_address, formats_, &new_entry),
830 new_sector));
831 // TODO: add test that catches doing the verify on the old entry.
David Rogersc4dc8642020-09-14 10:52:36 -0700832 PW_TRY_WITH_SIZE(MarkSectorCorruptIfNotOk(new_entry.VerifyChecksumInFlash(),
833 new_sector));
David Rogers98fea472020-04-01 15:43:48 -0700834 }
835 // Entry was written successfully; update descriptor's address and the sector
836 // descriptors to reflect the new entry.
837 new_sector->RemoveWritableBytes(result.size());
838 new_sector->AddValidBytes(result.size());
839
840 return result;
841}
842
Wyatt Heplere2cbadf2020-06-22 11:21:45 -0700843Status KeyValueStore::RelocateEntry(
844 const EntryMetadata& metadata,
845 KeyValueStore::Address& address,
846 std::span<const Address> reserved_addresses) {
David Rogersa2562b52020-03-05 15:30:05 -0800847 Entry entry;
David Rogersc4dc8642020-09-14 10:52:36 -0700848 PW_TRY(ReadEntry(metadata, entry));
David Rogersa2562b52020-03-05 15:30:05 -0800849
850 // Find a new sector for the entry and write it to the new location. For
851 // relocation the find should not not be a sector already containing the key
852 // but can be the always empty sector, since this is part of the GC process
853 // that will result in a new empty sector. Also find a sector that does not
854 // have reclaimable space (mostly for the full GC, where that would result in
855 // an immediate extra relocation).
856 SectorDescriptor* new_sector;
857
David Rogersc4dc8642020-09-14 10:52:36 -0700858 PW_TRY(sectors_.FindSpaceDuringGarbageCollection(
Wyatt Heplerc84393f2020-03-20 11:23:24 -0700859 &new_sector, entry.size(), metadata.addresses(), reserved_addresses));
Wyatt Heplerab3b2492020-03-11 16:15:16 -0700860
David Rogers31b358b2020-04-15 05:00:50 -0700861 Address new_address = sectors_.NextWritableAddress(*new_sector);
David Rogersc4dc8642020-09-14 10:52:36 -0700862 PW_TRY_ASSIGN(const size_t result_size,
863 CopyEntryToSector(entry, new_sector, new_address));
David Rogers98fea472020-04-01 15:43:48 -0700864 sectors_.FromAddress(address).RemoveValidBytes(result_size);
Wyatt Heplerab3b2492020-03-11 16:15:16 -0700865 address = new_address;
David Rogersa2562b52020-03-05 15:30:05 -0800866
Wyatt Hepler1b3da3a2021-01-07 13:26:57 -0800867 return OkStatus();
David Rogersa2562b52020-03-05 15:30:05 -0800868}
869
David Rogers3c298372020-10-12 14:15:39 -0700870Status KeyValueStore::FullMaintenanceHelper(MaintenanceType maintenance_type) {
David Rogers9abe3c72020-03-24 19:03:13 -0700871 if (initialized_ == InitializationState::kNotInitialized) {
Wyatt Heplerd78f7c62020-09-28 14:27:32 -0700872 return Status::FailedPrecondition();
David Rogers9abe3c72020-03-24 19:03:13 -0700873 }
874
Armando Montanez17083bb2020-04-24 10:18:26 -0700875 // Full maintenance can be a potentially heavy operation, and should be
876 // relatively infrequent, so log start/end at INFO level.
877 INF("Beginning full maintenance");
David Rogers98fea472020-04-01 15:43:48 -0700878 CheckForErrors();
David Rogers9abe3c72020-03-24 19:03:13 -0700879
880 if (error_detected_) {
David Rogersc4dc8642020-09-14 10:52:36 -0700881 PW_TRY(Repair());
David Rogers9abe3c72020-03-24 19:03:13 -0700882 }
David Rogers35c3f842020-04-22 15:34:05 -0700883 StatusWithSize update_status = UpdateEntriesToPrimaryFormat();
884 Status overall_status = update_status.status();
885
David Rogers31b358b2020-04-15 05:00:50 -0700886 // Make sure all the entries are on the primary format.
Armando Montanez17083bb2020-04-24 10:18:26 -0700887 if (!overall_status.ok()) {
888 ERR("Failed to update all entries to the primary format");
889 }
David Rogers31b358b2020-04-15 05:00:50 -0700890
Wyatt Heplerc84393f2020-03-20 11:23:24 -0700891 SectorDescriptor* sector = sectors_.last_new();
David Rogerscd87c322020-02-27 14:04:08 -0800892
David Rogers35c3f842020-04-22 15:34:05 -0700893 // Calculate number of bytes for the threshold.
894 size_t threshold_bytes =
895 (partition_.size_bytes() * kGcUsageThresholdPercentage) / 100;
896
897 // Is bytes in use over the threshold.
898 StorageStats stats = GetStorageStats();
899 bool over_usage_threshold = stats.in_use_bytes > threshold_bytes;
David Rogers3c298372020-10-12 14:15:39 -0700900 bool heavy = (maintenance_type == MaintenanceType::kHeavy);
901 bool force_gc = heavy || over_usage_threshold || (update_status.size() > 0);
David Rogers35c3f842020-04-22 15:34:05 -0700902
David Rogerscd87c322020-02-27 14:04:08 -0800903 // TODO: look in to making an iterator method for cycling through sectors
904 // starting from last_new_sector_.
Armando Montanez17083bb2020-04-24 10:18:26 -0700905 Status gc_status;
David Rogerscd87c322020-02-27 14:04:08 -0800906 for (size_t j = 0; j < sectors_.size(); j++) {
907 sector += 1;
908 if (sector == sectors_.end()) {
909 sector = sectors_.begin();
910 }
911
David Rogers35c3f842020-04-22 15:34:05 -0700912 if (sector->RecoverableBytes(partition_.sector_size_bytes()) > 0 &&
913 (force_gc || sector->valid_bytes() == 0)) {
Armando Montanez17083bb2020-04-24 10:18:26 -0700914 gc_status = GarbageCollectSector(*sector, {});
915 if (!gc_status.ok()) {
916 ERR("Failed to garbage collect all sectors");
917 break;
918 }
David Rogerscd87c322020-02-27 14:04:08 -0800919 }
920 }
Armando Montanez17083bb2020-04-24 10:18:26 -0700921 if (overall_status.ok()) {
922 overall_status = gc_status;
923 }
David Rogerscd87c322020-02-27 14:04:08 -0800924
Armando Montanez17083bb2020-04-24 10:18:26 -0700925 if (overall_status.ok()) {
926 INF("Full maintenance complete");
927 } else {
928 ERR("Full maintenance finished with some errors");
929 }
930 return overall_status;
David Rogerscd87c322020-02-27 14:04:08 -0800931}
932
David Rogers0f8a1bb2020-04-21 18:50:19 -0700933Status KeyValueStore::PartialMaintenance() {
David Rogers9abe3c72020-03-24 19:03:13 -0700934 if (initialized_ == InitializationState::kNotInitialized) {
Wyatt Heplerd78f7c62020-09-28 14:27:32 -0700935 return Status::FailedPrecondition();
David Rogers9abe3c72020-03-24 19:03:13 -0700936 }
937
David Rogers0f8a1bb2020-04-21 18:50:19 -0700938 CheckForErrors();
David Rogersfcea3252020-04-07 14:56:35 -0700939 // Do automatic repair, if KVS options allow for it.
940 if (error_detected_ && options_.recovery != ErrorRecovery::kManual) {
David Rogersc4dc8642020-09-14 10:52:36 -0700941 PW_TRY(Repair());
David Rogersfcea3252020-04-07 14:56:35 -0700942 }
Wyatt Heplere2cbadf2020-06-22 11:21:45 -0700943 return GarbageCollect(std::span<const Address>());
David Rogers0f8a1bb2020-04-21 18:50:19 -0700944}
945
Wyatt Heplere2cbadf2020-06-22 11:21:45 -0700946Status KeyValueStore::GarbageCollect(
947 std::span<const Address> reserved_addresses) {
David Rogers0f8a1bb2020-04-21 18:50:19 -0700948 DBG("Garbage Collect a single sector");
949 for (Address address : reserved_addresses) {
950 DBG(" Avoid address %u", unsigned(address));
951 }
David Rogersfcea3252020-04-07 14:56:35 -0700952
David Rogersa12786b2020-01-31 16:02:33 -0800953 // Step 1: Find the sector to garbage collect
David Rogersc9d545e2020-03-11 17:47:43 -0700954 SectorDescriptor* sector_to_gc =
Wyatt Heplerc84393f2020-03-20 11:23:24 -0700955 sectors_.FindSectorToGarbageCollect(reserved_addresses);
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800956
David Rogersa12786b2020-01-31 16:02:33 -0800957 if (sector_to_gc == nullptr) {
David Rogersa2562b52020-03-05 15:30:05 -0800958 // Nothing to GC.
Wyatt Heplerd78f7c62020-09-28 14:27:32 -0700959 return Status::NotFound();
David Rogersa12786b2020-01-31 16:02:33 -0800960 }
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800961
David Rogersc9d545e2020-03-11 17:47:43 -0700962 // Step 2: Garbage collect the selected sector.
Wyatt Heplerc84393f2020-03-20 11:23:24 -0700963 return GarbageCollectSector(*sector_to_gc, reserved_addresses);
David Rogerscd87c322020-02-27 14:04:08 -0800964}
965
David Rogersf3884eb2020-03-08 19:21:40 -0700966Status KeyValueStore::RelocateKeyAddressesInSector(
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700967 SectorDescriptor& sector_to_gc,
David Rogersfcea3252020-04-07 14:56:35 -0700968 const EntryMetadata& metadata,
Wyatt Heplere2cbadf2020-06-22 11:21:45 -0700969 std::span<const Address> reserved_addresses) {
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700970 for (FlashPartition::Address& address : metadata.addresses()) {
Wyatt Heplerc84393f2020-03-20 11:23:24 -0700971 if (sectors_.AddressInSector(sector_to_gc, address)) {
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700972 DBG(" Relocate entry for Key 0x%08" PRIx32 ", sector %u",
973 metadata.hash(),
Wyatt Heplerc84393f2020-03-20 11:23:24 -0700974 sectors_.Index(sectors_.FromAddress(address)));
David Rogersc4dc8642020-09-14 10:52:36 -0700975 PW_TRY(RelocateEntry(metadata, address, reserved_addresses));
David Rogersf3884eb2020-03-08 19:21:40 -0700976 }
977 }
Wyatt Heplerab3b2492020-03-11 16:15:16 -0700978
Wyatt Hepler1b3da3a2021-01-07 13:26:57 -0800979 return OkStatus();
David Rogersf3884eb2020-03-08 19:21:40 -0700980};
981
Wyatt Heplerab3b2492020-03-11 16:15:16 -0700982Status KeyValueStore::GarbageCollectSector(
Wyatt Heplere2cbadf2020-06-22 11:21:45 -0700983 SectorDescriptor& sector_to_gc,
984 std::span<const Address> reserved_addresses) {
David Rogers9abe3c72020-03-24 19:03:13 -0700985 DBG(" Garbage Collect sector %u", sectors_.Index(sector_to_gc));
David Rogers3c298372020-10-12 14:15:39 -0700986
David Rogersf3884eb2020-03-08 19:21:40 -0700987 // Step 1: Move any valid entries in the GC sector to other sectors
Wyatt Heplerc84393f2020-03-20 11:23:24 -0700988 if (sector_to_gc.valid_bytes() != 0) {
David Rogers98fea472020-04-01 15:43:48 -0700989 for (EntryMetadata& metadata : entry_cache_) {
David Rogersc4dc8642020-09-14 10:52:36 -0700990 PW_TRY(RelocateKeyAddressesInSector(
Wyatt Heplerc84393f2020-03-20 11:23:24 -0700991 sector_to_gc, metadata, reserved_addresses));
David Rogersf3884eb2020-03-08 19:21:40 -0700992 }
993 }
994
Wyatt Heplerc84393f2020-03-20 11:23:24 -0700995 if (sector_to_gc.valid_bytes() != 0) {
David Rogers67f4b6c2020-02-06 16:17:09 -0800996 ERR(" Failed to relocate valid entries from sector being garbage "
David Rogers9fc78b82020-06-12 13:56:12 -0700997 "collected, %u valid bytes remain",
998 unsigned(sector_to_gc.valid_bytes()));
Wyatt Heplerd78f7c62020-09-28 14:27:32 -0700999 return Status::Internal();
Wyatt Heplerb7609542020-01-24 10:29:54 -08001000 }
1001
David Rogerscd87c322020-02-27 14:04:08 -08001002 // Step 2: Reinitialize the sector
David Rogers3c298372020-10-12 14:15:39 -07001003 if (!sector_to_gc.Empty(partition_.sector_size_bytes())) {
1004 sector_to_gc.mark_corrupt();
1005 internal_stats_.sector_erase_count++;
1006 PW_TRY(partition_.Erase(sectors_.BaseAddress(sector_to_gc), 1));
1007 sector_to_gc.set_writable_bytes(partition_.sector_size_bytes());
1008 }
Wyatt Heplerb7609542020-01-24 10:29:54 -08001009
Wyatt Heplerc84393f2020-03-20 11:23:24 -07001010 DBG(" Garbage Collect sector %u complete", sectors_.Index(sector_to_gc));
Wyatt Hepler1b3da3a2021-01-07 13:26:57 -08001011 return OkStatus();
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -08001012}
1013
David Rogers35c3f842020-04-22 15:34:05 -07001014StatusWithSize KeyValueStore::UpdateEntriesToPrimaryFormat() {
1015 size_t entries_updated = 0;
David Rogers31b358b2020-04-15 05:00:50 -07001016 for (EntryMetadata& prior_metadata : entry_cache_) {
1017 Entry entry;
David Rogersc4dc8642020-09-14 10:52:36 -07001018 PW_TRY_WITH_SIZE(ReadEntry(prior_metadata, entry));
David Rogers31b358b2020-04-15 05:00:50 -07001019 if (formats_.primary().magic == entry.magic()) {
1020 // Ignore entries that are already on the primary format.
1021 continue;
1022 }
1023
1024 DBG("Updating entry 0x%08x from old format [0x%08x] to new format "
1025 "[0x%08x]",
1026 unsigned(prior_metadata.hash()),
1027 unsigned(entry.magic()),
1028 unsigned(formats_.primary().magic));
1029
David Rogers35c3f842020-04-22 15:34:05 -07001030 entries_updated++;
1031
David Rogers31b358b2020-04-15 05:00:50 -07001032 last_transaction_id_ += 1;
David Rogersc4dc8642020-09-14 10:52:36 -07001033 PW_TRY_WITH_SIZE(entry.Update(formats_.primary(), last_transaction_id_));
David Rogers31b358b2020-04-15 05:00:50 -07001034
1035 // List of addresses for sectors with space for this entry.
1036 Address* reserved_addresses = entry_cache_.TempReservedAddressesForWrite();
1037
1038 // Find addresses to write the entry to. This may involve garbage collecting
1039 // one or more sectors.
David Rogersc4dc8642020-09-14 10:52:36 -07001040 PW_TRY_WITH_SIZE(GetAddressesForWrite(reserved_addresses, entry.size()));
David Rogers31b358b2020-04-15 05:00:50 -07001041
David Rogersc4dc8642020-09-14 10:52:36 -07001042 PW_TRY_WITH_SIZE(
David Rogers35c3f842020-04-22 15:34:05 -07001043 CopyEntryToSector(entry,
David Rogers31b358b2020-04-15 05:00:50 -07001044 &sectors_.FromAddress(reserved_addresses[0]),
1045 reserved_addresses[0]));
1046
1047 // After writing the first entry successfully, update the key descriptors.
1048 // Once a single new the entry is written, the old entries are invalidated.
1049 EntryMetadata new_metadata = UpdateKeyDescriptor(
1050 entry, reserved_addresses[0], &prior_metadata, entry.size());
1051
1052 // Write the additional copies of the entry, if redundancy is greater
1053 // than 1.
1054 for (size_t i = 1; i < redundancy(); ++i) {
David Rogersc4dc8642020-09-14 10:52:36 -07001055 PW_TRY_WITH_SIZE(
David Rogers35c3f842020-04-22 15:34:05 -07001056 CopyEntryToSector(entry,
David Rogers31b358b2020-04-15 05:00:50 -07001057 &sectors_.FromAddress(reserved_addresses[i]),
1058 reserved_addresses[i]));
1059 new_metadata.AddNewAddress(reserved_addresses[i]);
1060 }
1061 }
David Rogers35c3f842020-04-22 15:34:05 -07001062
1063 return StatusWithSize(entries_updated);
David Rogers31b358b2020-04-15 05:00:50 -07001064}
1065
David Rogers9abe3c72020-03-24 19:03:13 -07001066// Add any missing redundant entries/copies for a key.
1067Status KeyValueStore::AddRedundantEntries(EntryMetadata& metadata) {
David Rogers9abe3c72020-03-24 19:03:13 -07001068 Entry entry;
David Rogersc4dc8642020-09-14 10:52:36 -07001069 PW_TRY(ReadEntry(metadata, entry));
1070 PW_TRY(entry.VerifyChecksumInFlash());
David Rogers9abe3c72020-03-24 19:03:13 -07001071
David Rogers0f8a1bb2020-04-21 18:50:19 -07001072 while (metadata.addresses().size() < redundancy()) {
1073 SectorDescriptor* new_sector;
David Rogersc4dc8642020-09-14 10:52:36 -07001074 PW_TRY(GetSectorForWrite(&new_sector, entry.size(), metadata.addresses()));
David Rogers9abe3c72020-03-24 19:03:13 -07001075
David Rogers31b358b2020-04-15 05:00:50 -07001076 Address new_address = sectors_.NextWritableAddress(*new_sector);
David Rogersc4dc8642020-09-14 10:52:36 -07001077 PW_TRY(CopyEntryToSector(entry, new_sector, new_address));
David Rogers9abe3c72020-03-24 19:03:13 -07001078
1079 metadata.AddNewAddress(new_address);
1080 }
Wyatt Hepler1b3da3a2021-01-07 13:26:57 -08001081 return OkStatus();
David Rogers9abe3c72020-03-24 19:03:13 -07001082}
1083
1084Status KeyValueStore::RepairCorruptSectors() {
1085 // Try to GC each corrupt sector, even if previous sectors fail. If GC of a
1086 // sector failed on the first pass, then do a second pass, since a later
1087 // sector might have cleared up space or otherwise unblocked the earlier
1088 // failed sector.
Wyatt Hepler1b3da3a2021-01-07 13:26:57 -08001089 Status repair_status = OkStatus();
David Rogers9abe3c72020-03-24 19:03:13 -07001090
1091 size_t loop_count = 0;
1092 do {
1093 loop_count++;
1094 // Error of RESOURCE_EXHAUSTED indicates no space found for relocation.
1095 // Reset back to OK for the next pass.
Wyatt Heplerf276c6b2020-11-11 21:13:38 -08001096 if (repair_status.IsResourceExhausted()) {
Wyatt Hepler1b3da3a2021-01-07 13:26:57 -08001097 repair_status = OkStatus();
David Rogers9abe3c72020-03-24 19:03:13 -07001098 }
1099
1100 DBG(" Pass %u", unsigned(loop_count));
1101 for (SectorDescriptor& sector : sectors_) {
1102 if (sector.corrupt()) {
1103 DBG(" Found sector %u with corruption", sectors_.Index(sector));
1104 Status sector_status = GarbageCollectSector(sector, {});
1105 if (sector_status.ok()) {
David Rogers3c298372020-10-12 14:15:39 -07001106 internal_stats_.corrupt_sectors_recovered += 1;
Wyatt Heplerf276c6b2020-11-11 21:13:38 -08001107 } else if (repair_status.ok() || repair_status.IsResourceExhausted()) {
David Rogers9abe3c72020-03-24 19:03:13 -07001108 repair_status = sector_status;
1109 }
1110 }
1111 }
1112 DBG(" Pass %u complete", unsigned(loop_count));
1113 } while (!repair_status.ok() && loop_count < 2);
1114
1115 return repair_status;
1116}
1117
1118Status KeyValueStore::EnsureFreeSectorExists() {
Wyatt Hepler1b3da3a2021-01-07 13:26:57 -08001119 Status repair_status = OkStatus();
David Rogers9abe3c72020-03-24 19:03:13 -07001120 bool empty_sector_found = false;
1121
1122 DBG(" Find empty sector");
1123 for (SectorDescriptor& sector : sectors_) {
1124 if (sector.Empty(partition_.sector_size_bytes())) {
1125 empty_sector_found = true;
1126 DBG(" Empty sector found");
1127 break;
1128 }
1129 }
1130 if (empty_sector_found == false) {
1131 DBG(" No empty sector found, attempting to GC a free sector");
Wyatt Heplere2cbadf2020-06-22 11:21:45 -07001132 Status sector_status = GarbageCollect(std::span<const Address, 0>());
David Rogers9abe3c72020-03-24 19:03:13 -07001133 if (repair_status.ok() && !sector_status.ok()) {
1134 DBG(" Unable to free an empty sector");
1135 repair_status = sector_status;
1136 }
1137 }
1138
1139 return repair_status;
1140}
1141
1142Status KeyValueStore::EnsureEntryRedundancy() {
Wyatt Hepler1b3da3a2021-01-07 13:26:57 -08001143 Status repair_status = OkStatus();
David Rogers9abe3c72020-03-24 19:03:13 -07001144
1145 if (redundancy() == 1) {
David Rogers98fea472020-04-01 15:43:48 -07001146 DBG(" Redundancy not in use, nothting to check");
Wyatt Hepler1b3da3a2021-01-07 13:26:57 -08001147 return OkStatus();
David Rogers9abe3c72020-03-24 19:03:13 -07001148 }
1149
David Rogers98fea472020-04-01 15:43:48 -07001150 DBG(" Write any needed additional duplicate copies of keys to fulfill %u"
1151 " redundancy",
David Rogers9abe3c72020-03-24 19:03:13 -07001152 unsigned(redundancy()));
David Rogers98fea472020-04-01 15:43:48 -07001153 for (EntryMetadata& metadata : entry_cache_) {
David Rogers9abe3c72020-03-24 19:03:13 -07001154 if (metadata.addresses().size() >= redundancy()) {
1155 continue;
1156 }
1157
1158 DBG(" Key with %u of %u copies found, adding missing copies",
1159 unsigned(metadata.addresses().size()),
1160 unsigned(redundancy()));
David Rogers98fea472020-04-01 15:43:48 -07001161 Status fill_status = AddRedundantEntries(metadata);
David Rogers9abe3c72020-03-24 19:03:13 -07001162 if (fill_status.ok()) {
David Rogers3c298372020-10-12 14:15:39 -07001163 internal_stats_.missing_redundant_entries_recovered += 1;
David Rogers9abe3c72020-03-24 19:03:13 -07001164 DBG(" Key missing copies added");
1165 } else {
1166 DBG(" Failed to add key missing copies");
1167 if (repair_status.ok()) {
1168 repair_status = fill_status;
1169 }
1170 }
1171 }
1172
1173 return repair_status;
1174}
1175
David Rogersfcea3252020-04-07 14:56:35 -07001176Status KeyValueStore::FixErrors() {
1177 DBG("Fixing KVS errors");
David Rogers9abe3c72020-03-24 19:03:13 -07001178
1179 // Step 1: Garbage collect any sectors marked as corrupt.
David Rogersfcea3252020-04-07 14:56:35 -07001180 Status overall_status = RepairCorruptSectors();
David Rogers9abe3c72020-03-24 19:03:13 -07001181
1182 // Step 2: Make sure there is at least 1 empty sector. This needs to be a
1183 // seperate check of sectors from step 1, because a found empty sector might
1184 // get written to by a later GC that fails and does not result in a free
1185 // sector.
David Rogersfcea3252020-04-07 14:56:35 -07001186 Status repair_status = EnsureFreeSectorExists();
David Rogers9abe3c72020-03-24 19:03:13 -07001187 if (overall_status.ok()) {
1188 overall_status = repair_status;
1189 }
1190
1191 // Step 3: Make sure each stored key has the full number of redundant
1192 // entries.
1193 repair_status = EnsureEntryRedundancy();
1194 if (overall_status.ok()) {
1195 overall_status = repair_status;
1196 }
1197
1198 if (overall_status.ok()) {
1199 error_detected_ = false;
1200 initialized_ = InitializationState::kReady;
1201 }
1202 return overall_status;
1203}
1204
David Rogersfcea3252020-04-07 14:56:35 -07001205Status KeyValueStore::Repair() {
1206 // If errors have been detected, just reinit the KVS metadata. This does a
1207 // full deep error check and any needed repairs. Then repair any errors.
1208 INF("Starting KVS repair");
1209
1210 DBG("Reinitialize KVS metadata");
1211 InitializeMetadata();
1212
1213 return FixErrors();
1214}
1215
David Rogersd50eb1c2020-05-12 17:46:36 -07001216KeyValueStore::Entry KeyValueStore::CreateEntry(Address address,
Rob Olivere64daf42020-11-24 11:50:03 -05001217 Key key,
Wyatt Heplere2cbadf2020-06-22 11:21:45 -07001218 std::span<const byte> value,
Wyatt Hepler7ded6da2020-03-11 18:24:43 -07001219 EntryState state) {
Keir Mierle9e38b402020-02-21 13:06:21 -08001220 // Always bump the transaction ID when creating a new entry.
1221 //
1222 // Burning transaction IDs prevents inconsistencies between flash and memory
1223 // that which could happen if a write succeeds, but for some reason the read
1224 // and verify step fails. Here's how this would happen:
1225 //
1226 // 1. The entry is written but for some reason the flash reports failure OR
1227 // The write succeeds, but the read / verify operation fails.
1228 // 2. The transaction ID is NOT incremented, because of the failure
1229 // 3. (later) A new entry is written, re-using the transaction ID (oops)
1230 //
David Rogersd50eb1c2020-05-12 17:46:36 -07001231 // By always burning transaction IDs, the above problem can't happen.
1232 last_transaction_id_ += 1;
Keir Mierle9e38b402020-02-21 13:06:21 -08001233
Wyatt Hepler7ded6da2020-03-11 18:24:43 -07001234 if (state == EntryState::kDeleted) {
Wyatt Hepler7465be32020-02-21 15:30:53 -08001235 return Entry::Tombstone(
David Rogersd50eb1c2020-05-12 17:46:36 -07001236 partition_, address, formats_.primary(), key, last_transaction_id_);
Wyatt Hepler1fc11042020-02-19 17:17:51 -08001237 }
David Rogersd50eb1c2020-05-12 17:46:36 -07001238 return Entry::Valid(partition_,
1239 address,
1240 formats_.primary(),
1241 key,
1242 value,
1243 last_transaction_id_);
Wyatt Heplerd2298282020-02-20 17:12:45 -08001244}
1245
Wyatt Hepler7ded6da2020-03-11 18:24:43 -07001246void KeyValueStore::LogDebugInfo() const {
Keir Mierle8c352dc2020-02-02 13:58:19 -08001247 const size_t sector_size_bytes = partition_.sector_size_bytes();
1248 DBG("====================== KEY VALUE STORE DUMP =========================");
1249 DBG(" ");
1250 DBG("Flash partition:");
David Rogers9fc78b82020-06-12 13:56:12 -07001251 DBG(" Sector count = %u", unsigned(partition_.sector_count()));
1252 DBG(" Sector max count = %u", unsigned(sectors_.max_size()));
1253 DBG(" Sectors in use = %u", unsigned(sectors_.size()));
1254 DBG(" Sector size = %u", unsigned(sector_size_bytes));
1255 DBG(" Total size = %u", unsigned(partition_.size_bytes()));
1256 DBG(" Alignment = %u", unsigned(partition_.alignment_bytes()));
Keir Mierle8c352dc2020-02-02 13:58:19 -08001257 DBG(" ");
1258 DBG("Key descriptors:");
David Rogers9fc78b82020-06-12 13:56:12 -07001259 DBG(" Entry count = %u", unsigned(entry_cache_.total_entries()));
1260 DBG(" Max entry count = %u", unsigned(entry_cache_.max_entries()));
Keir Mierle8c352dc2020-02-02 13:58:19 -08001261 DBG(" ");
1262 DBG(" # hash version address address (hex)");
Armando Montanez888370d2020-05-01 18:29:22 -07001263 size_t count = 0;
Wyatt Hepler7ded6da2020-03-11 18:24:43 -07001264 for (const EntryMetadata& metadata : entry_cache_) {
Keir Mierle8c352dc2020-02-02 13:58:19 -08001265 DBG(" |%3zu: | %8zx |%8zu | %8zu | %8zx",
Armando Montanez888370d2020-05-01 18:29:22 -07001266 count++,
Wyatt Hepler7ded6da2020-03-11 18:24:43 -07001267 size_t(metadata.hash()),
1268 size_t(metadata.transaction_id()),
1269 size_t(metadata.first_address()),
1270 size_t(metadata.first_address()));
Keir Mierle8c352dc2020-02-02 13:58:19 -08001271 }
1272 DBG(" ");
1273
1274 DBG("Sector descriptors:");
1275 DBG(" # tail free valid has_space");
Wyatt Heplerc84393f2020-03-20 11:23:24 -07001276 for (const SectorDescriptor& sd : sectors_) {
1277 DBG(" |%3u: | %8zu |%8zu | %s",
1278 sectors_.Index(sd),
Wyatt Hepler2c7eca02020-02-18 16:01:42 -08001279 size_t(sd.writable_bytes()),
1280 sd.valid_bytes(),
1281 sd.writable_bytes() ? "YES" : "");
Keir Mierle8c352dc2020-02-02 13:58:19 -08001282 }
1283 DBG(" ");
1284
1285 // TODO: This should stop logging after some threshold.
1286 // size_t dumped_bytes = 0;
1287 DBG("Sector raw data:");
Wyatt Hepler1c329ca2020-02-07 18:07:23 -08001288 for (size_t sector_id = 0; sector_id < sectors_.size(); ++sector_id) {
Keir Mierle8c352dc2020-02-02 13:58:19 -08001289 // Read sector data. Yes, this will blow the stack on embedded.
Wyatt Hepler1c329ca2020-02-07 18:07:23 -08001290 std::array<byte, 500> raw_sector_data; // TODO!!!
Keir Mierle8c352dc2020-02-02 13:58:19 -08001291 StatusWithSize sws =
1292 partition_.Read(sector_id * sector_size_bytes, raw_sector_data);
David Rogers9fc78b82020-06-12 13:56:12 -07001293 DBG("Read: %u bytes", unsigned(sws.size()));
Keir Mierle8c352dc2020-02-02 13:58:19 -08001294
1295 DBG(" base addr offs 0 1 2 3 4 5 6 7");
1296 for (size_t i = 0; i < sector_size_bytes; i += 8) {
1297 DBG(" %3zu %8zx %5zu | %02x %02x %02x %02x %02x %02x %02x %02x",
1298 sector_id,
1299 (sector_id * sector_size_bytes) + i,
1300 i,
1301 static_cast<unsigned int>(raw_sector_data[i + 0]),
1302 static_cast<unsigned int>(raw_sector_data[i + 1]),
1303 static_cast<unsigned int>(raw_sector_data[i + 2]),
1304 static_cast<unsigned int>(raw_sector_data[i + 3]),
1305 static_cast<unsigned int>(raw_sector_data[i + 4]),
1306 static_cast<unsigned int>(raw_sector_data[i + 5]),
1307 static_cast<unsigned int>(raw_sector_data[i + 6]),
1308 static_cast<unsigned int>(raw_sector_data[i + 7]));
1309
1310 // TODO: Fix exit condition.
1311 if (i > 128) {
1312 break;
1313 }
1314 }
1315 DBG(" ");
1316 }
1317
1318 DBG("////////////////////// KEY VALUE STORE DUMP END /////////////////////");
1319}
1320
David Rogerscf680ab2020-02-12 23:28:32 -08001321void KeyValueStore::LogSectors() const {
David Rogers9fc78b82020-06-12 13:56:12 -07001322 DBG("Sector descriptors: count %u", unsigned(sectors_.size()));
Wyatt Hepler1c329ca2020-02-07 18:07:23 -08001323 for (auto& sector : sectors_) {
David Rogers9fc78b82020-06-12 13:56:12 -07001324 DBG(" - Sector %u: valid %u, recoverable %u, free %u",
Wyatt Heplerc84393f2020-03-20 11:23:24 -07001325 sectors_.Index(sector),
David Rogers9fc78b82020-06-12 13:56:12 -07001326 unsigned(sector.valid_bytes()),
1327 unsigned(sector.RecoverableBytes(partition_.sector_size_bytes())),
1328 unsigned(sector.writable_bytes()));
David Rogers50185ad2020-02-07 00:02:46 -08001329 }
1330}
1331
David Rogerscf680ab2020-02-12 23:28:32 -08001332void KeyValueStore::LogKeyDescriptor() const {
David Rogers9fc78b82020-06-12 13:56:12 -07001333 DBG("Key descriptors: count %u", unsigned(entry_cache_.total_entries()));
David Rogers9abe3c72020-03-24 19:03:13 -07001334 for (const EntryMetadata& metadata : entry_cache_) {
David Rogers9fc78b82020-06-12 13:56:12 -07001335 DBG(" - Key: %s, hash %#x, transaction ID %u, first address %#x",
Wyatt Hepler02946272020-03-18 10:36:22 -07001336 metadata.state() == EntryState::kDeleted ? "Deleted" : "Valid",
David Rogers9fc78b82020-06-12 13:56:12 -07001337 unsigned(metadata.hash()),
1338 unsigned(metadata.transaction_id()),
1339 unsigned(metadata.first_address()));
David Rogerscf680ab2020-02-12 23:28:32 -08001340 }
1341}
1342
Wyatt Hepler2ad60672020-01-21 08:00:16 -08001343} // namespace pw::kvs