blob: 857db8ef2cd50c8c70e2fd13c7ba2d2ed7bc05c9 [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 Rogerscd134352020-04-17 19:37:15 -070081 Status metadata_result = InitializeMetadata();
David Rogersfcea3252020-04-07 14:56:35 -070082
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()) {
David Rogerscd134352020-04-17 19:37:15 -070090 if (metadata_result == Status::OUT_OF_RANGE) {
91 INF("KVS init: Redundancy level successfully updated");
92 } else {
93 WRN("KVS init: Corruption detected and fully repaired");
94 }
David Rogersfcea3252020-04-07 14:56:35 -070095 initialized_ = InitializationState::kReady;
96 } else if (recovery_status == Status::RESOURCE_EXHAUSTED) {
97 WRN("KVS init: Unable to maintain required free sector");
98 initialized_ = InitializationState::kNeedsMaintenance;
99 } else {
100 WRN("KVS init: Corruption detected and unable repair");
101 initialized_ = InitializationState::kNeedsMaintenance;
102 }
103 } else {
104 WRN("KVS init: Corruption detected, no repair attempted due to options");
105 initialized_ = InitializationState::kNeedsMaintenance;
106 }
107 }
108
109 INF("KeyValueStore init complete: active keys %zu, deleted keys %zu, sectors "
110 "%zu, logical sector size %zu bytes",
111 size(),
112 (entry_cache_.total_entries() - size()),
113 sectors_.size(),
114 partition_.sector_size_bytes());
115
116 // Report any corruption was not repaired.
117 if (error_detected_) {
118 WRN("KVS init: Corruption found but not repaired, KVS unavailable until "
119 "successful maintenance.");
120 return Status::DATA_LOSS;
121 }
122
123 return Status::OK;
124}
125
David Rogerscd134352020-04-17 19:37:15 -0700126Status KeyValueStore::InitializeMetadata() {
David Rogersfcea3252020-04-07 14:56:35 -0700127 const size_t sector_size_bytes = partition_.sector_size_bytes();
128
129 sectors_.Reset();
130 entry_cache_.Reset();
131
Keir Mierle8c352dc2020-02-02 13:58:19 -0800132 DBG("First pass: Read all entries from all sectors");
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800133 Address sector_address = 0;
Keir Mierle8c352dc2020-02-02 13:58:19 -0800134
Alexei Frolovd4adf912020-02-21 13:29:15 -0800135 size_t total_corrupt_bytes = 0;
David Rogerscd134352020-04-17 19:37:15 -0700136 size_t corrupt_entries = 0;
David Rogers91627482020-02-27 17:38:12 -0800137 bool empty_sector_found = false;
David Rogerscd134352020-04-17 19:37:15 -0700138 size_t entry_copies_missing = 0;
Alexei Frolovd4adf912020-02-21 13:29:15 -0800139
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800140 for (SectorDescriptor& sector : sectors_) {
Keir Mierle8c352dc2020-02-02 13:58:19 -0800141 Address entry_address = sector_address;
142
Alexei Frolovd4adf912020-02-21 13:29:15 -0800143 size_t sector_corrupt_bytes = 0;
144
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800145 for (int num_entries_in_sector = 0; true; num_entries_in_sector++) {
David Rogersfcea3252020-04-07 14:56:35 -0700146 DBG("Load entry: sector=%u, entry#=%d, address=%u",
147 unsigned(sector_address),
Keir Mierle8c352dc2020-02-02 13:58:19 -0800148 num_entries_in_sector,
David Rogersfcea3252020-04-07 14:56:35 -0700149 unsigned(entry_address));
Keir Mierle8c352dc2020-02-02 13:58:19 -0800150
Wyatt Heplerc84393f2020-03-20 11:23:24 -0700151 if (!sectors_.AddressInSector(sector, entry_address)) {
Keir Mierle8c352dc2020-02-02 13:58:19 -0800152 DBG("Fell off end of sector; moving to the next sector");
153 break;
154 }
155
156 Address next_entry_address;
157 Status status = LoadEntry(entry_address, &next_entry_address);
158 if (status == Status::NOT_FOUND) {
159 DBG("Hit un-written data in sector; moving to the next sector");
160 break;
David Rogersfcea3252020-04-07 14:56:35 -0700161 } else if (!status.ok()) {
162 // The entry could not be read, indicating likely data corruption within
163 // the sector. Try to scan the remainder of the sector for other
164 // entries.
Alexei Frolovd4adf912020-02-21 13:29:15 -0800165
David Rogers49766d92020-03-20 10:55:54 -0700166 error_detected_ = true;
Alexei Frolovd4adf912020-02-21 13:29:15 -0800167 corrupt_entries++;
168
169 status = ScanForEntry(sector,
170 entry_address + Entry::kMinAlignmentBytes,
171 &next_entry_address);
David Rogersfcea3252020-04-07 14:56:35 -0700172 if (!status.ok()) {
Alexei Frolovd4adf912020-02-21 13:29:15 -0800173 // No further entries in this sector. Mark the remaining bytes in the
174 // sector as corrupt (since we can't reliably know the size of the
175 // corrupt entry).
176 sector_corrupt_bytes +=
177 sector_size_bytes - (entry_address - sector_address);
178 break;
179 }
180
Alexei Frolovd4adf912020-02-21 13:29:15 -0800181 sector_corrupt_bytes += next_entry_address - entry_address;
Keir Mierle8c352dc2020-02-02 13:58:19 -0800182 }
Keir Mierle8c352dc2020-02-02 13:58:19 -0800183
184 // Entry loaded successfully; so get ready to load the next one.
185 entry_address = next_entry_address;
186
187 // Update of the number of writable bytes in this sector.
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800188 sector.set_writable_bytes(sector_size_bytes -
189 (entry_address - sector_address));
Keir Mierle8c352dc2020-02-02 13:58:19 -0800190 }
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800191
Alexei Frolovd4adf912020-02-21 13:29:15 -0800192 if (sector_corrupt_bytes > 0) {
193 // If the sector contains corrupt data, prevent any further entries from
194 // being written to it by indicating that it has no space. This should
195 // also make it a decent GC candidate. Valid keys in the sector are still
196 // readable as normal.
David Rogers49766d92020-03-20 10:55:54 -0700197 sector.mark_corrupt();
198 error_detected_ = true;
Alexei Frolovd4adf912020-02-21 13:29:15 -0800199
200 WRN("Sector %u contains %zuB of corrupt data",
Wyatt Heplerc84393f2020-03-20 11:23:24 -0700201 sectors_.Index(sector),
Alexei Frolovd4adf912020-02-21 13:29:15 -0800202 sector_corrupt_bytes);
203 }
204
David Rogers91627482020-02-27 17:38:12 -0800205 if (sector.Empty(sector_size_bytes)) {
206 empty_sector_found = true;
207 }
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800208 sector_address += sector_size_bytes;
Alexei Frolovd4adf912020-02-21 13:29:15 -0800209 total_corrupt_bytes += sector_corrupt_bytes;
Keir Mierle8c352dc2020-02-02 13:58:19 -0800210 }
211
212 DBG("Second pass: Count valid bytes in each sector");
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700213 Address newest_key = 0;
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800214
David Rogers98fea472020-04-01 15:43:48 -0700215 // For every valid entry, for each address, count the valid bytes in that
216 // sector. If the address fails to read, remove the address and mark the
217 // sector as corrupt. Track which entry has the newest transaction ID for
218 // initializing last_new_sector_.
219 for (EntryMetadata& metadata : entry_cache_) {
David Rogers49766d92020-03-20 10:55:54 -0700220 if (metadata.addresses().size() < redundancy()) {
David Rogers31b358b2020-04-15 05:00:50 -0700221 DBG("Key 0x%08x missing copies, has %u, needs %u",
222 unsigned(metadata.hash()),
223 unsigned(metadata.addresses().size()),
224 unsigned(redundancy()));
David Rogerscd134352020-04-17 19:37:15 -0700225 entry_copies_missing++;
David Rogers49766d92020-03-20 10:55:54 -0700226 }
David Rogers98fea472020-04-01 15:43:48 -0700227 size_t index = 0;
228 while (index < metadata.addresses().size()) {
229 Address address = metadata.addresses()[index];
David Rogersf56131c2020-03-04 10:19:22 -0800230 Entry entry;
David Rogers98fea472020-04-01 15:43:48 -0700231
232 Status read_result = Entry::Read(partition_, address, formats_, &entry);
233
234 SectorDescriptor& sector = sectors_.FromAddress(address);
235
236 if (read_result.ok()) {
237 sector.AddValidBytes(entry.size());
238 index++;
239 } else {
240 corrupt_entries++;
241 total_corrupt_bytes += sector.writable_bytes();
242 error_detected_ = true;
243 sector.mark_corrupt();
244
245 // Remove the bad address and stay at this index. The removal
246 // replaces out the removed address with the back address so
247 // this index needs to be rechecked with the new address.
248 metadata.RemoveAddress(address);
249 }
David Rogersf56131c2020-03-04 10:19:22 -0800250 }
David Rogers98fea472020-04-01 15:43:48 -0700251
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700252 if (metadata.IsNewerThan(last_transaction_id_)) {
253 last_transaction_id_ = metadata.transaction_id();
254 newest_key = metadata.addresses().back();
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800255 }
Keir Mierle8c352dc2020-02-02 13:58:19 -0800256 }
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800257
Wyatt Heplerc84393f2020-03-20 11:23:24 -0700258 sectors_.set_last_new_sector(newest_key);
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800259
David Rogers91627482020-02-27 17:38:12 -0800260 if (!empty_sector_found) {
David Rogers31b358b2020-04-15 05:00:50 -0700261 DBG("No empty sector found");
David Rogers9abe3c72020-03-24 19:03:13 -0700262 error_detected_ = true;
David Rogers91627482020-02-27 17:38:12 -0800263 }
264
David Rogerscd134352020-04-17 19:37:15 -0700265 if (entry_copies_missing > 0) {
266 bool other_errors = error_detected_;
267 error_detected_ = true;
268
269 if (!other_errors && entry_copies_missing == size()) {
270 INF("KVS configuration changed to redundancy of %zu total copies per key",
271 redundancy());
272 return Status::OUT_OF_RANGE;
273 }
David Rogers9abe3c72020-03-24 19:03:13 -0700274 }
David Rogerscd134352020-04-17 19:37:15 -0700275
276 if (error_detected_) {
277 WRN("Corruption detected. Found %zu corrupt bytes, %zu corrupt entries, "
278 "and %zu keys missing redundant copies.",
279 total_corrupt_bytes,
280 corrupt_entries,
281 entry_copies_missing);
282 return Status::FAILED_PRECONDITION;
283 }
284 return Status::OK;
Keir Mierle8c352dc2020-02-02 13:58:19 -0800285}
286
Alexei Frolov9e235832020-02-24 12:44:45 -0800287KeyValueStore::StorageStats KeyValueStore::GetStorageStats() const {
David Rogers9abe3c72020-03-24 19:03:13 -0700288 StorageStats stats{};
Alexei Frolov9e235832020-02-24 12:44:45 -0800289 const size_t sector_size = partition_.sector_size_bytes();
290 bool found_empty_sector = false;
David Rogers9abe3c72020-03-24 19:03:13 -0700291 stats.corrupt_sectors_recovered = error_stats_.corrupt_sectors_recovered;
292 stats.missing_redundant_entries_recovered =
293 error_stats_.missing_redundant_entries_recovered;
Alexei Frolov9e235832020-02-24 12:44:45 -0800294
295 for (const SectorDescriptor& sector : sectors_) {
296 stats.in_use_bytes += sector.valid_bytes();
297 stats.reclaimable_bytes += sector.RecoverableBytes(sector_size);
298
299 if (!found_empty_sector && sector.Empty(sector_size)) {
300 // The KVS tries to always keep an empty sector for GC, so don't count
301 // the first empty sector seen as writable space. However, a free sector
302 // cannot always be assumed to exist; if a GC operation fails, all sectors
303 // may be partially written, in which case the space reported might be
304 // inaccurate.
305 found_empty_sector = true;
306 continue;
307 }
308
309 stats.writable_bytes += sector.writable_bytes();
310 }
311
312 return stats;
313}
314
David Rogers98fea472020-04-01 15:43:48 -0700315// Check KVS for any error conditions. Primarily intended for test and
316// internal use.
David Rogers9abe3c72020-03-24 19:03:13 -0700317bool KeyValueStore::CheckForErrors() {
318 // Check for corrupted sectors
319 for (SectorDescriptor& sector : sectors_) {
320 if (sector.corrupt()) {
321 error_detected_ = true;
David Rogers98fea472020-04-01 15:43:48 -0700322 return error_detected();
David Rogers9abe3c72020-03-24 19:03:13 -0700323 }
324 }
325
326 // Check for missing redundancy.
327 if (redundancy() > 1) {
328 for (const EntryMetadata& metadata : entry_cache_) {
329 if (metadata.addresses().size() < redundancy()) {
330 error_detected_ = true;
David Rogers98fea472020-04-01 15:43:48 -0700331 return error_detected();
David Rogers9abe3c72020-03-24 19:03:13 -0700332 }
333 }
334 }
335
336 return error_detected();
337}
338
Keir Mierle8c352dc2020-02-02 13:58:19 -0800339Status KeyValueStore::LoadEntry(Address entry_address,
340 Address* next_entry_address) {
Wyatt Heplere541e072020-02-14 09:10:53 -0800341 Entry entry;
Wyatt Hepler22d0d9f2020-03-05 14:57:11 -0800342 TRY(Entry::Read(partition_, entry_address, formats_, &entry));
Keir Mierle8c352dc2020-02-02 13:58:19 -0800343
344 // Read the key from flash & validate the entry (which reads the value).
Wyatt Heplera00d1ef2020-02-14 14:31:26 -0800345 Entry::KeyBuffer key_buffer;
Wyatt Heplere541e072020-02-14 09:10:53 -0800346 TRY_ASSIGN(size_t key_length, entry.ReadKey(key_buffer));
347 const string_view key(key_buffer.data(), key_length);
Wyatt Heplerbab0e202020-02-04 07:40:08 -0800348
Wyatt Hepler22d0d9f2020-03-05 14:57:11 -0800349 TRY(entry.VerifyChecksumInFlash());
David Rogersf56131c2020-03-04 10:19:22 -0800350
351 // A valid entry was found, so update the next entry address before doing any
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700352 // of the checks that happen in AddNewOrUpdateExisting.
David Rogersf56131c2020-03-04 10:19:22 -0800353 *next_entry_address = entry.next_address();
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700354 return entry_cache_.AddNewOrUpdateExisting(
355 entry.descriptor(key), entry.address(), partition_.sector_size_bytes());
Keir Mierle8c352dc2020-02-02 13:58:19 -0800356}
357
Alexei Frolovd4adf912020-02-21 13:29:15 -0800358// Scans flash memory within a sector to find a KVS entry magic.
Alexei Frolovd4adf912020-02-21 13:29:15 -0800359Status KeyValueStore::ScanForEntry(const SectorDescriptor& sector,
360 Address start_address,
361 Address* next_entry_address) {
David Rogersfcea3252020-04-07 14:56:35 -0700362 DBG("Scanning sector %u for entries starting from address %u",
Wyatt Heplerc84393f2020-03-20 11:23:24 -0700363 sectors_.Index(sector),
David Rogersfcea3252020-04-07 14:56:35 -0700364 unsigned(start_address));
Alexei Frolovd4adf912020-02-21 13:29:15 -0800365
366 // Entries must start at addresses which are aligned on a multiple of
367 // Entry::kMinAlignmentBytes. However, that multiple can vary between entries.
368 // When scanning, we don't have an entry to tell us what the current alignment
369 // is, so the minimum alignment is used to be exhaustive.
370 for (Address address = AlignUp(start_address, Entry::kMinAlignmentBytes);
Wyatt Heplerc84393f2020-03-20 11:23:24 -0700371 sectors_.AddressInSector(sector, address);
Alexei Frolovd4adf912020-02-21 13:29:15 -0800372 address += Entry::kMinAlignmentBytes) {
Alexei Frolovd4adf912020-02-21 13:29:15 -0800373 uint32_t magic;
David Rogersfcea3252020-04-07 14:56:35 -0700374 StatusWithSize read_result =
375 partition_.Read(address, as_writable_bytes(span(&magic, 1)));
376 if (!read_result.ok()) {
377 continue;
378 }
Wyatt Hepler22d0d9f2020-03-05 14:57:11 -0800379 if (formats_.KnownMagic(magic)) {
David Rogersfcea3252020-04-07 14:56:35 -0700380 DBG("Found entry magic at address %u", unsigned(address));
Alexei Frolovd4adf912020-02-21 13:29:15 -0800381 *next_entry_address = address;
382 return Status::OK;
383 }
384 }
385
386 return Status::NOT_FOUND;
387}
388
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800389StatusWithSize KeyValueStore::Get(string_view key,
Wyatt Hepler5f6efc02020-02-18 16:54:31 -0800390 span<byte> value_buffer,
391 size_t offset_bytes) const {
David Rogers9abe3c72020-03-24 19:03:13 -0700392 TRY_WITH_SIZE(CheckReadOperation(key));
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800393
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700394 EntryMetadata metadata;
David Rogers98fea472020-04-01 15:43:48 -0700395 TRY_WITH_SIZE(FindExisting(key, &metadata));
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800396
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700397 return Get(key, metadata, value_buffer, offset_bytes);
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800398}
399
Wyatt Heplerfac81132020-02-27 17:26:33 -0800400Status KeyValueStore::PutBytes(string_view key, span<const byte> value) {
David Rogers9abe3c72020-03-24 19:03:13 -0700401 TRY(CheckWriteOperation(key));
Keir Mierle8c352dc2020-02-02 13:58:19 -0800402 DBG("Writing key/value; key length=%zu, value length=%zu",
403 key.size(),
404 value.size());
Wyatt Hepler729f28c2020-02-05 09:46:00 -0800405
Wyatt Hepler5406a672020-02-18 15:42:38 -0800406 if (Entry::size(partition_, key, value) > partition_.sector_size_bytes()) {
407 DBG("%zu B value with %zu B key cannot fit in one sector",
408 value.size(),
409 key.size());
410 return Status::INVALID_ARGUMENT;
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800411 }
412
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700413 EntryMetadata metadata;
David Rogers98fea472020-04-01 15:43:48 -0700414 Status status = FindEntry(key, &metadata);
Wyatt Hepler2d401692020-02-13 16:01:23 -0800415
416 if (status.ok()) {
David Rogersf56131c2020-03-04 10:19:22 -0800417 // TODO: figure out logging how to support multiple addresses.
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700418 DBG("Overwriting entry for key 0x%08" PRIx32 " in %zu sectors including %u",
419 metadata.hash(),
420 metadata.addresses().size(),
Wyatt Heplerc84393f2020-03-20 11:23:24 -0700421 sectors_.Index(metadata.first_address()));
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700422 return WriteEntryForExistingKey(metadata, EntryState::kValid, key, value);
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800423 }
David Rogers2761aeb2020-01-31 17:09:00 -0800424
Wyatt Hepler2d401692020-02-13 16:01:23 -0800425 if (status == Status::NOT_FOUND) {
426 return WriteEntryForNewKey(key, value);
427 }
428
429 return status;
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800430}
431
432Status KeyValueStore::Delete(string_view key) {
David Rogers9abe3c72020-03-24 19:03:13 -0700433 TRY(CheckWriteOperation(key));
Wyatt Hepler729f28c2020-02-05 09:46:00 -0800434
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700435 EntryMetadata metadata;
David Rogers98fea472020-04-01 15:43:48 -0700436 TRY(FindExisting(key, &metadata));
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800437
David Rogersf56131c2020-03-04 10:19:22 -0800438 // TODO: figure out logging how to support multiple addresses.
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700439 DBG("Writing tombstone for key 0x%08" PRIx32 " in %zu sectors including %u",
440 metadata.hash(),
441 metadata.addresses().size(),
Wyatt Heplerc84393f2020-03-20 11:23:24 -0700442 sectors_.Index(metadata.first_address()));
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700443 return WriteEntryForExistingKey(metadata, EntryState::kDeleted, key, {});
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800444}
445
Wyatt Hepler08d37d82020-02-27 15:45:37 -0800446void KeyValueStore::Item::ReadKey() {
447 key_buffer_.fill('\0');
448
449 Entry entry;
David Rogers98fea472020-04-01 15:43:48 -0700450 if (kvs_.ReadEntry(*iterator_, entry).ok()) {
Wyatt Hepler08d37d82020-02-27 15:45:37 -0800451 entry.ReadKey(key_buffer_);
452 }
453}
454
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800455KeyValueStore::iterator& KeyValueStore::iterator::operator++() {
456 // Skip to the next entry that is valid (not deleted).
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700457 while (++item_.iterator_ != item_.kvs_.entry_cache_.end() &&
Wyatt Hepler02946272020-03-18 10:36:22 -0700458 item_.iterator_->state() != EntryState::kValid) {
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800459 }
460 return *this;
461}
462
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800463KeyValueStore::iterator KeyValueStore::begin() const {
Wyatt Heplerbfc6a522020-04-01 16:30:24 -0700464 internal::EntryCache::const_iterator cache_iterator = entry_cache_.begin();
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800465 // Skip over any deleted entries at the start of the descriptor list.
Wyatt Hepler02946272020-03-18 10:36:22 -0700466 while (cache_iterator != entry_cache_.end() &&
467 cache_iterator->state() != EntryState::kValid) {
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700468 ++cache_iterator;
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800469 }
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700470 return iterator(*this, cache_iterator);
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800471}
472
Wyatt Heplerab3b2492020-03-11 16:15:16 -0700473StatusWithSize KeyValueStore::ValueSize(string_view key) const {
David Rogers9abe3c72020-03-24 19:03:13 -0700474 TRY_WITH_SIZE(CheckReadOperation(key));
Wyatt Heplered163b02020-02-03 17:49:32 -0800475
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700476 EntryMetadata metadata;
David Rogers98fea472020-04-01 15:43:48 -0700477 TRY_WITH_SIZE(FindExisting(key, &metadata));
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800478
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700479 return ValueSize(metadata);
Wyatt Heplerfac81132020-02-27 17:26:33 -0800480}
Wyatt Heplered163b02020-02-03 17:49:32 -0800481
David Rogers98fea472020-04-01 15:43:48 -0700482Status KeyValueStore::ReadEntry(const EntryMetadata& metadata,
483 Entry& entry) const {
484 // Try to read an entry
485 Status read_result = Status::DATA_LOSS;
486 for (Address address : metadata.addresses()) {
487 read_result = Entry::Read(partition_, address, formats_, &entry);
488 if (read_result.ok()) {
489 return read_result;
490 }
491
492 // Found a bad address. Set the sector as corrupt.
493 error_detected_ = true;
494 sectors_.FromAddress(address).mark_corrupt();
495 }
496
497 ERR("No valid entries for key. Data has been lost!");
498 return read_result;
499}
500
501Status KeyValueStore::FindEntry(string_view key,
502 EntryMetadata* found_entry) const {
503 StatusWithSize find_result =
504 entry_cache_.Find(partition_, sectors_, formats_, key, found_entry);
505
506 if (find_result.size() > 0u) {
507 error_detected_ = true;
508 }
509 return find_result.status();
510}
511
512Status KeyValueStore::FindExisting(string_view key,
513 EntryMetadata* metadata) const {
514 Status status = FindEntry(key, metadata);
515
516 // If the key's hash collides with an existing key or if the key is deleted,
517 // treat it as if it is not in the KVS.
518 if (status == Status::ALREADY_EXISTS ||
519 (status.ok() && metadata->state() == EntryState::kDeleted)) {
520 return Status::NOT_FOUND;
521 }
522 return status;
523}
524
Wyatt Heplerfac81132020-02-27 17:26:33 -0800525StatusWithSize KeyValueStore::Get(string_view key,
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700526 const EntryMetadata& metadata,
Wyatt Heplerfac81132020-02-27 17:26:33 -0800527 span<std::byte> value_buffer,
528 size_t offset_bytes) const {
529 Entry entry;
David Rogers98fea472020-04-01 15:43:48 -0700530
531 TRY_WITH_SIZE(ReadEntry(metadata, entry));
Wyatt Heplerfac81132020-02-27 17:26:33 -0800532
533 StatusWithSize result = entry.ReadValue(value_buffer, offset_bytes);
534 if (result.ok() && options_.verify_on_read && offset_bytes == 0u) {
Wyatt Hepler22d0d9f2020-03-05 14:57:11 -0800535 Status verify_result =
536 entry.VerifyChecksum(key, value_buffer.first(result.size()));
Wyatt Heplerfac81132020-02-27 17:26:33 -0800537 if (!verify_result.ok()) {
538 std::memset(value_buffer.data(), 0, result.size());
539 return StatusWithSize(verify_result, 0);
540 }
541
542 return StatusWithSize(verify_result, result.size());
543 }
544 return result;
Wyatt Heplered163b02020-02-03 17:49:32 -0800545}
546
Wyatt Hepler6e3a83b2020-02-04 07:36:45 -0800547Status KeyValueStore::FixedSizeGet(std::string_view key,
Wyatt Heplerfac81132020-02-27 17:26:33 -0800548 void* value,
549 size_t size_bytes) const {
David Rogers9abe3c72020-03-24 19:03:13 -0700550 TRY(CheckWriteOperation(key));
Wyatt Heplerfac81132020-02-27 17:26:33 -0800551
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700552 EntryMetadata metadata;
David Rogers98fea472020-04-01 15:43:48 -0700553 TRY(FindExisting(key, &metadata));
Wyatt Heplerfac81132020-02-27 17:26:33 -0800554
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700555 return FixedSizeGet(key, metadata, value, size_bytes);
Wyatt Heplerfac81132020-02-27 17:26:33 -0800556}
557
558Status KeyValueStore::FixedSizeGet(std::string_view key,
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700559 const EntryMetadata& metadata,
Wyatt Heplerfac81132020-02-27 17:26:33 -0800560 void* value,
Wyatt Hepler6e3a83b2020-02-04 07:36:45 -0800561 size_t size_bytes) const {
562 // Ensure that the size of the stored value matches the size of the type.
563 // Otherwise, report error. This check avoids potential memory corruption.
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700564 TRY_ASSIGN(const size_t actual_size, ValueSize(metadata));
Wyatt Heplerfac81132020-02-27 17:26:33 -0800565
566 if (actual_size != size_bytes) {
567 DBG("Requested %zu B read, but value is %zu B", size_bytes, actual_size);
Wyatt Hepler6e3a83b2020-02-04 07:36:45 -0800568 return Status::INVALID_ARGUMENT;
Wyatt Heplerbab0e202020-02-04 07:40:08 -0800569 }
Wyatt Heplerfac81132020-02-27 17:26:33 -0800570
571 StatusWithSize result =
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700572 Get(key, metadata, span(static_cast<byte*>(value), size_bytes), 0);
Wyatt Heplerfac81132020-02-27 17:26:33 -0800573
574 return result.status();
575}
576
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700577StatusWithSize KeyValueStore::ValueSize(const EntryMetadata& metadata) const {
Wyatt Heplerfac81132020-02-27 17:26:33 -0800578 Entry entry;
David Rogers98fea472020-04-01 15:43:48 -0700579 TRY_WITH_SIZE(ReadEntry(metadata, entry));
Wyatt Heplerfac81132020-02-27 17:26:33 -0800580
581 return StatusWithSize(entry.value_size());
Keir Mierle8c352dc2020-02-02 13:58:19 -0800582}
583
David Rogers9abe3c72020-03-24 19:03:13 -0700584Status KeyValueStore::CheckWriteOperation(string_view key) const {
Wyatt Hepleracaacf92020-01-24 10:58:30 -0800585 if (InvalidKey(key)) {
Wyatt Heplerb7609542020-01-24 10:29:54 -0800586 return Status::INVALID_ARGUMENT;
587 }
David Rogers9abe3c72020-03-24 19:03:13 -0700588
589 // For normal write operation the KVS must be fully ready.
Wyatt Heplerd2298282020-02-20 17:12:45 -0800590 if (!initialized()) {
Wyatt Heplerb7609542020-01-24 10:29:54 -0800591 return Status::FAILED_PRECONDITION;
592 }
Wyatt Heplerb7609542020-01-24 10:29:54 -0800593 return Status::OK;
594}
595
David Rogers9abe3c72020-03-24 19:03:13 -0700596Status KeyValueStore::CheckReadOperation(string_view key) const {
597 if (InvalidKey(key)) {
598 return Status::INVALID_ARGUMENT;
599 }
600
601 // Operations that are explicitly read-only can be done after init() has been
602 // called but not fully ready (when needing maintenance).
603 if (initialized_ == InitializationState::kNotInitialized) {
604 return Status::FAILED_PRECONDITION;
605 }
606 return Status::OK;
607}
608
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700609Status KeyValueStore::WriteEntryForExistingKey(EntryMetadata& metadata,
610 EntryState new_state,
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800611 string_view key,
612 span<const byte> value) {
Wyatt Heplerab3b2492020-03-11 16:15:16 -0700613 // Read the original entry to get the size for sector accounting purposes.
614 Entry entry;
David Rogers98fea472020-04-01 15:43:48 -0700615 TRY(ReadEntry(metadata, entry));
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800616
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700617 return WriteEntry(key, value, new_state, &metadata, entry.size());
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800618}
619
620Status KeyValueStore::WriteEntryForNewKey(string_view key,
621 span<const byte> value) {
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700622 if (entry_cache_.full()) {
Keir Mierle8c352dc2020-02-02 13:58:19 -0800623 WRN("KVS full: trying to store a new entry, but can't. Have %zu entries",
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700624 entry_cache_.total_entries());
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800625 return Status::RESOURCE_EXHAUSTED;
626 }
627
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700628 return WriteEntry(key, value, EntryState::kValid);
Wyatt Heplerab3b2492020-03-11 16:15:16 -0700629}
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800630
Wyatt Heplerab3b2492020-03-11 16:15:16 -0700631Status KeyValueStore::WriteEntry(string_view key,
632 span<const byte> value,
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700633 EntryState new_state,
634 EntryMetadata* prior_metadata,
Wyatt Heplerab3b2492020-03-11 16:15:16 -0700635 size_t prior_size) {
636 const size_t entry_size = Entry::size(partition_, key, value);
637
638 // List of addresses for sectors with space for this entry.
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700639 Address* reserved_addresses = entry_cache_.TempReservedAddressesForWrite();
Wyatt Heplerab3b2492020-03-11 16:15:16 -0700640
David Rogers31b358b2020-04-15 05:00:50 -0700641 // Find addresses to write the entry to. This may involve garbage collecting
642 // one or more sectors.
643 TRY(GetAddressesForWrite(reserved_addresses, entry_size));
Wyatt Heplerab3b2492020-03-11 16:15:16 -0700644
645 // Write the entry at the first address that was found.
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700646 Entry entry = CreateEntry(reserved_addresses[0], key, value, new_state);
Wyatt Heplerab3b2492020-03-11 16:15:16 -0700647 TRY(AppendEntry(entry, key, value));
648
649 // After writing the first entry successfully, update the key descriptors.
650 // Once a single new the entry is written, the old entries are invalidated.
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700651 EntryMetadata new_metadata =
David Rogers31b358b2020-04-15 05:00:50 -0700652 CreateOrUpdateKeyDescriptor(entry, key, prior_metadata, prior_size);
Wyatt Heplerab3b2492020-03-11 16:15:16 -0700653
654 // Write the additional copies of the entry, if redundancy is greater than 1.
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700655 for (size_t i = 1; i < redundancy(); ++i) {
656 entry.set_address(reserved_addresses[i]);
Wyatt Heplerab3b2492020-03-11 16:15:16 -0700657 TRY(AppendEntry(entry, key, value));
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700658 new_metadata.AddNewAddress(reserved_addresses[i]);
Wyatt Heplerab3b2492020-03-11 16:15:16 -0700659 }
Wyatt Heplerb7609542020-01-24 10:29:54 -0800660 return Status::OK;
661}
662
David Rogers31b358b2020-04-15 05:00:50 -0700663KeyValueStore::EntryMetadata KeyValueStore::CreateOrUpdateKeyDescriptor(
Wyatt Heplerab3b2492020-03-11 16:15:16 -0700664 const Entry& entry,
665 string_view key,
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700666 EntryMetadata* prior_metadata,
Wyatt Heplerab3b2492020-03-11 16:15:16 -0700667 size_t prior_size) {
668 // If there is no prior descriptor, create a new one.
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700669 if (prior_metadata == nullptr) {
670 return entry_cache_.AddNew(entry.descriptor(key), entry.address());
David Rogersa2562b52020-03-05 15:30:05 -0800671 }
672
David Rogers31b358b2020-04-15 05:00:50 -0700673 return UpdateKeyDescriptor(
674 entry, entry.address(), prior_metadata, prior_size);
675}
676
677KeyValueStore::EntryMetadata KeyValueStore::UpdateKeyDescriptor(
678 const Entry& entry,
679 Address new_address,
680 EntryMetadata* prior_metadata,
681 size_t prior_size) {
Wyatt Heplerab3b2492020-03-11 16:15:16 -0700682 // Remove valid bytes for the old entry and its copies, which are now stale.
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700683 for (Address address : prior_metadata->addresses()) {
Wyatt Heplerc84393f2020-03-20 11:23:24 -0700684 sectors_.FromAddress(address).RemoveValidBytes(prior_size);
David Rogersa2562b52020-03-05 15:30:05 -0800685 }
686
David Rogers31b358b2020-04-15 05:00:50 -0700687 prior_metadata->Reset(entry.descriptor(prior_metadata->hash()), new_address);
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700688 return *prior_metadata;
David Rogersa2562b52020-03-05 15:30:05 -0800689}
690
David Rogers31b358b2020-04-15 05:00:50 -0700691Status KeyValueStore::GetAddressesForWrite(Address* write_addresses,
692 size_t write_size) {
693 for (size_t i = 0; i < redundancy(); i++) {
694 SectorDescriptor* sector;
695 TRY(GetSectorForWrite(&sector, write_size, span(write_addresses, i)));
696 write_addresses[i] = sectors_.NextWritableAddress(*sector);
697
698 DBG("Found space for entry in sector %u at address %u",
699 sectors_.Index(sector),
700 unsigned(write_addresses[i]));
701 }
702
703 return Status::OK;
704}
705
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700706// Finds a sector to use for writing a new entry to. Does automatic garbage
David Rogersa2562b52020-03-05 15:30:05 -0800707// collection if needed and allowed.
708//
709// OK: Sector found with needed space.
710// RESOURCE_EXHAUSTED: No sector available with the needed space.
711Status KeyValueStore::GetSectorForWrite(SectorDescriptor** sector,
712 size_t entry_size,
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700713 span<const Address> reserved) {
Wyatt Heplerc84393f2020-03-20 11:23:24 -0700714 Status result = sectors_.FindSpace(sector, entry_size, reserved);
David Rogersa2562b52020-03-05 15:30:05 -0800715
David Rogersf3884eb2020-03-08 19:21:40 -0700716 size_t gc_sector_count = 0;
David Rogersa2562b52020-03-05 15:30:05 -0800717 bool do_auto_gc = options_.gc_on_write != GargbageCollectOnWrite::kDisabled;
718
719 // Do garbage collection as needed, so long as policy allows.
720 while (result == Status::RESOURCE_EXHAUSTED && do_auto_gc) {
721 if (options_.gc_on_write == GargbageCollectOnWrite::kOneSector) {
722 // If GC config option is kOneSector clear the flag to not do any more
723 // GC after this try.
724 do_auto_gc = false;
725 }
726 // Garbage collect and then try again to find the best sector.
David Rogers9abe3c72020-03-24 19:03:13 -0700727 Status gc_status = GarbageCollect(reserved);
David Rogersa2562b52020-03-05 15:30:05 -0800728 if (!gc_status.ok()) {
729 if (gc_status == Status::NOT_FOUND) {
730 // Not enough space, and no reclaimable bytes, this KVS is full!
731 return Status::RESOURCE_EXHAUSTED;
732 }
733 return gc_status;
734 }
735
Wyatt Heplerc84393f2020-03-20 11:23:24 -0700736 result = sectors_.FindSpace(sector, entry_size, reserved);
David Rogersf3884eb2020-03-08 19:21:40 -0700737
738 gc_sector_count++;
739 // Allow total sectors + 2 number of GC cycles so that once reclaimable
740 // bytes in all the sectors have been reclaimed can try and free up space by
741 // moving entries for keys other than the one being worked on in to sectors
742 // that have copies of the key trying to be written.
743 if (gc_sector_count > (partition_.sector_count() + 2)) {
744 ERR("Did more GC sectors than total sectors!!!!");
745 return Status::RESOURCE_EXHAUSTED;
746 }
David Rogersa2562b52020-03-05 15:30:05 -0800747 }
748
749 if (!result.ok()) {
750 WRN("Unable to find sector to write %zu B", entry_size);
751 }
752 return result;
753}
754
David Rogers9abe3c72020-03-24 19:03:13 -0700755Status KeyValueStore::MarkSectorCorruptIfNotOk(Status status,
756 SectorDescriptor* sector) {
757 if (!status.ok()) {
758 DBG(" Sector %u corrupt", sectors_.Index(sector));
759 sector->mark_corrupt();
760 error_detected_ = true;
761 }
762 return status;
763}
764
Wyatt Heplerab3b2492020-03-11 16:15:16 -0700765Status KeyValueStore::AppendEntry(const Entry& entry,
David Rogersa2562b52020-03-05 15:30:05 -0800766 string_view key,
767 span<const byte> value) {
Wyatt Heplerab3b2492020-03-11 16:15:16 -0700768 const StatusWithSize result = entry.Write(key, value);
David Rogersa2562b52020-03-05 15:30:05 -0800769
Wyatt Heplerc84393f2020-03-20 11:23:24 -0700770 SectorDescriptor& sector = sectors_.FromAddress(entry.address());
David Rogersa2562b52020-03-05 15:30:05 -0800771
772 if (!result.ok()) {
773 ERR("Failed to write %zu bytes at %#zx. %zu actually written",
774 entry.size(),
Wyatt Heplerab3b2492020-03-11 16:15:16 -0700775 size_t(entry.address()),
David Rogersa2562b52020-03-05 15:30:05 -0800776 result.size());
David Rogers9abe3c72020-03-24 19:03:13 -0700777 TRY(MarkSectorCorruptIfNotOk(result.status(), &sector));
David Rogersa2562b52020-03-05 15:30:05 -0800778 }
779
780 if (options_.verify_on_write) {
David Rogers9abe3c72020-03-24 19:03:13 -0700781 TRY(MarkSectorCorruptIfNotOk(entry.VerifyChecksumInFlash(), &sector));
David Rogersa2562b52020-03-05 15:30:05 -0800782 }
783
David Rogers98fea472020-04-01 15:43:48 -0700784 sector.RemoveWritableBytes(result.size());
Wyatt Heplerc84393f2020-03-20 11:23:24 -0700785 sector.AddValidBytes(result.size());
David Rogersa2562b52020-03-05 15:30:05 -0800786 return Status::OK;
787}
788
David Rogers98fea472020-04-01 15:43:48 -0700789StatusWithSize KeyValueStore::CopyEntryToSector(Entry& entry,
790 SectorDescriptor* new_sector,
David Rogers31b358b2020-04-15 05:00:50 -0700791 Address new_address) {
David Rogers98fea472020-04-01 15:43:48 -0700792 const StatusWithSize result = entry.Copy(new_address);
793
794 TRY_WITH_SIZE(MarkSectorCorruptIfNotOk(result.status(), new_sector));
795
796 if (options_.verify_on_write) {
David Rogers31b358b2020-04-15 05:00:50 -0700797 Entry new_entry;
798 TRY_WITH_SIZE(MarkSectorCorruptIfNotOk(
799 Entry::Read(partition_, new_address, formats_, &new_entry),
800 new_sector));
801 // TODO: add test that catches doing the verify on the old entry.
802 TRY_WITH_SIZE(MarkSectorCorruptIfNotOk(new_entry.VerifyChecksumInFlash(),
803 new_sector));
David Rogers98fea472020-04-01 15:43:48 -0700804 }
805 // Entry was written successfully; update descriptor's address and the sector
806 // descriptors to reflect the new entry.
807 new_sector->RemoveWritableBytes(result.size());
808 new_sector->AddValidBytes(result.size());
809
810 return result;
811}
812
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700813Status KeyValueStore::RelocateEntry(const EntryMetadata& metadata,
Wyatt Heplerab3b2492020-03-11 16:15:16 -0700814 KeyValueStore::Address& address,
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700815 span<const Address> reserved_addresses) {
David Rogersa2562b52020-03-05 15:30:05 -0800816 Entry entry;
David Rogers98fea472020-04-01 15:43:48 -0700817 TRY(ReadEntry(metadata, entry));
David Rogersa2562b52020-03-05 15:30:05 -0800818
819 // Find a new sector for the entry and write it to the new location. For
820 // relocation the find should not not be a sector already containing the key
821 // but can be the always empty sector, since this is part of the GC process
822 // that will result in a new empty sector. Also find a sector that does not
823 // have reclaimable space (mostly for the full GC, where that would result in
824 // an immediate extra relocation).
825 SectorDescriptor* new_sector;
826
Wyatt Heplerc84393f2020-03-20 11:23:24 -0700827 TRY(sectors_.FindSpaceDuringGarbageCollection(
828 &new_sector, entry.size(), metadata.addresses(), reserved_addresses));
Wyatt Heplerab3b2492020-03-11 16:15:16 -0700829
David Rogers31b358b2020-04-15 05:00:50 -0700830 Address new_address = sectors_.NextWritableAddress(*new_sector);
David Rogers98fea472020-04-01 15:43:48 -0700831 TRY_ASSIGN(const size_t result_size,
832 CopyEntryToSector(entry, new_sector, new_address));
833 sectors_.FromAddress(address).RemoveValidBytes(result_size);
Wyatt Heplerab3b2492020-03-11 16:15:16 -0700834 address = new_address;
David Rogersa2562b52020-03-05 15:30:05 -0800835
836 return Status::OK;
837}
838
David Rogers9abe3c72020-03-24 19:03:13 -0700839Status KeyValueStore::FullMaintenance() {
840 if (initialized_ == InitializationState::kNotInitialized) {
841 return Status::FAILED_PRECONDITION;
842 }
843
844 DBG("Do full maintenance");
David Rogers98fea472020-04-01 15:43:48 -0700845 CheckForErrors();
David Rogers9abe3c72020-03-24 19:03:13 -0700846
847 if (error_detected_) {
848 TRY(Repair());
849 }
Wyatt Heplerc84393f2020-03-20 11:23:24 -0700850
David Rogers31b358b2020-04-15 05:00:50 -0700851 // Make sure all the entries are on the primary format.
852 UpdateEntriesToPrimaryFormat();
853
Wyatt Heplerc84393f2020-03-20 11:23:24 -0700854 SectorDescriptor* sector = sectors_.last_new();
David Rogerscd87c322020-02-27 14:04:08 -0800855
856 // TODO: look in to making an iterator method for cycling through sectors
857 // starting from last_new_sector_.
858 for (size_t j = 0; j < sectors_.size(); j++) {
859 sector += 1;
860 if (sector == sectors_.end()) {
861 sector = sectors_.begin();
862 }
863
864 if (sector->RecoverableBytes(partition_.sector_size_bytes()) > 0) {
Wyatt Heplerc84393f2020-03-20 11:23:24 -0700865 TRY(GarbageCollectSector(*sector, {}));
David Rogerscd87c322020-02-27 14:04:08 -0800866 }
867 }
868
David Rogers9abe3c72020-03-24 19:03:13 -0700869 DBG("Full maintenance complete");
David Rogerscd87c322020-02-27 14:04:08 -0800870 return Status::OK;
871}
872
David Rogers9abe3c72020-03-24 19:03:13 -0700873Status KeyValueStore::GarbageCollect(span<const Address> reserved_addresses) {
874 if (initialized_ == InitializationState::kNotInitialized) {
875 return Status::FAILED_PRECONDITION;
876 }
877
David Rogersc9d545e2020-03-11 17:47:43 -0700878 DBG("Garbage Collect a single sector");
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700879 for (Address address : reserved_addresses) {
David Rogersc9d545e2020-03-11 17:47:43 -0700880 DBG(" Avoid address %u", unsigned(address));
881 }
David Rogers67f4b6c2020-02-06 16:17:09 -0800882
David Rogersfcea3252020-04-07 14:56:35 -0700883 // Do automatic repair, if KVS options allow for it.
884 if (error_detected_ && options_.recovery != ErrorRecovery::kManual) {
885 TRY(Repair());
886 }
887
David Rogersa12786b2020-01-31 16:02:33 -0800888 // Step 1: Find the sector to garbage collect
David Rogersc9d545e2020-03-11 17:47:43 -0700889 SectorDescriptor* sector_to_gc =
Wyatt Heplerc84393f2020-03-20 11:23:24 -0700890 sectors_.FindSectorToGarbageCollect(reserved_addresses);
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800891
David Rogersa12786b2020-01-31 16:02:33 -0800892 if (sector_to_gc == nullptr) {
David Rogersa2562b52020-03-05 15:30:05 -0800893 // Nothing to GC.
894 return Status::NOT_FOUND;
David Rogersa12786b2020-01-31 16:02:33 -0800895 }
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800896
David Rogersc9d545e2020-03-11 17:47:43 -0700897 // Step 2: Garbage collect the selected sector.
Wyatt Heplerc84393f2020-03-20 11:23:24 -0700898 return GarbageCollectSector(*sector_to_gc, reserved_addresses);
David Rogerscd87c322020-02-27 14:04:08 -0800899}
900
David Rogersf3884eb2020-03-08 19:21:40 -0700901Status KeyValueStore::RelocateKeyAddressesInSector(
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700902 SectorDescriptor& sector_to_gc,
David Rogersfcea3252020-04-07 14:56:35 -0700903 const EntryMetadata& metadata,
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700904 span<const Address> reserved_addresses) {
905 for (FlashPartition::Address& address : metadata.addresses()) {
Wyatt Heplerc84393f2020-03-20 11:23:24 -0700906 if (sectors_.AddressInSector(sector_to_gc, address)) {
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700907 DBG(" Relocate entry for Key 0x%08" PRIx32 ", sector %u",
908 metadata.hash(),
Wyatt Heplerc84393f2020-03-20 11:23:24 -0700909 sectors_.Index(sectors_.FromAddress(address)));
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700910 TRY(RelocateEntry(metadata, address, reserved_addresses));
David Rogersf3884eb2020-03-08 19:21:40 -0700911 }
912 }
Wyatt Heplerab3b2492020-03-11 16:15:16 -0700913
David Rogersf3884eb2020-03-08 19:21:40 -0700914 return Status::OK;
915};
916
Wyatt Heplerab3b2492020-03-11 16:15:16 -0700917Status KeyValueStore::GarbageCollectSector(
Wyatt Heplerc84393f2020-03-20 11:23:24 -0700918 SectorDescriptor& sector_to_gc, span<const Address> reserved_addresses) {
David Rogers9abe3c72020-03-24 19:03:13 -0700919 DBG(" Garbage Collect sector %u", sectors_.Index(sector_to_gc));
David Rogersf3884eb2020-03-08 19:21:40 -0700920 // Step 1: Move any valid entries in the GC sector to other sectors
Wyatt Heplerc84393f2020-03-20 11:23:24 -0700921 if (sector_to_gc.valid_bytes() != 0) {
David Rogers98fea472020-04-01 15:43:48 -0700922 for (EntryMetadata& metadata : entry_cache_) {
Wyatt Heplerab3b2492020-03-11 16:15:16 -0700923 TRY(RelocateKeyAddressesInSector(
Wyatt Heplerc84393f2020-03-20 11:23:24 -0700924 sector_to_gc, metadata, reserved_addresses));
David Rogersf3884eb2020-03-08 19:21:40 -0700925 }
926 }
927
Wyatt Heplerc84393f2020-03-20 11:23:24 -0700928 if (sector_to_gc.valid_bytes() != 0) {
David Rogers67f4b6c2020-02-06 16:17:09 -0800929 ERR(" Failed to relocate valid entries from sector being garbage "
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800930 "collected, %zu valid bytes remain",
Wyatt Heplerc84393f2020-03-20 11:23:24 -0700931 sector_to_gc.valid_bytes());
Wyatt Heplerb7609542020-01-24 10:29:54 -0800932 return Status::INTERNAL;
933 }
934
David Rogerscd87c322020-02-27 14:04:08 -0800935 // Step 2: Reinitialize the sector
David Rogers9abe3c72020-03-24 19:03:13 -0700936 sector_to_gc.mark_corrupt();
Wyatt Heplerc84393f2020-03-20 11:23:24 -0700937 TRY(partition_.Erase(sectors_.BaseAddress(sector_to_gc), 1));
938 sector_to_gc.set_writable_bytes(partition_.sector_size_bytes());
Wyatt Heplerb7609542020-01-24 10:29:54 -0800939
Wyatt Heplerc84393f2020-03-20 11:23:24 -0700940 DBG(" Garbage Collect sector %u complete", sectors_.Index(sector_to_gc));
David Rogersa12786b2020-01-31 16:02:33 -0800941 return Status::OK;
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800942}
943
David Rogers31b358b2020-04-15 05:00:50 -0700944Status KeyValueStore::UpdateEntriesToPrimaryFormat() {
945 for (EntryMetadata& prior_metadata : entry_cache_) {
946 Entry entry;
947 TRY(ReadEntry(prior_metadata, entry));
948 if (formats_.primary().magic == entry.magic()) {
949 // Ignore entries that are already on the primary format.
950 continue;
951 }
952
953 DBG("Updating entry 0x%08x from old format [0x%08x] to new format "
954 "[0x%08x]",
955 unsigned(prior_metadata.hash()),
956 unsigned(entry.magic()),
957 unsigned(formats_.primary().magic));
958
959 last_transaction_id_ += 1;
960 TRY(entry.Update(formats_.primary(), last_transaction_id_));
961
962 // List of addresses for sectors with space for this entry.
963 Address* reserved_addresses = entry_cache_.TempReservedAddressesForWrite();
964
965 // Find addresses to write the entry to. This may involve garbage collecting
966 // one or more sectors.
967 TRY(GetAddressesForWrite(reserved_addresses, entry.size()));
968
969 TRY(CopyEntryToSector(entry,
970 &sectors_.FromAddress(reserved_addresses[0]),
971 reserved_addresses[0]));
972
973 // After writing the first entry successfully, update the key descriptors.
974 // Once a single new the entry is written, the old entries are invalidated.
975 EntryMetadata new_metadata = UpdateKeyDescriptor(
976 entry, reserved_addresses[0], &prior_metadata, entry.size());
977
978 // Write the additional copies of the entry, if redundancy is greater
979 // than 1.
980 for (size_t i = 1; i < redundancy(); ++i) {
981 TRY(CopyEntryToSector(entry,
982 &sectors_.FromAddress(reserved_addresses[i]),
983 reserved_addresses[i]));
984 new_metadata.AddNewAddress(reserved_addresses[i]);
985 }
986 }
987 return Status::OK;
988}
989
David Rogers9abe3c72020-03-24 19:03:13 -0700990// Add any missing redundant entries/copies for a key.
991Status KeyValueStore::AddRedundantEntries(EntryMetadata& metadata) {
992 SectorDescriptor* new_sector;
993
994 Entry entry;
995
David Rogers98fea472020-04-01 15:43:48 -0700996 TRY(ReadEntry(metadata, entry));
David Rogers9abe3c72020-03-24 19:03:13 -0700997 TRY(entry.VerifyChecksumInFlash());
998
999 for (size_t i = metadata.addresses().size();
1000 metadata.addresses().size() < redundancy();
1001 i++) {
1002 TRY(sectors_.FindSpace(&new_sector, entry.size(), metadata.addresses()));
1003
David Rogers31b358b2020-04-15 05:00:50 -07001004 Address new_address = sectors_.NextWritableAddress(*new_sector);
David Rogers98fea472020-04-01 15:43:48 -07001005 TRY(CopyEntryToSector(entry, new_sector, new_address));
David Rogers9abe3c72020-03-24 19:03:13 -07001006
1007 metadata.AddNewAddress(new_address);
1008 }
1009 return Status::OK;
1010}
1011
1012Status KeyValueStore::RepairCorruptSectors() {
1013 // Try to GC each corrupt sector, even if previous sectors fail. If GC of a
1014 // sector failed on the first pass, then do a second pass, since a later
1015 // sector might have cleared up space or otherwise unblocked the earlier
1016 // failed sector.
1017 Status repair_status = Status::OK;
1018
1019 size_t loop_count = 0;
1020 do {
1021 loop_count++;
1022 // Error of RESOURCE_EXHAUSTED indicates no space found for relocation.
1023 // Reset back to OK for the next pass.
1024 if (repair_status == Status::RESOURCE_EXHAUSTED) {
1025 repair_status = Status::OK;
1026 }
1027
1028 DBG(" Pass %u", unsigned(loop_count));
1029 for (SectorDescriptor& sector : sectors_) {
1030 if (sector.corrupt()) {
1031 DBG(" Found sector %u with corruption", sectors_.Index(sector));
1032 Status sector_status = GarbageCollectSector(sector, {});
1033 if (sector_status.ok()) {
1034 error_stats_.corrupt_sectors_recovered += 1;
1035 } else if (repair_status.ok() ||
1036 repair_status == Status::RESOURCE_EXHAUSTED) {
1037 repair_status = sector_status;
1038 }
1039 }
1040 }
1041 DBG(" Pass %u complete", unsigned(loop_count));
1042 } while (!repair_status.ok() && loop_count < 2);
1043
1044 return repair_status;
1045}
1046
1047Status KeyValueStore::EnsureFreeSectorExists() {
1048 Status repair_status = Status::OK;
1049 bool empty_sector_found = false;
1050
1051 DBG(" Find empty sector");
1052 for (SectorDescriptor& sector : sectors_) {
1053 if (sector.Empty(partition_.sector_size_bytes())) {
1054 empty_sector_found = true;
1055 DBG(" Empty sector found");
1056 break;
1057 }
1058 }
1059 if (empty_sector_found == false) {
1060 DBG(" No empty sector found, attempting to GC a free sector");
1061 Status sector_status = GarbageCollect(span<const Address, 0>());
1062 if (repair_status.ok() && !sector_status.ok()) {
1063 DBG(" Unable to free an empty sector");
1064 repair_status = sector_status;
1065 }
1066 }
1067
1068 return repair_status;
1069}
1070
1071Status KeyValueStore::EnsureEntryRedundancy() {
1072 Status repair_status = Status::OK;
1073
1074 if (redundancy() == 1) {
David Rogers98fea472020-04-01 15:43:48 -07001075 DBG(" Redundancy not in use, nothting to check");
David Rogers9abe3c72020-03-24 19:03:13 -07001076 return Status::OK;
1077 }
1078
David Rogers98fea472020-04-01 15:43:48 -07001079 DBG(" Write any needed additional duplicate copies of keys to fulfill %u"
1080 " redundancy",
David Rogers9abe3c72020-03-24 19:03:13 -07001081 unsigned(redundancy()));
David Rogers98fea472020-04-01 15:43:48 -07001082 for (EntryMetadata& metadata : entry_cache_) {
David Rogers9abe3c72020-03-24 19:03:13 -07001083 if (metadata.addresses().size() >= redundancy()) {
1084 continue;
1085 }
1086
1087 DBG(" Key with %u of %u copies found, adding missing copies",
1088 unsigned(metadata.addresses().size()),
1089 unsigned(redundancy()));
David Rogers98fea472020-04-01 15:43:48 -07001090 Status fill_status = AddRedundantEntries(metadata);
David Rogers9abe3c72020-03-24 19:03:13 -07001091 if (fill_status.ok()) {
1092 error_stats_.missing_redundant_entries_recovered += 1;
1093 DBG(" Key missing copies added");
1094 } else {
1095 DBG(" Failed to add key missing copies");
1096 if (repair_status.ok()) {
1097 repair_status = fill_status;
1098 }
1099 }
1100 }
1101
1102 return repair_status;
1103}
1104
David Rogersfcea3252020-04-07 14:56:35 -07001105Status KeyValueStore::FixErrors() {
1106 DBG("Fixing KVS errors");
David Rogers9abe3c72020-03-24 19:03:13 -07001107
1108 // Step 1: Garbage collect any sectors marked as corrupt.
David Rogersfcea3252020-04-07 14:56:35 -07001109 Status overall_status = RepairCorruptSectors();
David Rogers9abe3c72020-03-24 19:03:13 -07001110
1111 // Step 2: Make sure there is at least 1 empty sector. This needs to be a
1112 // seperate check of sectors from step 1, because a found empty sector might
1113 // get written to by a later GC that fails and does not result in a free
1114 // sector.
David Rogersfcea3252020-04-07 14:56:35 -07001115 Status repair_status = EnsureFreeSectorExists();
David Rogers9abe3c72020-03-24 19:03:13 -07001116 if (overall_status.ok()) {
1117 overall_status = repair_status;
1118 }
1119
1120 // Step 3: Make sure each stored key has the full number of redundant
1121 // entries.
1122 repair_status = EnsureEntryRedundancy();
1123 if (overall_status.ok()) {
1124 overall_status = repair_status;
1125 }
1126
1127 if (overall_status.ok()) {
1128 error_detected_ = false;
1129 initialized_ = InitializationState::kReady;
1130 }
1131 return overall_status;
1132}
1133
David Rogersfcea3252020-04-07 14:56:35 -07001134Status KeyValueStore::Repair() {
1135 // If errors have been detected, just reinit the KVS metadata. This does a
1136 // full deep error check and any needed repairs. Then repair any errors.
1137 INF("Starting KVS repair");
1138
1139 DBG("Reinitialize KVS metadata");
1140 InitializeMetadata();
1141
1142 return FixErrors();
1143}
1144
Wyatt Heplerbdd8e5a2020-02-20 19:27:26 -08001145KeyValueStore::Entry KeyValueStore::CreateEntry(Address address,
Wyatt Heplerab3b2492020-03-11 16:15:16 -07001146 string_view key,
Wyatt Heplerbdd8e5a2020-02-20 19:27:26 -08001147 span<const byte> value,
Wyatt Hepler7ded6da2020-03-11 18:24:43 -07001148 EntryState state) {
Keir Mierle9e38b402020-02-21 13:06:21 -08001149 // Always bump the transaction ID when creating a new entry.
1150 //
1151 // Burning transaction IDs prevents inconsistencies between flash and memory
1152 // that which could happen if a write succeeds, but for some reason the read
1153 // and verify step fails. Here's how this would happen:
1154 //
1155 // 1. The entry is written but for some reason the flash reports failure OR
1156 // The write succeeds, but the read / verify operation fails.
1157 // 2. The transaction ID is NOT incremented, because of the failure
1158 // 3. (later) A new entry is written, re-using the transaction ID (oops)
1159 //
1160 // By always burning transaction IDs, the above problem can't happen.
1161 last_transaction_id_ += 1;
1162
Wyatt Hepler7ded6da2020-03-11 18:24:43 -07001163 if (state == EntryState::kDeleted) {
Wyatt Hepler7465be32020-02-21 15:30:53 -08001164 return Entry::Tombstone(
Wyatt Hepler22d0d9f2020-03-05 14:57:11 -08001165 partition_, address, formats_.primary(), key, last_transaction_id_);
Wyatt Hepler1fc11042020-02-19 17:17:51 -08001166 }
1167 return Entry::Valid(partition_,
1168 address,
Wyatt Hepler22d0d9f2020-03-05 14:57:11 -08001169 formats_.primary(),
Wyatt Hepler1fc11042020-02-19 17:17:51 -08001170 key,
1171 value,
Keir Mierle9e38b402020-02-21 13:06:21 -08001172 last_transaction_id_);
Wyatt Heplerd2298282020-02-20 17:12:45 -08001173}
1174
Wyatt Hepler7ded6da2020-03-11 18:24:43 -07001175void KeyValueStore::LogDebugInfo() const {
Keir Mierle8c352dc2020-02-02 13:58:19 -08001176 const size_t sector_size_bytes = partition_.sector_size_bytes();
1177 DBG("====================== KEY VALUE STORE DUMP =========================");
1178 DBG(" ");
1179 DBG("Flash partition:");
Wyatt Heplerad0a7932020-02-06 08:20:38 -08001180 DBG(" Sector count = %zu", partition_.sector_count());
Wyatt Hepler38ce30f2020-02-19 11:48:31 -08001181 DBG(" Sector max count = %zu", sectors_.max_size());
Wyatt Hepler1c329ca2020-02-07 18:07:23 -08001182 DBG(" Sectors in use = %zu", sectors_.size());
Keir Mierle8c352dc2020-02-02 13:58:19 -08001183 DBG(" Sector size = %zu", sector_size_bytes);
1184 DBG(" Total size = %zu", partition_.size_bytes());
1185 DBG(" Alignment = %zu", partition_.alignment_bytes());
1186 DBG(" ");
1187 DBG("Key descriptors:");
Wyatt Hepler7ded6da2020-03-11 18:24:43 -07001188 DBG(" Entry count = %zu", entry_cache_.total_entries());
1189 DBG(" Max entry count = %zu", entry_cache_.max_entries());
Keir Mierle8c352dc2020-02-02 13:58:19 -08001190 DBG(" ");
1191 DBG(" # hash version address address (hex)");
Wyatt Hepler7ded6da2020-03-11 18:24:43 -07001192 size_t i = 0;
1193 for (const EntryMetadata& metadata : entry_cache_) {
Keir Mierle8c352dc2020-02-02 13:58:19 -08001194 DBG(" |%3zu: | %8zx |%8zu | %8zu | %8zx",
Wyatt Hepler7ded6da2020-03-11 18:24:43 -07001195 i++,
1196 size_t(metadata.hash()),
1197 size_t(metadata.transaction_id()),
1198 size_t(metadata.first_address()),
1199 size_t(metadata.first_address()));
Keir Mierle8c352dc2020-02-02 13:58:19 -08001200 }
1201 DBG(" ");
1202
1203 DBG("Sector descriptors:");
1204 DBG(" # tail free valid has_space");
Wyatt Heplerc84393f2020-03-20 11:23:24 -07001205 for (const SectorDescriptor& sd : sectors_) {
1206 DBG(" |%3u: | %8zu |%8zu | %s",
1207 sectors_.Index(sd),
Wyatt Hepler2c7eca02020-02-18 16:01:42 -08001208 size_t(sd.writable_bytes()),
1209 sd.valid_bytes(),
1210 sd.writable_bytes() ? "YES" : "");
Keir Mierle8c352dc2020-02-02 13:58:19 -08001211 }
1212 DBG(" ");
1213
1214 // TODO: This should stop logging after some threshold.
1215 // size_t dumped_bytes = 0;
1216 DBG("Sector raw data:");
Wyatt Hepler1c329ca2020-02-07 18:07:23 -08001217 for (size_t sector_id = 0; sector_id < sectors_.size(); ++sector_id) {
Keir Mierle8c352dc2020-02-02 13:58:19 -08001218 // Read sector data. Yes, this will blow the stack on embedded.
Wyatt Hepler1c329ca2020-02-07 18:07:23 -08001219 std::array<byte, 500> raw_sector_data; // TODO!!!
Keir Mierle8c352dc2020-02-02 13:58:19 -08001220 StatusWithSize sws =
1221 partition_.Read(sector_id * sector_size_bytes, raw_sector_data);
1222 DBG("Read: %zu bytes", sws.size());
1223
1224 DBG(" base addr offs 0 1 2 3 4 5 6 7");
1225 for (size_t i = 0; i < sector_size_bytes; i += 8) {
1226 DBG(" %3zu %8zx %5zu | %02x %02x %02x %02x %02x %02x %02x %02x",
1227 sector_id,
1228 (sector_id * sector_size_bytes) + i,
1229 i,
1230 static_cast<unsigned int>(raw_sector_data[i + 0]),
1231 static_cast<unsigned int>(raw_sector_data[i + 1]),
1232 static_cast<unsigned int>(raw_sector_data[i + 2]),
1233 static_cast<unsigned int>(raw_sector_data[i + 3]),
1234 static_cast<unsigned int>(raw_sector_data[i + 4]),
1235 static_cast<unsigned int>(raw_sector_data[i + 5]),
1236 static_cast<unsigned int>(raw_sector_data[i + 6]),
1237 static_cast<unsigned int>(raw_sector_data[i + 7]));
1238
1239 // TODO: Fix exit condition.
1240 if (i > 128) {
1241 break;
1242 }
1243 }
1244 DBG(" ");
1245 }
1246
1247 DBG("////////////////////// KEY VALUE STORE DUMP END /////////////////////");
1248}
1249
David Rogerscf680ab2020-02-12 23:28:32 -08001250void KeyValueStore::LogSectors() const {
1251 DBG("Sector descriptors: count %zu", sectors_.size());
Wyatt Hepler1c329ca2020-02-07 18:07:23 -08001252 for (auto& sector : sectors_) {
Wyatt Hepler2c7eca02020-02-18 16:01:42 -08001253 DBG(" - Sector %u: valid %zu, recoverable %zu, free %zu",
Wyatt Heplerc84393f2020-03-20 11:23:24 -07001254 sectors_.Index(sector),
Wyatt Hepler2c7eca02020-02-18 16:01:42 -08001255 sector.valid_bytes(),
1256 sector.RecoverableBytes(partition_.sector_size_bytes()),
1257 sector.writable_bytes());
David Rogers50185ad2020-02-07 00:02:46 -08001258 }
1259}
1260
David Rogerscf680ab2020-02-12 23:28:32 -08001261void KeyValueStore::LogKeyDescriptor() const {
Wyatt Hepler7ded6da2020-03-11 18:24:43 -07001262 DBG("Key descriptors: count %zu", entry_cache_.total_entries());
David Rogers9abe3c72020-03-24 19:03:13 -07001263 for (const EntryMetadata& metadata : entry_cache_) {
Wyatt Hepler7ded6da2020-03-11 18:24:43 -07001264 DBG(" - Key: %s, hash %#zx, transaction ID %zu, first address %#zx",
Wyatt Hepler02946272020-03-18 10:36:22 -07001265 metadata.state() == EntryState::kDeleted ? "Deleted" : "Valid",
Wyatt Hepler7ded6da2020-03-11 18:24:43 -07001266 static_cast<size_t>(metadata.hash()),
1267 static_cast<size_t>(metadata.transaction_id()),
1268 static_cast<size_t>(metadata.first_address()));
David Rogerscf680ab2020-02-12 23:28:32 -08001269 }
1270}
1271
Wyatt Hepler2ad60672020-01-21 08:00:16 -08001272} // namespace pw::kvs