blob: d39711738b2d9175462cd6e124c04e09e9f3f899 [file] [log] [blame]
Wyatt Heplerb7609542020-01-24 10:29:54 -08001// Copyright 2020 The Pigweed Authors
2//
3// Licensed under the Apache License, Version 2.0 (the "License"); you may not
4// use this file except in compliance with the License. You may obtain a copy of
5// the License at
6//
7// https://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
11// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12// License for the specific language governing permissions and limitations under
13// the License.
14
Wyatt Heplerb7609542020-01-24 10:29:54 -080015#include "pw_kvs/key_value_store.h"
16
Wyatt Heplerbab0e202020-02-04 07:40:08 -080017#include <algorithm>
Wyatt Hepler5a33d8c2020-02-06 09:32:58 -080018#include <cinttypes>
Wyatt Heplerb7609542020-01-24 10:29:54 -080019#include <cstring>
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -080020#include <type_traits>
Wyatt Heplerb7609542020-01-24 10:29:54 -080021
Keir Mierle8c352dc2020-02-02 13:58:19 -080022#define PW_LOG_USE_ULTRA_SHORT_NAMES 1
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -080023#include "pw_kvs_private/macros.h"
Keir Mierle8c352dc2020-02-02 13:58:19 -080024#include "pw_log/log.h"
Wyatt Heplerb7609542020-01-24 10:29:54 -080025
Wyatt Hepler2ad60672020-01-21 08:00:16 -080026namespace pw::kvs {
Wyatt Heplera00d1ef2020-02-14 14:31:26 -080027namespace {
Wyatt Heplerb7609542020-01-24 10:29:54 -080028
Wyatt Hepleracaacf92020-01-24 10:58:30 -080029using std::byte;
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -080030using std::string_view;
Wyatt Hepleracaacf92020-01-24 10:58:30 -080031
Wyatt Heplera00d1ef2020-02-14 14:31:26 -080032constexpr bool InvalidKey(std::string_view key) {
Wyatt Heplerbdd8e5a2020-02-20 19:27:26 -080033 return key.empty() || (key.size() > internal::Entry::kMaxKeyLength);
Wyatt Heplera00d1ef2020-02-14 14:31:26 -080034}
35
36} // namespace
37
Wyatt Heplerad0a7932020-02-06 08:20:38 -080038KeyValueStore::KeyValueStore(FlashPartition* partition,
Wyatt Hepler22d0d9f2020-03-05 14:57:11 -080039 span<const EntryFormat> formats,
Wyatt Hepler7ded6da2020-03-11 18:24:43 -070040 const Options& options,
41 size_t redundancy,
42 Vector<SectorDescriptor>& sector_descriptor_list,
43 const SectorDescriptor** temp_sectors_to_skip,
44 Vector<KeyDescriptor>& key_descriptor_list,
45 Address* addresses)
Wyatt Heplerad0a7932020-02-06 08:20:38 -080046 : partition_(*partition),
Wyatt Hepler22d0d9f2020-03-05 14:57:11 -080047 formats_(formats),
Wyatt Heplerc84393f2020-03-20 11:23:24 -070048 sectors_(sector_descriptor_list, *partition, temp_sectors_to_skip),
Wyatt Hepler7ded6da2020-03-11 18:24:43 -070049 entry_cache_(key_descriptor_list, addresses, redundancy),
David Rogers49766d92020-03-20 10:55:54 -070050 options_(options),
David Rogers9abe3c72020-03-24 19:03:13 -070051 initialized_(InitializationState::kNotInitialized),
David Rogers49766d92020-03-20 10:55:54 -070052 error_detected_(false),
David Rogers9abe3c72020-03-24 19:03:13 -070053 error_stats_({}),
David Rogers49766d92020-03-20 10:55:54 -070054 last_transaction_id_(0) {}
Wyatt Heplerad0a7932020-02-06 08:20:38 -080055
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -080056Status KeyValueStore::Init() {
David Rogers9abe3c72020-03-24 19:03:13 -070057 initialized_ = InitializationState::kNotInitialized;
David Rogers49766d92020-03-20 10:55:54 -070058 error_detected_ = false;
Keir Mierlebf904812020-03-11 17:28:22 -070059 last_transaction_id_ = 0;
Wyatt Heplerd2298282020-02-20 17:12:45 -080060
David Rogers2e9e0c82020-02-13 15:06:06 -080061 INF("Initializing key value store");
Wyatt Hepler38ce30f2020-02-19 11:48:31 -080062 if (partition_.sector_count() > sectors_.max_size()) {
David Rogers2e9e0c82020-02-13 15:06:06 -080063 ERR("KVS init failed: kMaxUsableSectors (=%zu) must be at least as "
64 "large as the number of sectors in the flash partition (=%zu)",
Wyatt Hepler38ce30f2020-02-19 11:48:31 -080065 sectors_.max_size(),
David Rogers2e9e0c82020-02-13 15:06:06 -080066 partition_.sector_count());
Wyatt Heplerad0a7932020-02-06 08:20:38 -080067 return Status::FAILED_PRECONDITION;
68 }
69
Keir Mierle8c352dc2020-02-02 13:58:19 -080070 const size_t sector_size_bytes = partition_.sector_size_bytes();
Keir Mierle8c352dc2020-02-02 13:58:19 -080071
David Rogers49766d92020-03-20 10:55:54 -070072 // TODO: investigate doing this as a static assert/compile-time check.
73 if (sector_size_bytes > SectorDescriptor::max_sector_size()) {
74 ERR("KVS init failed: sector_size_bytes (=%zu) is greater than maximum "
75 "allowed sector size (=%zu)",
76 sector_size_bytes,
77 SectorDescriptor::max_sector_size());
78 return Status::FAILED_PRECONDITION;
79 }
80
David Rogersfcea3252020-04-07 14:56:35 -070081 InitializeMetadata();
82
83 if (!error_detected_) {
84 initialized_ = InitializationState::kReady;
85 } else {
86 if (options_.recovery != ErrorRecovery::kManual) {
87 Status recovery_status = FixErrors();
88
89 if (recovery_status.ok()) {
90 WRN("KVS init: Corruption detected and fully repaired");
91 initialized_ = InitializationState::kReady;
92 } else if (recovery_status == Status::RESOURCE_EXHAUSTED) {
93 WRN("KVS init: Unable to maintain required free sector");
94 initialized_ = InitializationState::kNeedsMaintenance;
95 } else {
96 WRN("KVS init: Corruption detected and unable repair");
97 initialized_ = InitializationState::kNeedsMaintenance;
98 }
99 } else {
100 WRN("KVS init: Corruption detected, no repair attempted due to options");
101 initialized_ = InitializationState::kNeedsMaintenance;
102 }
103 }
104
105 INF("KeyValueStore init complete: active keys %zu, deleted keys %zu, sectors "
106 "%zu, logical sector size %zu bytes",
107 size(),
108 (entry_cache_.total_entries() - size()),
109 sectors_.size(),
110 partition_.sector_size_bytes());
111
112 // Report any corruption was not repaired.
113 if (error_detected_) {
114 WRN("KVS init: Corruption found but not repaired, KVS unavailable until "
115 "successful maintenance.");
116 return Status::DATA_LOSS;
117 }
118
119 return Status::OK;
120}
121
122void KeyValueStore::InitializeMetadata() {
123 const size_t sector_size_bytes = partition_.sector_size_bytes();
124
125 sectors_.Reset();
126 entry_cache_.Reset();
127
Keir Mierle8c352dc2020-02-02 13:58:19 -0800128 DBG("First pass: Read all entries from all sectors");
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800129 Address sector_address = 0;
Keir Mierle8c352dc2020-02-02 13:58:19 -0800130
Alexei Frolovd4adf912020-02-21 13:29:15 -0800131 size_t total_corrupt_bytes = 0;
132 int corrupt_entries = 0;
David Rogers91627482020-02-27 17:38:12 -0800133 bool empty_sector_found = false;
Alexei Frolovd4adf912020-02-21 13:29:15 -0800134
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800135 for (SectorDescriptor& sector : sectors_) {
Keir Mierle8c352dc2020-02-02 13:58:19 -0800136 Address entry_address = sector_address;
137
Alexei Frolovd4adf912020-02-21 13:29:15 -0800138 size_t sector_corrupt_bytes = 0;
139
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800140 for (int num_entries_in_sector = 0; true; num_entries_in_sector++) {
David Rogersfcea3252020-04-07 14:56:35 -0700141 DBG("Load entry: sector=%u, entry#=%d, address=%u",
142 unsigned(sector_address),
Keir Mierle8c352dc2020-02-02 13:58:19 -0800143 num_entries_in_sector,
David Rogersfcea3252020-04-07 14:56:35 -0700144 unsigned(entry_address));
Keir Mierle8c352dc2020-02-02 13:58:19 -0800145
Wyatt Heplerc84393f2020-03-20 11:23:24 -0700146 if (!sectors_.AddressInSector(sector, entry_address)) {
Keir Mierle8c352dc2020-02-02 13:58:19 -0800147 DBG("Fell off end of sector; moving to the next sector");
148 break;
149 }
150
151 Address next_entry_address;
152 Status status = LoadEntry(entry_address, &next_entry_address);
153 if (status == Status::NOT_FOUND) {
154 DBG("Hit un-written data in sector; moving to the next sector");
155 break;
David Rogersfcea3252020-04-07 14:56:35 -0700156 } else if (!status.ok()) {
157 // The entry could not be read, indicating likely data corruption within
158 // the sector. Try to scan the remainder of the sector for other
159 // entries.
Alexei Frolovd4adf912020-02-21 13:29:15 -0800160
David Rogers49766d92020-03-20 10:55:54 -0700161 error_detected_ = true;
Alexei Frolovd4adf912020-02-21 13:29:15 -0800162 corrupt_entries++;
163
164 status = ScanForEntry(sector,
165 entry_address + Entry::kMinAlignmentBytes,
166 &next_entry_address);
David Rogersfcea3252020-04-07 14:56:35 -0700167 if (!status.ok()) {
Alexei Frolovd4adf912020-02-21 13:29:15 -0800168 // No further entries in this sector. Mark the remaining bytes in the
169 // sector as corrupt (since we can't reliably know the size of the
170 // corrupt entry).
171 sector_corrupt_bytes +=
172 sector_size_bytes - (entry_address - sector_address);
173 break;
174 }
175
Alexei Frolovd4adf912020-02-21 13:29:15 -0800176 sector_corrupt_bytes += next_entry_address - entry_address;
Keir Mierle8c352dc2020-02-02 13:58:19 -0800177 }
Keir Mierle8c352dc2020-02-02 13:58:19 -0800178
179 // Entry loaded successfully; so get ready to load the next one.
180 entry_address = next_entry_address;
181
182 // Update of the number of writable bytes in this sector.
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800183 sector.set_writable_bytes(sector_size_bytes -
184 (entry_address - sector_address));
Keir Mierle8c352dc2020-02-02 13:58:19 -0800185 }
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800186
Alexei Frolovd4adf912020-02-21 13:29:15 -0800187 if (sector_corrupt_bytes > 0) {
188 // If the sector contains corrupt data, prevent any further entries from
189 // being written to it by indicating that it has no space. This should
190 // also make it a decent GC candidate. Valid keys in the sector are still
191 // readable as normal.
David Rogers49766d92020-03-20 10:55:54 -0700192 sector.mark_corrupt();
193 error_detected_ = true;
Alexei Frolovd4adf912020-02-21 13:29:15 -0800194
195 WRN("Sector %u contains %zuB of corrupt data",
Wyatt Heplerc84393f2020-03-20 11:23:24 -0700196 sectors_.Index(sector),
Alexei Frolovd4adf912020-02-21 13:29:15 -0800197 sector_corrupt_bytes);
198 }
199
David Rogers91627482020-02-27 17:38:12 -0800200 if (sector.Empty(sector_size_bytes)) {
201 empty_sector_found = true;
202 }
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800203 sector_address += sector_size_bytes;
Alexei Frolovd4adf912020-02-21 13:29:15 -0800204 total_corrupt_bytes += sector_corrupt_bytes;
Keir Mierle8c352dc2020-02-02 13:58:19 -0800205 }
206
207 DBG("Second pass: Count valid bytes in each sector");
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700208 Address newest_key = 0;
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800209
David Rogers98fea472020-04-01 15:43:48 -0700210 // For every valid entry, for each address, count the valid bytes in that
211 // sector. If the address fails to read, remove the address and mark the
212 // sector as corrupt. Track which entry has the newest transaction ID for
213 // initializing last_new_sector_.
214 for (EntryMetadata& metadata : entry_cache_) {
David Rogers49766d92020-03-20 10:55:54 -0700215 if (metadata.addresses().size() < redundancy()) {
David Rogers31b358b2020-04-15 05:00:50 -0700216 DBG("Key 0x%08x missing copies, has %u, needs %u",
217 unsigned(metadata.hash()),
218 unsigned(metadata.addresses().size()),
219 unsigned(redundancy()));
David Rogers49766d92020-03-20 10:55:54 -0700220 error_detected_ = true;
221 }
David Rogers98fea472020-04-01 15:43:48 -0700222 size_t index = 0;
223 while (index < metadata.addresses().size()) {
224 Address address = metadata.addresses()[index];
David Rogersf56131c2020-03-04 10:19:22 -0800225 Entry entry;
David Rogers98fea472020-04-01 15:43:48 -0700226
227 Status read_result = Entry::Read(partition_, address, formats_, &entry);
228
229 SectorDescriptor& sector = sectors_.FromAddress(address);
230
231 if (read_result.ok()) {
232 sector.AddValidBytes(entry.size());
233 index++;
234 } else {
235 corrupt_entries++;
236 total_corrupt_bytes += sector.writable_bytes();
237 error_detected_ = true;
238 sector.mark_corrupt();
239
240 // Remove the bad address and stay at this index. The removal
241 // replaces out the removed address with the back address so
242 // this index needs to be rechecked with the new address.
243 metadata.RemoveAddress(address);
244 }
David Rogersf56131c2020-03-04 10:19:22 -0800245 }
David Rogers98fea472020-04-01 15:43:48 -0700246
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700247 if (metadata.IsNewerThan(last_transaction_id_)) {
248 last_transaction_id_ = metadata.transaction_id();
249 newest_key = metadata.addresses().back();
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800250 }
Keir Mierle8c352dc2020-02-02 13:58:19 -0800251 }
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800252
Wyatt Heplerc84393f2020-03-20 11:23:24 -0700253 sectors_.set_last_new_sector(newest_key);
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800254
David Rogers91627482020-02-27 17:38:12 -0800255 if (!empty_sector_found) {
David Rogers31b358b2020-04-15 05:00:50 -0700256 DBG("No empty sector found");
David Rogers9abe3c72020-03-24 19:03:13 -0700257 error_detected_ = true;
David Rogers91627482020-02-27 17:38:12 -0800258 }
259
David Rogers31b358b2020-04-15 05:00:50 -0700260 if (error_detected_) {
David Rogersfcea3252020-04-07 14:56:35 -0700261 WRN("Corruption detected. Found %zu corrupt bytes and %d corrupt entries.",
262 total_corrupt_bytes,
263 corrupt_entries);
David Rogers9abe3c72020-03-24 19:03:13 -0700264 }
Keir Mierle8c352dc2020-02-02 13:58:19 -0800265}
266
Alexei Frolov9e235832020-02-24 12:44:45 -0800267KeyValueStore::StorageStats KeyValueStore::GetStorageStats() const {
David Rogers9abe3c72020-03-24 19:03:13 -0700268 StorageStats stats{};
Alexei Frolov9e235832020-02-24 12:44:45 -0800269 const size_t sector_size = partition_.sector_size_bytes();
270 bool found_empty_sector = false;
David Rogers9abe3c72020-03-24 19:03:13 -0700271 stats.corrupt_sectors_recovered = error_stats_.corrupt_sectors_recovered;
272 stats.missing_redundant_entries_recovered =
273 error_stats_.missing_redundant_entries_recovered;
Alexei Frolov9e235832020-02-24 12:44:45 -0800274
275 for (const SectorDescriptor& sector : sectors_) {
276 stats.in_use_bytes += sector.valid_bytes();
277 stats.reclaimable_bytes += sector.RecoverableBytes(sector_size);
278
279 if (!found_empty_sector && sector.Empty(sector_size)) {
280 // The KVS tries to always keep an empty sector for GC, so don't count
281 // the first empty sector seen as writable space. However, a free sector
282 // cannot always be assumed to exist; if a GC operation fails, all sectors
283 // may be partially written, in which case the space reported might be
284 // inaccurate.
285 found_empty_sector = true;
286 continue;
287 }
288
289 stats.writable_bytes += sector.writable_bytes();
290 }
291
292 return stats;
293}
294
David Rogers98fea472020-04-01 15:43:48 -0700295// Check KVS for any error conditions. Primarily intended for test and
296// internal use.
David Rogers9abe3c72020-03-24 19:03:13 -0700297bool KeyValueStore::CheckForErrors() {
298 // Check for corrupted sectors
299 for (SectorDescriptor& sector : sectors_) {
300 if (sector.corrupt()) {
301 error_detected_ = true;
David Rogers98fea472020-04-01 15:43:48 -0700302 return error_detected();
David Rogers9abe3c72020-03-24 19:03:13 -0700303 }
304 }
305
306 // Check for missing redundancy.
307 if (redundancy() > 1) {
308 for (const EntryMetadata& metadata : entry_cache_) {
309 if (metadata.addresses().size() < redundancy()) {
310 error_detected_ = true;
David Rogers98fea472020-04-01 15:43:48 -0700311 return error_detected();
David Rogers9abe3c72020-03-24 19:03:13 -0700312 }
313 }
314 }
315
316 return error_detected();
317}
318
Keir Mierle8c352dc2020-02-02 13:58:19 -0800319Status KeyValueStore::LoadEntry(Address entry_address,
320 Address* next_entry_address) {
Wyatt Heplere541e072020-02-14 09:10:53 -0800321 Entry entry;
Wyatt Hepler22d0d9f2020-03-05 14:57:11 -0800322 TRY(Entry::Read(partition_, entry_address, formats_, &entry));
Keir Mierle8c352dc2020-02-02 13:58:19 -0800323
324 // Read the key from flash & validate the entry (which reads the value).
Wyatt Heplera00d1ef2020-02-14 14:31:26 -0800325 Entry::KeyBuffer key_buffer;
Wyatt Heplere541e072020-02-14 09:10:53 -0800326 TRY_ASSIGN(size_t key_length, entry.ReadKey(key_buffer));
327 const string_view key(key_buffer.data(), key_length);
Wyatt Heplerbab0e202020-02-04 07:40:08 -0800328
Wyatt Hepler22d0d9f2020-03-05 14:57:11 -0800329 TRY(entry.VerifyChecksumInFlash());
David Rogersf56131c2020-03-04 10:19:22 -0800330
331 // A valid entry was found, so update the next entry address before doing any
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700332 // of the checks that happen in AddNewOrUpdateExisting.
David Rogersf56131c2020-03-04 10:19:22 -0800333 *next_entry_address = entry.next_address();
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700334 return entry_cache_.AddNewOrUpdateExisting(
335 entry.descriptor(key), entry.address(), partition_.sector_size_bytes());
Keir Mierle8c352dc2020-02-02 13:58:19 -0800336}
337
Alexei Frolovd4adf912020-02-21 13:29:15 -0800338// Scans flash memory within a sector to find a KVS entry magic.
Alexei Frolovd4adf912020-02-21 13:29:15 -0800339Status KeyValueStore::ScanForEntry(const SectorDescriptor& sector,
340 Address start_address,
341 Address* next_entry_address) {
David Rogersfcea3252020-04-07 14:56:35 -0700342 DBG("Scanning sector %u for entries starting from address %u",
Wyatt Heplerc84393f2020-03-20 11:23:24 -0700343 sectors_.Index(sector),
David Rogersfcea3252020-04-07 14:56:35 -0700344 unsigned(start_address));
Alexei Frolovd4adf912020-02-21 13:29:15 -0800345
346 // Entries must start at addresses which are aligned on a multiple of
347 // Entry::kMinAlignmentBytes. However, that multiple can vary between entries.
348 // When scanning, we don't have an entry to tell us what the current alignment
349 // is, so the minimum alignment is used to be exhaustive.
350 for (Address address = AlignUp(start_address, Entry::kMinAlignmentBytes);
Wyatt Heplerc84393f2020-03-20 11:23:24 -0700351 sectors_.AddressInSector(sector, address);
Alexei Frolovd4adf912020-02-21 13:29:15 -0800352 address += Entry::kMinAlignmentBytes) {
Alexei Frolovd4adf912020-02-21 13:29:15 -0800353 uint32_t magic;
David Rogersfcea3252020-04-07 14:56:35 -0700354 StatusWithSize read_result =
355 partition_.Read(address, as_writable_bytes(span(&magic, 1)));
356 if (!read_result.ok()) {
357 continue;
358 }
Wyatt Hepler22d0d9f2020-03-05 14:57:11 -0800359 if (formats_.KnownMagic(magic)) {
David Rogersfcea3252020-04-07 14:56:35 -0700360 DBG("Found entry magic at address %u", unsigned(address));
Alexei Frolovd4adf912020-02-21 13:29:15 -0800361 *next_entry_address = address;
362 return Status::OK;
363 }
364 }
365
366 return Status::NOT_FOUND;
367}
368
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800369StatusWithSize KeyValueStore::Get(string_view key,
Wyatt Hepler5f6efc02020-02-18 16:54:31 -0800370 span<byte> value_buffer,
371 size_t offset_bytes) const {
David Rogers9abe3c72020-03-24 19:03:13 -0700372 TRY_WITH_SIZE(CheckReadOperation(key));
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800373
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700374 EntryMetadata metadata;
David Rogers98fea472020-04-01 15:43:48 -0700375 TRY_WITH_SIZE(FindExisting(key, &metadata));
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800376
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700377 return Get(key, metadata, value_buffer, offset_bytes);
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800378}
379
Wyatt Heplerfac81132020-02-27 17:26:33 -0800380Status KeyValueStore::PutBytes(string_view key, span<const byte> value) {
David Rogers9abe3c72020-03-24 19:03:13 -0700381 TRY(CheckWriteOperation(key));
Keir Mierle8c352dc2020-02-02 13:58:19 -0800382 DBG("Writing key/value; key length=%zu, value length=%zu",
383 key.size(),
384 value.size());
Wyatt Hepler729f28c2020-02-05 09:46:00 -0800385
Wyatt Hepler5406a672020-02-18 15:42:38 -0800386 if (Entry::size(partition_, key, value) > partition_.sector_size_bytes()) {
387 DBG("%zu B value with %zu B key cannot fit in one sector",
388 value.size(),
389 key.size());
390 return Status::INVALID_ARGUMENT;
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800391 }
392
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700393 EntryMetadata metadata;
David Rogers98fea472020-04-01 15:43:48 -0700394 Status status = FindEntry(key, &metadata);
Wyatt Hepler2d401692020-02-13 16:01:23 -0800395
396 if (status.ok()) {
David Rogersf56131c2020-03-04 10:19:22 -0800397 // TODO: figure out logging how to support multiple addresses.
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700398 DBG("Overwriting entry for key 0x%08" PRIx32 " in %zu sectors including %u",
399 metadata.hash(),
400 metadata.addresses().size(),
Wyatt Heplerc84393f2020-03-20 11:23:24 -0700401 sectors_.Index(metadata.first_address()));
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700402 return WriteEntryForExistingKey(metadata, EntryState::kValid, key, value);
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800403 }
David Rogers2761aeb2020-01-31 17:09:00 -0800404
Wyatt Hepler2d401692020-02-13 16:01:23 -0800405 if (status == Status::NOT_FOUND) {
406 return WriteEntryForNewKey(key, value);
407 }
408
409 return status;
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800410}
411
412Status KeyValueStore::Delete(string_view key) {
David Rogers9abe3c72020-03-24 19:03:13 -0700413 TRY(CheckWriteOperation(key));
Wyatt Hepler729f28c2020-02-05 09:46:00 -0800414
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700415 EntryMetadata metadata;
David Rogers98fea472020-04-01 15:43:48 -0700416 TRY(FindExisting(key, &metadata));
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800417
David Rogersf56131c2020-03-04 10:19:22 -0800418 // TODO: figure out logging how to support multiple addresses.
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700419 DBG("Writing tombstone for key 0x%08" PRIx32 " in %zu sectors including %u",
420 metadata.hash(),
421 metadata.addresses().size(),
Wyatt Heplerc84393f2020-03-20 11:23:24 -0700422 sectors_.Index(metadata.first_address()));
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700423 return WriteEntryForExistingKey(metadata, EntryState::kDeleted, key, {});
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800424}
425
Wyatt Hepler08d37d82020-02-27 15:45:37 -0800426void KeyValueStore::Item::ReadKey() {
427 key_buffer_.fill('\0');
428
429 Entry entry;
David Rogers98fea472020-04-01 15:43:48 -0700430 if (kvs_.ReadEntry(*iterator_, entry).ok()) {
Wyatt Hepler08d37d82020-02-27 15:45:37 -0800431 entry.ReadKey(key_buffer_);
432 }
433}
434
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800435KeyValueStore::iterator& KeyValueStore::iterator::operator++() {
436 // Skip to the next entry that is valid (not deleted).
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700437 while (++item_.iterator_ != item_.kvs_.entry_cache_.end() &&
Wyatt Hepler02946272020-03-18 10:36:22 -0700438 item_.iterator_->state() != EntryState::kValid) {
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800439 }
440 return *this;
441}
442
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800443KeyValueStore::iterator KeyValueStore::begin() const {
Wyatt Heplerbfc6a522020-04-01 16:30:24 -0700444 internal::EntryCache::const_iterator cache_iterator = entry_cache_.begin();
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800445 // Skip over any deleted entries at the start of the descriptor list.
Wyatt Hepler02946272020-03-18 10:36:22 -0700446 while (cache_iterator != entry_cache_.end() &&
447 cache_iterator->state() != EntryState::kValid) {
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700448 ++cache_iterator;
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800449 }
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700450 return iterator(*this, cache_iterator);
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800451}
452
Wyatt Heplerab3b2492020-03-11 16:15:16 -0700453StatusWithSize KeyValueStore::ValueSize(string_view key) const {
David Rogers9abe3c72020-03-24 19:03:13 -0700454 TRY_WITH_SIZE(CheckReadOperation(key));
Wyatt Heplered163b02020-02-03 17:49:32 -0800455
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700456 EntryMetadata metadata;
David Rogers98fea472020-04-01 15:43:48 -0700457 TRY_WITH_SIZE(FindExisting(key, &metadata));
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800458
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700459 return ValueSize(metadata);
Wyatt Heplerfac81132020-02-27 17:26:33 -0800460}
Wyatt Heplered163b02020-02-03 17:49:32 -0800461
David Rogers98fea472020-04-01 15:43:48 -0700462Status KeyValueStore::ReadEntry(const EntryMetadata& metadata,
463 Entry& entry) const {
464 // Try to read an entry
465 Status read_result = Status::DATA_LOSS;
466 for (Address address : metadata.addresses()) {
467 read_result = Entry::Read(partition_, address, formats_, &entry);
468 if (read_result.ok()) {
469 return read_result;
470 }
471
472 // Found a bad address. Set the sector as corrupt.
473 error_detected_ = true;
474 sectors_.FromAddress(address).mark_corrupt();
475 }
476
477 ERR("No valid entries for key. Data has been lost!");
478 return read_result;
479}
480
481Status KeyValueStore::FindEntry(string_view key,
482 EntryMetadata* found_entry) const {
483 StatusWithSize find_result =
484 entry_cache_.Find(partition_, sectors_, formats_, key, found_entry);
485
486 if (find_result.size() > 0u) {
487 error_detected_ = true;
488 }
489 return find_result.status();
490}
491
492Status KeyValueStore::FindExisting(string_view key,
493 EntryMetadata* metadata) const {
494 Status status = FindEntry(key, metadata);
495
496 // If the key's hash collides with an existing key or if the key is deleted,
497 // treat it as if it is not in the KVS.
498 if (status == Status::ALREADY_EXISTS ||
499 (status.ok() && metadata->state() == EntryState::kDeleted)) {
500 return Status::NOT_FOUND;
501 }
502 return status;
503}
504
Wyatt Heplerfac81132020-02-27 17:26:33 -0800505StatusWithSize KeyValueStore::Get(string_view key,
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700506 const EntryMetadata& metadata,
Wyatt Heplerfac81132020-02-27 17:26:33 -0800507 span<std::byte> value_buffer,
508 size_t offset_bytes) const {
509 Entry entry;
David Rogers98fea472020-04-01 15:43:48 -0700510
511 TRY_WITH_SIZE(ReadEntry(metadata, entry));
Wyatt Heplerfac81132020-02-27 17:26:33 -0800512
513 StatusWithSize result = entry.ReadValue(value_buffer, offset_bytes);
514 if (result.ok() && options_.verify_on_read && offset_bytes == 0u) {
Wyatt Hepler22d0d9f2020-03-05 14:57:11 -0800515 Status verify_result =
516 entry.VerifyChecksum(key, value_buffer.first(result.size()));
Wyatt Heplerfac81132020-02-27 17:26:33 -0800517 if (!verify_result.ok()) {
518 std::memset(value_buffer.data(), 0, result.size());
519 return StatusWithSize(verify_result, 0);
520 }
521
522 return StatusWithSize(verify_result, result.size());
523 }
524 return result;
Wyatt Heplered163b02020-02-03 17:49:32 -0800525}
526
Wyatt Hepler6e3a83b2020-02-04 07:36:45 -0800527Status KeyValueStore::FixedSizeGet(std::string_view key,
Wyatt Heplerfac81132020-02-27 17:26:33 -0800528 void* value,
529 size_t size_bytes) const {
David Rogers9abe3c72020-03-24 19:03:13 -0700530 TRY(CheckWriteOperation(key));
Wyatt Heplerfac81132020-02-27 17:26:33 -0800531
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700532 EntryMetadata metadata;
David Rogers98fea472020-04-01 15:43:48 -0700533 TRY(FindExisting(key, &metadata));
Wyatt Heplerfac81132020-02-27 17:26:33 -0800534
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700535 return FixedSizeGet(key, metadata, value, size_bytes);
Wyatt Heplerfac81132020-02-27 17:26:33 -0800536}
537
538Status KeyValueStore::FixedSizeGet(std::string_view key,
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700539 const EntryMetadata& metadata,
Wyatt Heplerfac81132020-02-27 17:26:33 -0800540 void* value,
Wyatt Hepler6e3a83b2020-02-04 07:36:45 -0800541 size_t size_bytes) const {
542 // Ensure that the size of the stored value matches the size of the type.
543 // Otherwise, report error. This check avoids potential memory corruption.
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700544 TRY_ASSIGN(const size_t actual_size, ValueSize(metadata));
Wyatt Heplerfac81132020-02-27 17:26:33 -0800545
546 if (actual_size != size_bytes) {
547 DBG("Requested %zu B read, but value is %zu B", size_bytes, actual_size);
Wyatt Hepler6e3a83b2020-02-04 07:36:45 -0800548 return Status::INVALID_ARGUMENT;
Wyatt Heplerbab0e202020-02-04 07:40:08 -0800549 }
Wyatt Heplerfac81132020-02-27 17:26:33 -0800550
551 StatusWithSize result =
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700552 Get(key, metadata, span(static_cast<byte*>(value), size_bytes), 0);
Wyatt Heplerfac81132020-02-27 17:26:33 -0800553
554 return result.status();
555}
556
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700557StatusWithSize KeyValueStore::ValueSize(const EntryMetadata& metadata) const {
Wyatt Heplerfac81132020-02-27 17:26:33 -0800558 Entry entry;
David Rogers98fea472020-04-01 15:43:48 -0700559 TRY_WITH_SIZE(ReadEntry(metadata, entry));
Wyatt Heplerfac81132020-02-27 17:26:33 -0800560
561 return StatusWithSize(entry.value_size());
Keir Mierle8c352dc2020-02-02 13:58:19 -0800562}
563
David Rogers9abe3c72020-03-24 19:03:13 -0700564Status KeyValueStore::CheckWriteOperation(string_view key) const {
Wyatt Hepleracaacf92020-01-24 10:58:30 -0800565 if (InvalidKey(key)) {
Wyatt Heplerb7609542020-01-24 10:29:54 -0800566 return Status::INVALID_ARGUMENT;
567 }
David Rogers9abe3c72020-03-24 19:03:13 -0700568
569 // For normal write operation the KVS must be fully ready.
Wyatt Heplerd2298282020-02-20 17:12:45 -0800570 if (!initialized()) {
Wyatt Heplerb7609542020-01-24 10:29:54 -0800571 return Status::FAILED_PRECONDITION;
572 }
Wyatt Heplerb7609542020-01-24 10:29:54 -0800573 return Status::OK;
574}
575
David Rogers9abe3c72020-03-24 19:03:13 -0700576Status KeyValueStore::CheckReadOperation(string_view key) const {
577 if (InvalidKey(key)) {
578 return Status::INVALID_ARGUMENT;
579 }
580
581 // Operations that are explicitly read-only can be done after init() has been
582 // called but not fully ready (when needing maintenance).
583 if (initialized_ == InitializationState::kNotInitialized) {
584 return Status::FAILED_PRECONDITION;
585 }
586 return Status::OK;
587}
588
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700589Status KeyValueStore::WriteEntryForExistingKey(EntryMetadata& metadata,
590 EntryState new_state,
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800591 string_view key,
592 span<const byte> value) {
Wyatt Heplerab3b2492020-03-11 16:15:16 -0700593 // Read the original entry to get the size for sector accounting purposes.
594 Entry entry;
David Rogers98fea472020-04-01 15:43:48 -0700595 TRY(ReadEntry(metadata, entry));
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800596
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700597 return WriteEntry(key, value, new_state, &metadata, entry.size());
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800598}
599
600Status KeyValueStore::WriteEntryForNewKey(string_view key,
601 span<const byte> value) {
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700602 if (entry_cache_.full()) {
Keir Mierle8c352dc2020-02-02 13:58:19 -0800603 WRN("KVS full: trying to store a new entry, but can't. Have %zu entries",
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700604 entry_cache_.total_entries());
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800605 return Status::RESOURCE_EXHAUSTED;
606 }
607
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700608 return WriteEntry(key, value, EntryState::kValid);
Wyatt Heplerab3b2492020-03-11 16:15:16 -0700609}
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800610
Wyatt Heplerab3b2492020-03-11 16:15:16 -0700611Status KeyValueStore::WriteEntry(string_view key,
612 span<const byte> value,
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700613 EntryState new_state,
614 EntryMetadata* prior_metadata,
Wyatt Heplerab3b2492020-03-11 16:15:16 -0700615 size_t prior_size) {
616 const size_t entry_size = Entry::size(partition_, key, value);
617
618 // List of addresses for sectors with space for this entry.
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700619 Address* reserved_addresses = entry_cache_.TempReservedAddressesForWrite();
Wyatt Heplerab3b2492020-03-11 16:15:16 -0700620
David Rogers31b358b2020-04-15 05:00:50 -0700621 // Find addresses to write the entry to. This may involve garbage collecting
622 // one or more sectors.
623 TRY(GetAddressesForWrite(reserved_addresses, entry_size));
Wyatt Heplerab3b2492020-03-11 16:15:16 -0700624
625 // Write the entry at the first address that was found.
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700626 Entry entry = CreateEntry(reserved_addresses[0], key, value, new_state);
Wyatt Heplerab3b2492020-03-11 16:15:16 -0700627 TRY(AppendEntry(entry, key, value));
628
629 // After writing the first entry successfully, update the key descriptors.
630 // Once a single new the entry is written, the old entries are invalidated.
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700631 EntryMetadata new_metadata =
David Rogers31b358b2020-04-15 05:00:50 -0700632 CreateOrUpdateKeyDescriptor(entry, key, prior_metadata, prior_size);
Wyatt Heplerab3b2492020-03-11 16:15:16 -0700633
634 // Write the additional copies of the entry, if redundancy is greater than 1.
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700635 for (size_t i = 1; i < redundancy(); ++i) {
636 entry.set_address(reserved_addresses[i]);
Wyatt Heplerab3b2492020-03-11 16:15:16 -0700637 TRY(AppendEntry(entry, key, value));
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700638 new_metadata.AddNewAddress(reserved_addresses[i]);
Wyatt Heplerab3b2492020-03-11 16:15:16 -0700639 }
Wyatt Heplerb7609542020-01-24 10:29:54 -0800640 return Status::OK;
641}
642
David Rogers31b358b2020-04-15 05:00:50 -0700643KeyValueStore::EntryMetadata KeyValueStore::CreateOrUpdateKeyDescriptor(
Wyatt Heplerab3b2492020-03-11 16:15:16 -0700644 const Entry& entry,
645 string_view key,
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700646 EntryMetadata* prior_metadata,
Wyatt Heplerab3b2492020-03-11 16:15:16 -0700647 size_t prior_size) {
648 // If there is no prior descriptor, create a new one.
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700649 if (prior_metadata == nullptr) {
650 return entry_cache_.AddNew(entry.descriptor(key), entry.address());
David Rogersa2562b52020-03-05 15:30:05 -0800651 }
652
David Rogers31b358b2020-04-15 05:00:50 -0700653 return UpdateKeyDescriptor(
654 entry, entry.address(), prior_metadata, prior_size);
655}
656
657KeyValueStore::EntryMetadata KeyValueStore::UpdateKeyDescriptor(
658 const Entry& entry,
659 Address new_address,
660 EntryMetadata* prior_metadata,
661 size_t prior_size) {
Wyatt Heplerab3b2492020-03-11 16:15:16 -0700662 // Remove valid bytes for the old entry and its copies, which are now stale.
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700663 for (Address address : prior_metadata->addresses()) {
Wyatt Heplerc84393f2020-03-20 11:23:24 -0700664 sectors_.FromAddress(address).RemoveValidBytes(prior_size);
David Rogersa2562b52020-03-05 15:30:05 -0800665 }
666
David Rogers31b358b2020-04-15 05:00:50 -0700667 prior_metadata->Reset(entry.descriptor(prior_metadata->hash()), new_address);
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700668 return *prior_metadata;
David Rogersa2562b52020-03-05 15:30:05 -0800669}
670
David Rogers31b358b2020-04-15 05:00:50 -0700671Status KeyValueStore::GetAddressesForWrite(Address* write_addresses,
672 size_t write_size) {
673 for (size_t i = 0; i < redundancy(); i++) {
674 SectorDescriptor* sector;
675 TRY(GetSectorForWrite(&sector, write_size, span(write_addresses, i)));
676 write_addresses[i] = sectors_.NextWritableAddress(*sector);
677
678 DBG("Found space for entry in sector %u at address %u",
679 sectors_.Index(sector),
680 unsigned(write_addresses[i]));
681 }
682
683 return Status::OK;
684}
685
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700686// Finds a sector to use for writing a new entry to. Does automatic garbage
David Rogersa2562b52020-03-05 15:30:05 -0800687// collection if needed and allowed.
688//
689// OK: Sector found with needed space.
690// RESOURCE_EXHAUSTED: No sector available with the needed space.
691Status KeyValueStore::GetSectorForWrite(SectorDescriptor** sector,
692 size_t entry_size,
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700693 span<const Address> reserved) {
Wyatt Heplerc84393f2020-03-20 11:23:24 -0700694 Status result = sectors_.FindSpace(sector, entry_size, reserved);
David Rogersa2562b52020-03-05 15:30:05 -0800695
David Rogersf3884eb2020-03-08 19:21:40 -0700696 size_t gc_sector_count = 0;
David Rogersa2562b52020-03-05 15:30:05 -0800697 bool do_auto_gc = options_.gc_on_write != GargbageCollectOnWrite::kDisabled;
698
699 // Do garbage collection as needed, so long as policy allows.
700 while (result == Status::RESOURCE_EXHAUSTED && do_auto_gc) {
701 if (options_.gc_on_write == GargbageCollectOnWrite::kOneSector) {
702 // If GC config option is kOneSector clear the flag to not do any more
703 // GC after this try.
704 do_auto_gc = false;
705 }
706 // Garbage collect and then try again to find the best sector.
David Rogers9abe3c72020-03-24 19:03:13 -0700707 Status gc_status = GarbageCollect(reserved);
David Rogersa2562b52020-03-05 15:30:05 -0800708 if (!gc_status.ok()) {
709 if (gc_status == Status::NOT_FOUND) {
710 // Not enough space, and no reclaimable bytes, this KVS is full!
711 return Status::RESOURCE_EXHAUSTED;
712 }
713 return gc_status;
714 }
715
Wyatt Heplerc84393f2020-03-20 11:23:24 -0700716 result = sectors_.FindSpace(sector, entry_size, reserved);
David Rogersf3884eb2020-03-08 19:21:40 -0700717
718 gc_sector_count++;
719 // Allow total sectors + 2 number of GC cycles so that once reclaimable
720 // bytes in all the sectors have been reclaimed can try and free up space by
721 // moving entries for keys other than the one being worked on in to sectors
722 // that have copies of the key trying to be written.
723 if (gc_sector_count > (partition_.sector_count() + 2)) {
724 ERR("Did more GC sectors than total sectors!!!!");
725 return Status::RESOURCE_EXHAUSTED;
726 }
David Rogersa2562b52020-03-05 15:30:05 -0800727 }
728
729 if (!result.ok()) {
730 WRN("Unable to find sector to write %zu B", entry_size);
731 }
732 return result;
733}
734
David Rogers9abe3c72020-03-24 19:03:13 -0700735Status KeyValueStore::MarkSectorCorruptIfNotOk(Status status,
736 SectorDescriptor* sector) {
737 if (!status.ok()) {
738 DBG(" Sector %u corrupt", sectors_.Index(sector));
739 sector->mark_corrupt();
740 error_detected_ = true;
741 }
742 return status;
743}
744
Wyatt Heplerab3b2492020-03-11 16:15:16 -0700745Status KeyValueStore::AppendEntry(const Entry& entry,
David Rogersa2562b52020-03-05 15:30:05 -0800746 string_view key,
747 span<const byte> value) {
Wyatt Heplerab3b2492020-03-11 16:15:16 -0700748 const StatusWithSize result = entry.Write(key, value);
David Rogersa2562b52020-03-05 15:30:05 -0800749
Wyatt Heplerc84393f2020-03-20 11:23:24 -0700750 SectorDescriptor& sector = sectors_.FromAddress(entry.address());
David Rogersa2562b52020-03-05 15:30:05 -0800751
752 if (!result.ok()) {
753 ERR("Failed to write %zu bytes at %#zx. %zu actually written",
754 entry.size(),
Wyatt Heplerab3b2492020-03-11 16:15:16 -0700755 size_t(entry.address()),
David Rogersa2562b52020-03-05 15:30:05 -0800756 result.size());
David Rogers9abe3c72020-03-24 19:03:13 -0700757 TRY(MarkSectorCorruptIfNotOk(result.status(), &sector));
David Rogersa2562b52020-03-05 15:30:05 -0800758 }
759
760 if (options_.verify_on_write) {
David Rogers9abe3c72020-03-24 19:03:13 -0700761 TRY(MarkSectorCorruptIfNotOk(entry.VerifyChecksumInFlash(), &sector));
David Rogersa2562b52020-03-05 15:30:05 -0800762 }
763
David Rogers98fea472020-04-01 15:43:48 -0700764 sector.RemoveWritableBytes(result.size());
Wyatt Heplerc84393f2020-03-20 11:23:24 -0700765 sector.AddValidBytes(result.size());
David Rogersa2562b52020-03-05 15:30:05 -0800766 return Status::OK;
767}
768
David Rogers98fea472020-04-01 15:43:48 -0700769StatusWithSize KeyValueStore::CopyEntryToSector(Entry& entry,
770 SectorDescriptor* new_sector,
David Rogers31b358b2020-04-15 05:00:50 -0700771 Address new_address) {
David Rogers98fea472020-04-01 15:43:48 -0700772 const StatusWithSize result = entry.Copy(new_address);
773
774 TRY_WITH_SIZE(MarkSectorCorruptIfNotOk(result.status(), new_sector));
775
776 if (options_.verify_on_write) {
David Rogers31b358b2020-04-15 05:00:50 -0700777 Entry new_entry;
778 TRY_WITH_SIZE(MarkSectorCorruptIfNotOk(
779 Entry::Read(partition_, new_address, formats_, &new_entry),
780 new_sector));
781 // TODO: add test that catches doing the verify on the old entry.
782 TRY_WITH_SIZE(MarkSectorCorruptIfNotOk(new_entry.VerifyChecksumInFlash(),
783 new_sector));
David Rogers98fea472020-04-01 15:43:48 -0700784 }
785 // Entry was written successfully; update descriptor's address and the sector
786 // descriptors to reflect the new entry.
787 new_sector->RemoveWritableBytes(result.size());
788 new_sector->AddValidBytes(result.size());
789
790 return result;
791}
792
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700793Status KeyValueStore::RelocateEntry(const EntryMetadata& metadata,
Wyatt Heplerab3b2492020-03-11 16:15:16 -0700794 KeyValueStore::Address& address,
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700795 span<const Address> reserved_addresses) {
David Rogersa2562b52020-03-05 15:30:05 -0800796 Entry entry;
David Rogers98fea472020-04-01 15:43:48 -0700797 TRY(ReadEntry(metadata, entry));
David Rogersa2562b52020-03-05 15:30:05 -0800798
799 // Find a new sector for the entry and write it to the new location. For
800 // relocation the find should not not be a sector already containing the key
801 // but can be the always empty sector, since this is part of the GC process
802 // that will result in a new empty sector. Also find a sector that does not
803 // have reclaimable space (mostly for the full GC, where that would result in
804 // an immediate extra relocation).
805 SectorDescriptor* new_sector;
806
Wyatt Heplerc84393f2020-03-20 11:23:24 -0700807 TRY(sectors_.FindSpaceDuringGarbageCollection(
808 &new_sector, entry.size(), metadata.addresses(), reserved_addresses));
Wyatt Heplerab3b2492020-03-11 16:15:16 -0700809
David Rogers31b358b2020-04-15 05:00:50 -0700810 Address new_address = sectors_.NextWritableAddress(*new_sector);
David Rogers98fea472020-04-01 15:43:48 -0700811 TRY_ASSIGN(const size_t result_size,
812 CopyEntryToSector(entry, new_sector, new_address));
813 sectors_.FromAddress(address).RemoveValidBytes(result_size);
Wyatt Heplerab3b2492020-03-11 16:15:16 -0700814 address = new_address;
David Rogersa2562b52020-03-05 15:30:05 -0800815
816 return Status::OK;
817}
818
David Rogers9abe3c72020-03-24 19:03:13 -0700819Status KeyValueStore::FullMaintenance() {
820 if (initialized_ == InitializationState::kNotInitialized) {
821 return Status::FAILED_PRECONDITION;
822 }
823
824 DBG("Do full maintenance");
David Rogers98fea472020-04-01 15:43:48 -0700825 CheckForErrors();
David Rogers9abe3c72020-03-24 19:03:13 -0700826
827 if (error_detected_) {
828 TRY(Repair());
829 }
Wyatt Heplerc84393f2020-03-20 11:23:24 -0700830
David Rogers31b358b2020-04-15 05:00:50 -0700831 // Make sure all the entries are on the primary format.
832 UpdateEntriesToPrimaryFormat();
833
Wyatt Heplerc84393f2020-03-20 11:23:24 -0700834 SectorDescriptor* sector = sectors_.last_new();
David Rogerscd87c322020-02-27 14:04:08 -0800835
836 // TODO: look in to making an iterator method for cycling through sectors
837 // starting from last_new_sector_.
838 for (size_t j = 0; j < sectors_.size(); j++) {
839 sector += 1;
840 if (sector == sectors_.end()) {
841 sector = sectors_.begin();
842 }
843
844 if (sector->RecoverableBytes(partition_.sector_size_bytes()) > 0) {
Wyatt Heplerc84393f2020-03-20 11:23:24 -0700845 TRY(GarbageCollectSector(*sector, {}));
David Rogerscd87c322020-02-27 14:04:08 -0800846 }
847 }
848
David Rogers9abe3c72020-03-24 19:03:13 -0700849 DBG("Full maintenance complete");
David Rogerscd87c322020-02-27 14:04:08 -0800850 return Status::OK;
851}
852
David Rogers9abe3c72020-03-24 19:03:13 -0700853Status KeyValueStore::GarbageCollect(span<const Address> reserved_addresses) {
854 if (initialized_ == InitializationState::kNotInitialized) {
855 return Status::FAILED_PRECONDITION;
856 }
857
David Rogersc9d545e2020-03-11 17:47:43 -0700858 DBG("Garbage Collect a single sector");
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700859 for (Address address : reserved_addresses) {
David Rogersc9d545e2020-03-11 17:47:43 -0700860 DBG(" Avoid address %u", unsigned(address));
861 }
David Rogers67f4b6c2020-02-06 16:17:09 -0800862
David Rogersfcea3252020-04-07 14:56:35 -0700863 // Do automatic repair, if KVS options allow for it.
864 if (error_detected_ && options_.recovery != ErrorRecovery::kManual) {
865 TRY(Repair());
866 }
867
David Rogersa12786b2020-01-31 16:02:33 -0800868 // Step 1: Find the sector to garbage collect
David Rogersc9d545e2020-03-11 17:47:43 -0700869 SectorDescriptor* sector_to_gc =
Wyatt Heplerc84393f2020-03-20 11:23:24 -0700870 sectors_.FindSectorToGarbageCollect(reserved_addresses);
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800871
David Rogersa12786b2020-01-31 16:02:33 -0800872 if (sector_to_gc == nullptr) {
David Rogersa2562b52020-03-05 15:30:05 -0800873 // Nothing to GC.
874 return Status::NOT_FOUND;
David Rogersa12786b2020-01-31 16:02:33 -0800875 }
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800876
David Rogersc9d545e2020-03-11 17:47:43 -0700877 // Step 2: Garbage collect the selected sector.
Wyatt Heplerc84393f2020-03-20 11:23:24 -0700878 return GarbageCollectSector(*sector_to_gc, reserved_addresses);
David Rogerscd87c322020-02-27 14:04:08 -0800879}
880
David Rogersf3884eb2020-03-08 19:21:40 -0700881Status KeyValueStore::RelocateKeyAddressesInSector(
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700882 SectorDescriptor& sector_to_gc,
David Rogersfcea3252020-04-07 14:56:35 -0700883 const EntryMetadata& metadata,
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700884 span<const Address> reserved_addresses) {
885 for (FlashPartition::Address& address : metadata.addresses()) {
Wyatt Heplerc84393f2020-03-20 11:23:24 -0700886 if (sectors_.AddressInSector(sector_to_gc, address)) {
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700887 DBG(" Relocate entry for Key 0x%08" PRIx32 ", sector %u",
888 metadata.hash(),
Wyatt Heplerc84393f2020-03-20 11:23:24 -0700889 sectors_.Index(sectors_.FromAddress(address)));
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700890 TRY(RelocateEntry(metadata, address, reserved_addresses));
David Rogersf3884eb2020-03-08 19:21:40 -0700891 }
892 }
Wyatt Heplerab3b2492020-03-11 16:15:16 -0700893
David Rogersf3884eb2020-03-08 19:21:40 -0700894 return Status::OK;
895};
896
Wyatt Heplerab3b2492020-03-11 16:15:16 -0700897Status KeyValueStore::GarbageCollectSector(
Wyatt Heplerc84393f2020-03-20 11:23:24 -0700898 SectorDescriptor& sector_to_gc, span<const Address> reserved_addresses) {
David Rogers9abe3c72020-03-24 19:03:13 -0700899 DBG(" Garbage Collect sector %u", sectors_.Index(sector_to_gc));
David Rogersf3884eb2020-03-08 19:21:40 -0700900 // Step 1: Move any valid entries in the GC sector to other sectors
Wyatt Heplerc84393f2020-03-20 11:23:24 -0700901 if (sector_to_gc.valid_bytes() != 0) {
David Rogers98fea472020-04-01 15:43:48 -0700902 for (EntryMetadata& metadata : entry_cache_) {
Wyatt Heplerab3b2492020-03-11 16:15:16 -0700903 TRY(RelocateKeyAddressesInSector(
Wyatt Heplerc84393f2020-03-20 11:23:24 -0700904 sector_to_gc, metadata, reserved_addresses));
David Rogersf3884eb2020-03-08 19:21:40 -0700905 }
906 }
907
Wyatt Heplerc84393f2020-03-20 11:23:24 -0700908 if (sector_to_gc.valid_bytes() != 0) {
David Rogers67f4b6c2020-02-06 16:17:09 -0800909 ERR(" Failed to relocate valid entries from sector being garbage "
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800910 "collected, %zu valid bytes remain",
Wyatt Heplerc84393f2020-03-20 11:23:24 -0700911 sector_to_gc.valid_bytes());
Wyatt Heplerb7609542020-01-24 10:29:54 -0800912 return Status::INTERNAL;
913 }
914
David Rogerscd87c322020-02-27 14:04:08 -0800915 // Step 2: Reinitialize the sector
David Rogers9abe3c72020-03-24 19:03:13 -0700916 sector_to_gc.mark_corrupt();
Wyatt Heplerc84393f2020-03-20 11:23:24 -0700917 TRY(partition_.Erase(sectors_.BaseAddress(sector_to_gc), 1));
918 sector_to_gc.set_writable_bytes(partition_.sector_size_bytes());
Wyatt Heplerb7609542020-01-24 10:29:54 -0800919
Wyatt Heplerc84393f2020-03-20 11:23:24 -0700920 DBG(" Garbage Collect sector %u complete", sectors_.Index(sector_to_gc));
David Rogersa12786b2020-01-31 16:02:33 -0800921 return Status::OK;
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800922}
923
David Rogers31b358b2020-04-15 05:00:50 -0700924Status KeyValueStore::UpdateEntriesToPrimaryFormat() {
925 for (EntryMetadata& prior_metadata : entry_cache_) {
926 Entry entry;
927 TRY(ReadEntry(prior_metadata, entry));
928 if (formats_.primary().magic == entry.magic()) {
929 // Ignore entries that are already on the primary format.
930 continue;
931 }
932
933 DBG("Updating entry 0x%08x from old format [0x%08x] to new format "
934 "[0x%08x]",
935 unsigned(prior_metadata.hash()),
936 unsigned(entry.magic()),
937 unsigned(formats_.primary().magic));
938
939 last_transaction_id_ += 1;
940 TRY(entry.Update(formats_.primary(), last_transaction_id_));
941
942 // List of addresses for sectors with space for this entry.
943 Address* reserved_addresses = entry_cache_.TempReservedAddressesForWrite();
944
945 // Find addresses to write the entry to. This may involve garbage collecting
946 // one or more sectors.
947 TRY(GetAddressesForWrite(reserved_addresses, entry.size()));
948
949 TRY(CopyEntryToSector(entry,
950 &sectors_.FromAddress(reserved_addresses[0]),
951 reserved_addresses[0]));
952
953 // After writing the first entry successfully, update the key descriptors.
954 // Once a single new the entry is written, the old entries are invalidated.
955 EntryMetadata new_metadata = UpdateKeyDescriptor(
956 entry, reserved_addresses[0], &prior_metadata, entry.size());
957
958 // Write the additional copies of the entry, if redundancy is greater
959 // than 1.
960 for (size_t i = 1; i < redundancy(); ++i) {
961 TRY(CopyEntryToSector(entry,
962 &sectors_.FromAddress(reserved_addresses[i]),
963 reserved_addresses[i]));
964 new_metadata.AddNewAddress(reserved_addresses[i]);
965 }
966 }
967 return Status::OK;
968}
969
David Rogers9abe3c72020-03-24 19:03:13 -0700970// Add any missing redundant entries/copies for a key.
971Status KeyValueStore::AddRedundantEntries(EntryMetadata& metadata) {
972 SectorDescriptor* new_sector;
973
974 Entry entry;
975
David Rogers98fea472020-04-01 15:43:48 -0700976 TRY(ReadEntry(metadata, entry));
David Rogers9abe3c72020-03-24 19:03:13 -0700977 TRY(entry.VerifyChecksumInFlash());
978
979 for (size_t i = metadata.addresses().size();
980 metadata.addresses().size() < redundancy();
981 i++) {
982 TRY(sectors_.FindSpace(&new_sector, entry.size(), metadata.addresses()));
983
David Rogers31b358b2020-04-15 05:00:50 -0700984 Address new_address = sectors_.NextWritableAddress(*new_sector);
David Rogers98fea472020-04-01 15:43:48 -0700985 TRY(CopyEntryToSector(entry, new_sector, new_address));
David Rogers9abe3c72020-03-24 19:03:13 -0700986
987 metadata.AddNewAddress(new_address);
988 }
989 return Status::OK;
990}
991
992Status KeyValueStore::RepairCorruptSectors() {
993 // Try to GC each corrupt sector, even if previous sectors fail. If GC of a
994 // sector failed on the first pass, then do a second pass, since a later
995 // sector might have cleared up space or otherwise unblocked the earlier
996 // failed sector.
997 Status repair_status = Status::OK;
998
999 size_t loop_count = 0;
1000 do {
1001 loop_count++;
1002 // Error of RESOURCE_EXHAUSTED indicates no space found for relocation.
1003 // Reset back to OK for the next pass.
1004 if (repair_status == Status::RESOURCE_EXHAUSTED) {
1005 repair_status = Status::OK;
1006 }
1007
1008 DBG(" Pass %u", unsigned(loop_count));
1009 for (SectorDescriptor& sector : sectors_) {
1010 if (sector.corrupt()) {
1011 DBG(" Found sector %u with corruption", sectors_.Index(sector));
1012 Status sector_status = GarbageCollectSector(sector, {});
1013 if (sector_status.ok()) {
1014 error_stats_.corrupt_sectors_recovered += 1;
1015 } else if (repair_status.ok() ||
1016 repair_status == Status::RESOURCE_EXHAUSTED) {
1017 repair_status = sector_status;
1018 }
1019 }
1020 }
1021 DBG(" Pass %u complete", unsigned(loop_count));
1022 } while (!repair_status.ok() && loop_count < 2);
1023
1024 return repair_status;
1025}
1026
1027Status KeyValueStore::EnsureFreeSectorExists() {
1028 Status repair_status = Status::OK;
1029 bool empty_sector_found = false;
1030
1031 DBG(" Find empty sector");
1032 for (SectorDescriptor& sector : sectors_) {
1033 if (sector.Empty(partition_.sector_size_bytes())) {
1034 empty_sector_found = true;
1035 DBG(" Empty sector found");
1036 break;
1037 }
1038 }
1039 if (empty_sector_found == false) {
1040 DBG(" No empty sector found, attempting to GC a free sector");
1041 Status sector_status = GarbageCollect(span<const Address, 0>());
1042 if (repair_status.ok() && !sector_status.ok()) {
1043 DBG(" Unable to free an empty sector");
1044 repair_status = sector_status;
1045 }
1046 }
1047
1048 return repair_status;
1049}
1050
1051Status KeyValueStore::EnsureEntryRedundancy() {
1052 Status repair_status = Status::OK;
1053
1054 if (redundancy() == 1) {
David Rogers98fea472020-04-01 15:43:48 -07001055 DBG(" Redundancy not in use, nothting to check");
David Rogers9abe3c72020-03-24 19:03:13 -07001056 return Status::OK;
1057 }
1058
David Rogers98fea472020-04-01 15:43:48 -07001059 DBG(" Write any needed additional duplicate copies of keys to fulfill %u"
1060 " redundancy",
David Rogers9abe3c72020-03-24 19:03:13 -07001061 unsigned(redundancy()));
David Rogers98fea472020-04-01 15:43:48 -07001062 for (EntryMetadata& metadata : entry_cache_) {
David Rogers9abe3c72020-03-24 19:03:13 -07001063 if (metadata.addresses().size() >= redundancy()) {
1064 continue;
1065 }
1066
1067 DBG(" Key with %u of %u copies found, adding missing copies",
1068 unsigned(metadata.addresses().size()),
1069 unsigned(redundancy()));
David Rogers98fea472020-04-01 15:43:48 -07001070 Status fill_status = AddRedundantEntries(metadata);
David Rogers9abe3c72020-03-24 19:03:13 -07001071 if (fill_status.ok()) {
1072 error_stats_.missing_redundant_entries_recovered += 1;
1073 DBG(" Key missing copies added");
1074 } else {
1075 DBG(" Failed to add key missing copies");
1076 if (repair_status.ok()) {
1077 repair_status = fill_status;
1078 }
1079 }
1080 }
1081
1082 return repair_status;
1083}
1084
David Rogersfcea3252020-04-07 14:56:35 -07001085Status KeyValueStore::FixErrors() {
1086 DBG("Fixing KVS errors");
David Rogers9abe3c72020-03-24 19:03:13 -07001087
1088 // Step 1: Garbage collect any sectors marked as corrupt.
David Rogersfcea3252020-04-07 14:56:35 -07001089 Status overall_status = RepairCorruptSectors();
David Rogers9abe3c72020-03-24 19:03:13 -07001090
1091 // Step 2: Make sure there is at least 1 empty sector. This needs to be a
1092 // seperate check of sectors from step 1, because a found empty sector might
1093 // get written to by a later GC that fails and does not result in a free
1094 // sector.
David Rogersfcea3252020-04-07 14:56:35 -07001095 Status repair_status = EnsureFreeSectorExists();
David Rogers9abe3c72020-03-24 19:03:13 -07001096 if (overall_status.ok()) {
1097 overall_status = repair_status;
1098 }
1099
1100 // Step 3: Make sure each stored key has the full number of redundant
1101 // entries.
1102 repair_status = EnsureEntryRedundancy();
1103 if (overall_status.ok()) {
1104 overall_status = repair_status;
1105 }
1106
1107 if (overall_status.ok()) {
1108 error_detected_ = false;
1109 initialized_ = InitializationState::kReady;
1110 }
1111 return overall_status;
1112}
1113
David Rogersfcea3252020-04-07 14:56:35 -07001114Status KeyValueStore::Repair() {
1115 // If errors have been detected, just reinit the KVS metadata. This does a
1116 // full deep error check and any needed repairs. Then repair any errors.
1117 INF("Starting KVS repair");
1118
1119 DBG("Reinitialize KVS metadata");
1120 InitializeMetadata();
1121
1122 return FixErrors();
1123}
1124
Wyatt Heplerbdd8e5a2020-02-20 19:27:26 -08001125KeyValueStore::Entry KeyValueStore::CreateEntry(Address address,
Wyatt Heplerab3b2492020-03-11 16:15:16 -07001126 string_view key,
Wyatt Heplerbdd8e5a2020-02-20 19:27:26 -08001127 span<const byte> value,
Wyatt Hepler7ded6da2020-03-11 18:24:43 -07001128 EntryState state) {
Keir Mierle9e38b402020-02-21 13:06:21 -08001129 // Always bump the transaction ID when creating a new entry.
1130 //
1131 // Burning transaction IDs prevents inconsistencies between flash and memory
1132 // that which could happen if a write succeeds, but for some reason the read
1133 // and verify step fails. Here's how this would happen:
1134 //
1135 // 1. The entry is written but for some reason the flash reports failure OR
1136 // The write succeeds, but the read / verify operation fails.
1137 // 2. The transaction ID is NOT incremented, because of the failure
1138 // 3. (later) A new entry is written, re-using the transaction ID (oops)
1139 //
1140 // By always burning transaction IDs, the above problem can't happen.
1141 last_transaction_id_ += 1;
1142
Wyatt Hepler7ded6da2020-03-11 18:24:43 -07001143 if (state == EntryState::kDeleted) {
Wyatt Hepler7465be32020-02-21 15:30:53 -08001144 return Entry::Tombstone(
Wyatt Hepler22d0d9f2020-03-05 14:57:11 -08001145 partition_, address, formats_.primary(), key, last_transaction_id_);
Wyatt Hepler1fc11042020-02-19 17:17:51 -08001146 }
1147 return Entry::Valid(partition_,
1148 address,
Wyatt Hepler22d0d9f2020-03-05 14:57:11 -08001149 formats_.primary(),
Wyatt Hepler1fc11042020-02-19 17:17:51 -08001150 key,
1151 value,
Keir Mierle9e38b402020-02-21 13:06:21 -08001152 last_transaction_id_);
Wyatt Heplerd2298282020-02-20 17:12:45 -08001153}
1154
Wyatt Hepler7ded6da2020-03-11 18:24:43 -07001155void KeyValueStore::LogDebugInfo() const {
Keir Mierle8c352dc2020-02-02 13:58:19 -08001156 const size_t sector_size_bytes = partition_.sector_size_bytes();
1157 DBG("====================== KEY VALUE STORE DUMP =========================");
1158 DBG(" ");
1159 DBG("Flash partition:");
Wyatt Heplerad0a7932020-02-06 08:20:38 -08001160 DBG(" Sector count = %zu", partition_.sector_count());
Wyatt Hepler38ce30f2020-02-19 11:48:31 -08001161 DBG(" Sector max count = %zu", sectors_.max_size());
Wyatt Hepler1c329ca2020-02-07 18:07:23 -08001162 DBG(" Sectors in use = %zu", sectors_.size());
Keir Mierle8c352dc2020-02-02 13:58:19 -08001163 DBG(" Sector size = %zu", sector_size_bytes);
1164 DBG(" Total size = %zu", partition_.size_bytes());
1165 DBG(" Alignment = %zu", partition_.alignment_bytes());
1166 DBG(" ");
1167 DBG("Key descriptors:");
Wyatt Hepler7ded6da2020-03-11 18:24:43 -07001168 DBG(" Entry count = %zu", entry_cache_.total_entries());
1169 DBG(" Max entry count = %zu", entry_cache_.max_entries());
Keir Mierle8c352dc2020-02-02 13:58:19 -08001170 DBG(" ");
1171 DBG(" # hash version address address (hex)");
Wyatt Hepler7ded6da2020-03-11 18:24:43 -07001172 size_t i = 0;
1173 for (const EntryMetadata& metadata : entry_cache_) {
Keir Mierle8c352dc2020-02-02 13:58:19 -08001174 DBG(" |%3zu: | %8zx |%8zu | %8zu | %8zx",
Wyatt Hepler7ded6da2020-03-11 18:24:43 -07001175 i++,
1176 size_t(metadata.hash()),
1177 size_t(metadata.transaction_id()),
1178 size_t(metadata.first_address()),
1179 size_t(metadata.first_address()));
Keir Mierle8c352dc2020-02-02 13:58:19 -08001180 }
1181 DBG(" ");
1182
1183 DBG("Sector descriptors:");
1184 DBG(" # tail free valid has_space");
Wyatt Heplerc84393f2020-03-20 11:23:24 -07001185 for (const SectorDescriptor& sd : sectors_) {
1186 DBG(" |%3u: | %8zu |%8zu | %s",
1187 sectors_.Index(sd),
Wyatt Hepler2c7eca02020-02-18 16:01:42 -08001188 size_t(sd.writable_bytes()),
1189 sd.valid_bytes(),
1190 sd.writable_bytes() ? "YES" : "");
Keir Mierle8c352dc2020-02-02 13:58:19 -08001191 }
1192 DBG(" ");
1193
1194 // TODO: This should stop logging after some threshold.
1195 // size_t dumped_bytes = 0;
1196 DBG("Sector raw data:");
Wyatt Hepler1c329ca2020-02-07 18:07:23 -08001197 for (size_t sector_id = 0; sector_id < sectors_.size(); ++sector_id) {
Keir Mierle8c352dc2020-02-02 13:58:19 -08001198 // Read sector data. Yes, this will blow the stack on embedded.
Wyatt Hepler1c329ca2020-02-07 18:07:23 -08001199 std::array<byte, 500> raw_sector_data; // TODO!!!
Keir Mierle8c352dc2020-02-02 13:58:19 -08001200 StatusWithSize sws =
1201 partition_.Read(sector_id * sector_size_bytes, raw_sector_data);
1202 DBG("Read: %zu bytes", sws.size());
1203
1204 DBG(" base addr offs 0 1 2 3 4 5 6 7");
1205 for (size_t i = 0; i < sector_size_bytes; i += 8) {
1206 DBG(" %3zu %8zx %5zu | %02x %02x %02x %02x %02x %02x %02x %02x",
1207 sector_id,
1208 (sector_id * sector_size_bytes) + i,
1209 i,
1210 static_cast<unsigned int>(raw_sector_data[i + 0]),
1211 static_cast<unsigned int>(raw_sector_data[i + 1]),
1212 static_cast<unsigned int>(raw_sector_data[i + 2]),
1213 static_cast<unsigned int>(raw_sector_data[i + 3]),
1214 static_cast<unsigned int>(raw_sector_data[i + 4]),
1215 static_cast<unsigned int>(raw_sector_data[i + 5]),
1216 static_cast<unsigned int>(raw_sector_data[i + 6]),
1217 static_cast<unsigned int>(raw_sector_data[i + 7]));
1218
1219 // TODO: Fix exit condition.
1220 if (i > 128) {
1221 break;
1222 }
1223 }
1224 DBG(" ");
1225 }
1226
1227 DBG("////////////////////// KEY VALUE STORE DUMP END /////////////////////");
1228}
1229
David Rogerscf680ab2020-02-12 23:28:32 -08001230void KeyValueStore::LogSectors() const {
1231 DBG("Sector descriptors: count %zu", sectors_.size());
Wyatt Hepler1c329ca2020-02-07 18:07:23 -08001232 for (auto& sector : sectors_) {
Wyatt Hepler2c7eca02020-02-18 16:01:42 -08001233 DBG(" - Sector %u: valid %zu, recoverable %zu, free %zu",
Wyatt Heplerc84393f2020-03-20 11:23:24 -07001234 sectors_.Index(sector),
Wyatt Hepler2c7eca02020-02-18 16:01:42 -08001235 sector.valid_bytes(),
1236 sector.RecoverableBytes(partition_.sector_size_bytes()),
1237 sector.writable_bytes());
David Rogers50185ad2020-02-07 00:02:46 -08001238 }
1239}
1240
David Rogerscf680ab2020-02-12 23:28:32 -08001241void KeyValueStore::LogKeyDescriptor() const {
Wyatt Hepler7ded6da2020-03-11 18:24:43 -07001242 DBG("Key descriptors: count %zu", entry_cache_.total_entries());
David Rogers9abe3c72020-03-24 19:03:13 -07001243 for (const EntryMetadata& metadata : entry_cache_) {
Wyatt Hepler7ded6da2020-03-11 18:24:43 -07001244 DBG(" - Key: %s, hash %#zx, transaction ID %zu, first address %#zx",
Wyatt Hepler02946272020-03-18 10:36:22 -07001245 metadata.state() == EntryState::kDeleted ? "Deleted" : "Valid",
Wyatt Hepler7ded6da2020-03-11 18:24:43 -07001246 static_cast<size_t>(metadata.hash()),
1247 static_cast<size_t>(metadata.transaction_id()),
1248 static_cast<size_t>(metadata.first_address()));
David Rogerscf680ab2020-02-12 23:28:32 -08001249 }
1250}
1251
Wyatt Hepler2ad60672020-01-21 08:00:16 -08001252} // namespace pw::kvs