blob: 1f3737ecd785cddaaae23ac5d270ed1ad9d7bbd8 [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) {
Armando Montanezf8419ae2020-04-21 10:03:05 -070087 size_t pre_fix_redundancy_errors =
88 error_stats_.missing_redundant_entries_recovered;
David Rogersfcea3252020-04-07 14:56:35 -070089 Status recovery_status = FixErrors();
90
91 if (recovery_status.ok()) {
David Rogerscd134352020-04-17 19:37:15 -070092 if (metadata_result == Status::OUT_OF_RANGE) {
Armando Montanezf8419ae2020-04-21 10:03:05 -070093 error_stats_.missing_redundant_entries_recovered =
94 pre_fix_redundancy_errors;
David Rogerscd134352020-04-17 19:37:15 -070095 INF("KVS init: Redundancy level successfully updated");
96 } else {
97 WRN("KVS init: Corruption detected and fully repaired");
98 }
David Rogersfcea3252020-04-07 14:56:35 -070099 initialized_ = InitializationState::kReady;
100 } else if (recovery_status == Status::RESOURCE_EXHAUSTED) {
101 WRN("KVS init: Unable to maintain required free sector");
102 initialized_ = InitializationState::kNeedsMaintenance;
103 } else {
104 WRN("KVS init: Corruption detected and unable repair");
105 initialized_ = InitializationState::kNeedsMaintenance;
106 }
107 } else {
108 WRN("KVS init: Corruption detected, no repair attempted due to options");
109 initialized_ = InitializationState::kNeedsMaintenance;
110 }
111 }
112
113 INF("KeyValueStore init complete: active keys %zu, deleted keys %zu, sectors "
114 "%zu, logical sector size %zu bytes",
115 size(),
116 (entry_cache_.total_entries() - size()),
117 sectors_.size(),
118 partition_.sector_size_bytes());
119
120 // Report any corruption was not repaired.
121 if (error_detected_) {
122 WRN("KVS init: Corruption found but not repaired, KVS unavailable until "
123 "successful maintenance.");
124 return Status::DATA_LOSS;
125 }
126
127 return Status::OK;
128}
129
David Rogerscd134352020-04-17 19:37:15 -0700130Status KeyValueStore::InitializeMetadata() {
David Rogersfcea3252020-04-07 14:56:35 -0700131 const size_t sector_size_bytes = partition_.sector_size_bytes();
132
133 sectors_.Reset();
134 entry_cache_.Reset();
135
Keir Mierle8c352dc2020-02-02 13:58:19 -0800136 DBG("First pass: Read all entries from all sectors");
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800137 Address sector_address = 0;
Keir Mierle8c352dc2020-02-02 13:58:19 -0800138
Alexei Frolovd4adf912020-02-21 13:29:15 -0800139 size_t total_corrupt_bytes = 0;
David Rogerscd134352020-04-17 19:37:15 -0700140 size_t corrupt_entries = 0;
David Rogers91627482020-02-27 17:38:12 -0800141 bool empty_sector_found = false;
David Rogerscd134352020-04-17 19:37:15 -0700142 size_t entry_copies_missing = 0;
Alexei Frolovd4adf912020-02-21 13:29:15 -0800143
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800144 for (SectorDescriptor& sector : sectors_) {
Keir Mierle8c352dc2020-02-02 13:58:19 -0800145 Address entry_address = sector_address;
146
Alexei Frolovd4adf912020-02-21 13:29:15 -0800147 size_t sector_corrupt_bytes = 0;
148
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800149 for (int num_entries_in_sector = 0; true; num_entries_in_sector++) {
David Rogersfcea3252020-04-07 14:56:35 -0700150 DBG("Load entry: sector=%u, entry#=%d, address=%u",
151 unsigned(sector_address),
Keir Mierle8c352dc2020-02-02 13:58:19 -0800152 num_entries_in_sector,
David Rogersfcea3252020-04-07 14:56:35 -0700153 unsigned(entry_address));
Keir Mierle8c352dc2020-02-02 13:58:19 -0800154
Wyatt Heplerc84393f2020-03-20 11:23:24 -0700155 if (!sectors_.AddressInSector(sector, entry_address)) {
Keir Mierle8c352dc2020-02-02 13:58:19 -0800156 DBG("Fell off end of sector; moving to the next sector");
157 break;
158 }
159
160 Address next_entry_address;
161 Status status = LoadEntry(entry_address, &next_entry_address);
162 if (status == Status::NOT_FOUND) {
163 DBG("Hit un-written data in sector; moving to the next sector");
164 break;
David Rogersfcea3252020-04-07 14:56:35 -0700165 } else if (!status.ok()) {
166 // The entry could not be read, indicating likely data corruption within
167 // the sector. Try to scan the remainder of the sector for other
168 // entries.
Alexei Frolovd4adf912020-02-21 13:29:15 -0800169
David Rogers49766d92020-03-20 10:55:54 -0700170 error_detected_ = true;
Alexei Frolovd4adf912020-02-21 13:29:15 -0800171 corrupt_entries++;
172
173 status = ScanForEntry(sector,
174 entry_address + Entry::kMinAlignmentBytes,
175 &next_entry_address);
David Rogersfcea3252020-04-07 14:56:35 -0700176 if (!status.ok()) {
Alexei Frolovd4adf912020-02-21 13:29:15 -0800177 // No further entries in this sector. Mark the remaining bytes in the
178 // sector as corrupt (since we can't reliably know the size of the
179 // corrupt entry).
180 sector_corrupt_bytes +=
181 sector_size_bytes - (entry_address - sector_address);
182 break;
183 }
184
Alexei Frolovd4adf912020-02-21 13:29:15 -0800185 sector_corrupt_bytes += next_entry_address - entry_address;
Keir Mierle8c352dc2020-02-02 13:58:19 -0800186 }
Keir Mierle8c352dc2020-02-02 13:58:19 -0800187
188 // Entry loaded successfully; so get ready to load the next one.
189 entry_address = next_entry_address;
190
191 // Update of the number of writable bytes in this sector.
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800192 sector.set_writable_bytes(sector_size_bytes -
193 (entry_address - sector_address));
Keir Mierle8c352dc2020-02-02 13:58:19 -0800194 }
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800195
Alexei Frolovd4adf912020-02-21 13:29:15 -0800196 if (sector_corrupt_bytes > 0) {
197 // If the sector contains corrupt data, prevent any further entries from
198 // being written to it by indicating that it has no space. This should
199 // also make it a decent GC candidate. Valid keys in the sector are still
200 // readable as normal.
David Rogers49766d92020-03-20 10:55:54 -0700201 sector.mark_corrupt();
202 error_detected_ = true;
Alexei Frolovd4adf912020-02-21 13:29:15 -0800203
204 WRN("Sector %u contains %zuB of corrupt data",
Wyatt Heplerc84393f2020-03-20 11:23:24 -0700205 sectors_.Index(sector),
Alexei Frolovd4adf912020-02-21 13:29:15 -0800206 sector_corrupt_bytes);
207 }
208
David Rogers91627482020-02-27 17:38:12 -0800209 if (sector.Empty(sector_size_bytes)) {
210 empty_sector_found = true;
211 }
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800212 sector_address += sector_size_bytes;
Alexei Frolovd4adf912020-02-21 13:29:15 -0800213 total_corrupt_bytes += sector_corrupt_bytes;
Keir Mierle8c352dc2020-02-02 13:58:19 -0800214 }
215
216 DBG("Second pass: Count valid bytes in each sector");
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700217 Address newest_key = 0;
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800218
David Rogers98fea472020-04-01 15:43:48 -0700219 // For every valid entry, for each address, count the valid bytes in that
220 // sector. If the address fails to read, remove the address and mark the
221 // sector as corrupt. Track which entry has the newest transaction ID for
222 // initializing last_new_sector_.
223 for (EntryMetadata& metadata : entry_cache_) {
David Rogers49766d92020-03-20 10:55:54 -0700224 if (metadata.addresses().size() < redundancy()) {
David Rogers31b358b2020-04-15 05:00:50 -0700225 DBG("Key 0x%08x missing copies, has %u, needs %u",
226 unsigned(metadata.hash()),
227 unsigned(metadata.addresses().size()),
228 unsigned(redundancy()));
David Rogerscd134352020-04-17 19:37:15 -0700229 entry_copies_missing++;
David Rogers49766d92020-03-20 10:55:54 -0700230 }
David Rogers98fea472020-04-01 15:43:48 -0700231 size_t index = 0;
232 while (index < metadata.addresses().size()) {
233 Address address = metadata.addresses()[index];
David Rogersf56131c2020-03-04 10:19:22 -0800234 Entry entry;
David Rogers98fea472020-04-01 15:43:48 -0700235
236 Status read_result = Entry::Read(partition_, address, formats_, &entry);
237
238 SectorDescriptor& sector = sectors_.FromAddress(address);
239
240 if (read_result.ok()) {
241 sector.AddValidBytes(entry.size());
242 index++;
243 } else {
244 corrupt_entries++;
245 total_corrupt_bytes += sector.writable_bytes();
246 error_detected_ = true;
247 sector.mark_corrupt();
248
249 // Remove the bad address and stay at this index. The removal
250 // replaces out the removed address with the back address so
251 // this index needs to be rechecked with the new address.
252 metadata.RemoveAddress(address);
253 }
David Rogersf56131c2020-03-04 10:19:22 -0800254 }
David Rogers98fea472020-04-01 15:43:48 -0700255
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700256 if (metadata.IsNewerThan(last_transaction_id_)) {
257 last_transaction_id_ = metadata.transaction_id();
258 newest_key = metadata.addresses().back();
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800259 }
Keir Mierle8c352dc2020-02-02 13:58:19 -0800260 }
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800261
Wyatt Heplerc84393f2020-03-20 11:23:24 -0700262 sectors_.set_last_new_sector(newest_key);
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800263
David Rogers91627482020-02-27 17:38:12 -0800264 if (!empty_sector_found) {
David Rogers31b358b2020-04-15 05:00:50 -0700265 DBG("No empty sector found");
David Rogers9abe3c72020-03-24 19:03:13 -0700266 error_detected_ = true;
David Rogers91627482020-02-27 17:38:12 -0800267 }
268
David Rogerscd134352020-04-17 19:37:15 -0700269 if (entry_copies_missing > 0) {
270 bool other_errors = error_detected_;
271 error_detected_ = true;
272
273 if (!other_errors && entry_copies_missing == size()) {
274 INF("KVS configuration changed to redundancy of %zu total copies per key",
275 redundancy());
276 return Status::OUT_OF_RANGE;
277 }
David Rogers9abe3c72020-03-24 19:03:13 -0700278 }
David Rogerscd134352020-04-17 19:37:15 -0700279
280 if (error_detected_) {
281 WRN("Corruption detected. Found %zu corrupt bytes, %zu corrupt entries, "
282 "and %zu keys missing redundant copies.",
283 total_corrupt_bytes,
284 corrupt_entries,
285 entry_copies_missing);
286 return Status::FAILED_PRECONDITION;
287 }
288 return Status::OK;
Keir Mierle8c352dc2020-02-02 13:58:19 -0800289}
290
Alexei Frolov9e235832020-02-24 12:44:45 -0800291KeyValueStore::StorageStats KeyValueStore::GetStorageStats() const {
David Rogers9abe3c72020-03-24 19:03:13 -0700292 StorageStats stats{};
Alexei Frolov9e235832020-02-24 12:44:45 -0800293 const size_t sector_size = partition_.sector_size_bytes();
294 bool found_empty_sector = false;
David Rogers9abe3c72020-03-24 19:03:13 -0700295 stats.corrupt_sectors_recovered = error_stats_.corrupt_sectors_recovered;
296 stats.missing_redundant_entries_recovered =
297 error_stats_.missing_redundant_entries_recovered;
Alexei Frolov9e235832020-02-24 12:44:45 -0800298
299 for (const SectorDescriptor& sector : sectors_) {
300 stats.in_use_bytes += sector.valid_bytes();
301 stats.reclaimable_bytes += sector.RecoverableBytes(sector_size);
302
303 if (!found_empty_sector && sector.Empty(sector_size)) {
304 // The KVS tries to always keep an empty sector for GC, so don't count
305 // the first empty sector seen as writable space. However, a free sector
306 // cannot always be assumed to exist; if a GC operation fails, all sectors
307 // may be partially written, in which case the space reported might be
308 // inaccurate.
309 found_empty_sector = true;
310 continue;
311 }
312
313 stats.writable_bytes += sector.writable_bytes();
314 }
315
316 return stats;
317}
318
David Rogers98fea472020-04-01 15:43:48 -0700319// Check KVS for any error conditions. Primarily intended for test and
320// internal use.
David Rogers9abe3c72020-03-24 19:03:13 -0700321bool KeyValueStore::CheckForErrors() {
322 // Check for corrupted sectors
323 for (SectorDescriptor& sector : sectors_) {
324 if (sector.corrupt()) {
325 error_detected_ = true;
David Rogers98fea472020-04-01 15:43:48 -0700326 return error_detected();
David Rogers9abe3c72020-03-24 19:03:13 -0700327 }
328 }
329
330 // Check for missing redundancy.
331 if (redundancy() > 1) {
332 for (const EntryMetadata& metadata : entry_cache_) {
333 if (metadata.addresses().size() < redundancy()) {
334 error_detected_ = true;
David Rogers98fea472020-04-01 15:43:48 -0700335 return error_detected();
David Rogers9abe3c72020-03-24 19:03:13 -0700336 }
337 }
338 }
339
340 return error_detected();
341}
342
Keir Mierle8c352dc2020-02-02 13:58:19 -0800343Status KeyValueStore::LoadEntry(Address entry_address,
344 Address* next_entry_address) {
Wyatt Heplere541e072020-02-14 09:10:53 -0800345 Entry entry;
Wyatt Hepler22d0d9f2020-03-05 14:57:11 -0800346 TRY(Entry::Read(partition_, entry_address, formats_, &entry));
Keir Mierle8c352dc2020-02-02 13:58:19 -0800347
348 // Read the key from flash & validate the entry (which reads the value).
Wyatt Heplera00d1ef2020-02-14 14:31:26 -0800349 Entry::KeyBuffer key_buffer;
Wyatt Heplere541e072020-02-14 09:10:53 -0800350 TRY_ASSIGN(size_t key_length, entry.ReadKey(key_buffer));
351 const string_view key(key_buffer.data(), key_length);
Wyatt Heplerbab0e202020-02-04 07:40:08 -0800352
Wyatt Hepler22d0d9f2020-03-05 14:57:11 -0800353 TRY(entry.VerifyChecksumInFlash());
David Rogersf56131c2020-03-04 10:19:22 -0800354
355 // A valid entry was found, so update the next entry address before doing any
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700356 // of the checks that happen in AddNewOrUpdateExisting.
David Rogersf56131c2020-03-04 10:19:22 -0800357 *next_entry_address = entry.next_address();
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700358 return entry_cache_.AddNewOrUpdateExisting(
359 entry.descriptor(key), entry.address(), partition_.sector_size_bytes());
Keir Mierle8c352dc2020-02-02 13:58:19 -0800360}
361
Alexei Frolovd4adf912020-02-21 13:29:15 -0800362// Scans flash memory within a sector to find a KVS entry magic.
Alexei Frolovd4adf912020-02-21 13:29:15 -0800363Status KeyValueStore::ScanForEntry(const SectorDescriptor& sector,
364 Address start_address,
365 Address* next_entry_address) {
David Rogersfcea3252020-04-07 14:56:35 -0700366 DBG("Scanning sector %u for entries starting from address %u",
Wyatt Heplerc84393f2020-03-20 11:23:24 -0700367 sectors_.Index(sector),
David Rogersfcea3252020-04-07 14:56:35 -0700368 unsigned(start_address));
Alexei Frolovd4adf912020-02-21 13:29:15 -0800369
370 // Entries must start at addresses which are aligned on a multiple of
371 // Entry::kMinAlignmentBytes. However, that multiple can vary between entries.
372 // When scanning, we don't have an entry to tell us what the current alignment
373 // is, so the minimum alignment is used to be exhaustive.
374 for (Address address = AlignUp(start_address, Entry::kMinAlignmentBytes);
Wyatt Heplerc84393f2020-03-20 11:23:24 -0700375 sectors_.AddressInSector(sector, address);
Alexei Frolovd4adf912020-02-21 13:29:15 -0800376 address += Entry::kMinAlignmentBytes) {
Alexei Frolovd4adf912020-02-21 13:29:15 -0800377 uint32_t magic;
David Rogersfcea3252020-04-07 14:56:35 -0700378 StatusWithSize read_result =
379 partition_.Read(address, as_writable_bytes(span(&magic, 1)));
380 if (!read_result.ok()) {
381 continue;
382 }
Wyatt Hepler22d0d9f2020-03-05 14:57:11 -0800383 if (formats_.KnownMagic(magic)) {
David Rogersfcea3252020-04-07 14:56:35 -0700384 DBG("Found entry magic at address %u", unsigned(address));
Alexei Frolovd4adf912020-02-21 13:29:15 -0800385 *next_entry_address = address;
386 return Status::OK;
387 }
388 }
389
390 return Status::NOT_FOUND;
391}
392
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800393StatusWithSize KeyValueStore::Get(string_view key,
Wyatt Hepler5f6efc02020-02-18 16:54:31 -0800394 span<byte> value_buffer,
395 size_t offset_bytes) const {
David Rogers9abe3c72020-03-24 19:03:13 -0700396 TRY_WITH_SIZE(CheckReadOperation(key));
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800397
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700398 EntryMetadata metadata;
David Rogers98fea472020-04-01 15:43:48 -0700399 TRY_WITH_SIZE(FindExisting(key, &metadata));
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800400
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700401 return Get(key, metadata, value_buffer, offset_bytes);
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800402}
403
Wyatt Heplerfac81132020-02-27 17:26:33 -0800404Status KeyValueStore::PutBytes(string_view key, span<const byte> value) {
David Rogers9abe3c72020-03-24 19:03:13 -0700405 TRY(CheckWriteOperation(key));
Keir Mierle8c352dc2020-02-02 13:58:19 -0800406 DBG("Writing key/value; key length=%zu, value length=%zu",
407 key.size(),
408 value.size());
Wyatt Hepler729f28c2020-02-05 09:46:00 -0800409
Wyatt Hepler5406a672020-02-18 15:42:38 -0800410 if (Entry::size(partition_, key, value) > partition_.sector_size_bytes()) {
411 DBG("%zu B value with %zu B key cannot fit in one sector",
412 value.size(),
413 key.size());
414 return Status::INVALID_ARGUMENT;
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800415 }
416
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700417 EntryMetadata metadata;
David Rogers98fea472020-04-01 15:43:48 -0700418 Status status = FindEntry(key, &metadata);
Wyatt Hepler2d401692020-02-13 16:01:23 -0800419
420 if (status.ok()) {
David Rogersf56131c2020-03-04 10:19:22 -0800421 // TODO: figure out logging how to support multiple addresses.
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700422 DBG("Overwriting entry for key 0x%08" PRIx32 " in %zu sectors including %u",
423 metadata.hash(),
424 metadata.addresses().size(),
Wyatt Heplerc84393f2020-03-20 11:23:24 -0700425 sectors_.Index(metadata.first_address()));
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700426 return WriteEntryForExistingKey(metadata, EntryState::kValid, key, value);
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800427 }
David Rogers2761aeb2020-01-31 17:09:00 -0800428
Wyatt Hepler2d401692020-02-13 16:01:23 -0800429 if (status == Status::NOT_FOUND) {
430 return WriteEntryForNewKey(key, value);
431 }
432
433 return status;
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800434}
435
436Status KeyValueStore::Delete(string_view key) {
David Rogers9abe3c72020-03-24 19:03:13 -0700437 TRY(CheckWriteOperation(key));
Wyatt Hepler729f28c2020-02-05 09:46:00 -0800438
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700439 EntryMetadata metadata;
David Rogers98fea472020-04-01 15:43:48 -0700440 TRY(FindExisting(key, &metadata));
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800441
David Rogersf56131c2020-03-04 10:19:22 -0800442 // TODO: figure out logging how to support multiple addresses.
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700443 DBG("Writing tombstone for key 0x%08" PRIx32 " in %zu sectors including %u",
444 metadata.hash(),
445 metadata.addresses().size(),
Wyatt Heplerc84393f2020-03-20 11:23:24 -0700446 sectors_.Index(metadata.first_address()));
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700447 return WriteEntryForExistingKey(metadata, EntryState::kDeleted, key, {});
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800448}
449
Wyatt Hepler08d37d82020-02-27 15:45:37 -0800450void KeyValueStore::Item::ReadKey() {
451 key_buffer_.fill('\0');
452
453 Entry entry;
David Rogers98fea472020-04-01 15:43:48 -0700454 if (kvs_.ReadEntry(*iterator_, entry).ok()) {
Wyatt Hepler08d37d82020-02-27 15:45:37 -0800455 entry.ReadKey(key_buffer_);
456 }
457}
458
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800459KeyValueStore::iterator& KeyValueStore::iterator::operator++() {
460 // Skip to the next entry that is valid (not deleted).
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700461 while (++item_.iterator_ != item_.kvs_.entry_cache_.end() &&
Wyatt Hepler02946272020-03-18 10:36:22 -0700462 item_.iterator_->state() != EntryState::kValid) {
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800463 }
464 return *this;
465}
466
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800467KeyValueStore::iterator KeyValueStore::begin() const {
Wyatt Heplerbfc6a522020-04-01 16:30:24 -0700468 internal::EntryCache::const_iterator cache_iterator = entry_cache_.begin();
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800469 // Skip over any deleted entries at the start of the descriptor list.
Wyatt Hepler02946272020-03-18 10:36:22 -0700470 while (cache_iterator != entry_cache_.end() &&
471 cache_iterator->state() != EntryState::kValid) {
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700472 ++cache_iterator;
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800473 }
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700474 return iterator(*this, cache_iterator);
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800475}
476
Wyatt Heplerab3b2492020-03-11 16:15:16 -0700477StatusWithSize KeyValueStore::ValueSize(string_view key) const {
David Rogers9abe3c72020-03-24 19:03:13 -0700478 TRY_WITH_SIZE(CheckReadOperation(key));
Wyatt Heplered163b02020-02-03 17:49:32 -0800479
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700480 EntryMetadata metadata;
David Rogers98fea472020-04-01 15:43:48 -0700481 TRY_WITH_SIZE(FindExisting(key, &metadata));
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800482
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700483 return ValueSize(metadata);
Wyatt Heplerfac81132020-02-27 17:26:33 -0800484}
Wyatt Heplered163b02020-02-03 17:49:32 -0800485
David Rogers98fea472020-04-01 15:43:48 -0700486Status KeyValueStore::ReadEntry(const EntryMetadata& metadata,
487 Entry& entry) const {
488 // Try to read an entry
489 Status read_result = Status::DATA_LOSS;
490 for (Address address : metadata.addresses()) {
491 read_result = Entry::Read(partition_, address, formats_, &entry);
492 if (read_result.ok()) {
493 return read_result;
494 }
495
496 // Found a bad address. Set the sector as corrupt.
497 error_detected_ = true;
498 sectors_.FromAddress(address).mark_corrupt();
499 }
500
501 ERR("No valid entries for key. Data has been lost!");
502 return read_result;
503}
504
505Status KeyValueStore::FindEntry(string_view key,
506 EntryMetadata* found_entry) const {
507 StatusWithSize find_result =
508 entry_cache_.Find(partition_, sectors_, formats_, key, found_entry);
509
510 if (find_result.size() > 0u) {
511 error_detected_ = true;
512 }
513 return find_result.status();
514}
515
516Status KeyValueStore::FindExisting(string_view key,
517 EntryMetadata* metadata) const {
518 Status status = FindEntry(key, metadata);
519
520 // If the key's hash collides with an existing key or if the key is deleted,
521 // treat it as if it is not in the KVS.
522 if (status == Status::ALREADY_EXISTS ||
523 (status.ok() && metadata->state() == EntryState::kDeleted)) {
524 return Status::NOT_FOUND;
525 }
526 return status;
527}
528
Wyatt Heplerfac81132020-02-27 17:26:33 -0800529StatusWithSize KeyValueStore::Get(string_view key,
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700530 const EntryMetadata& metadata,
Wyatt Heplerfac81132020-02-27 17:26:33 -0800531 span<std::byte> value_buffer,
532 size_t offset_bytes) const {
533 Entry entry;
David Rogers98fea472020-04-01 15:43:48 -0700534
535 TRY_WITH_SIZE(ReadEntry(metadata, entry));
Wyatt Heplerfac81132020-02-27 17:26:33 -0800536
537 StatusWithSize result = entry.ReadValue(value_buffer, offset_bytes);
538 if (result.ok() && options_.verify_on_read && offset_bytes == 0u) {
Wyatt Hepler22d0d9f2020-03-05 14:57:11 -0800539 Status verify_result =
540 entry.VerifyChecksum(key, value_buffer.first(result.size()));
Wyatt Heplerfac81132020-02-27 17:26:33 -0800541 if (!verify_result.ok()) {
542 std::memset(value_buffer.data(), 0, result.size());
543 return StatusWithSize(verify_result, 0);
544 }
545
546 return StatusWithSize(verify_result, result.size());
547 }
548 return result;
Wyatt Heplered163b02020-02-03 17:49:32 -0800549}
550
Wyatt Hepler6e3a83b2020-02-04 07:36:45 -0800551Status KeyValueStore::FixedSizeGet(std::string_view key,
Wyatt Heplerfac81132020-02-27 17:26:33 -0800552 void* value,
553 size_t size_bytes) const {
David Rogers9abe3c72020-03-24 19:03:13 -0700554 TRY(CheckWriteOperation(key));
Wyatt Heplerfac81132020-02-27 17:26:33 -0800555
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700556 EntryMetadata metadata;
David Rogers98fea472020-04-01 15:43:48 -0700557 TRY(FindExisting(key, &metadata));
Wyatt Heplerfac81132020-02-27 17:26:33 -0800558
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700559 return FixedSizeGet(key, metadata, value, size_bytes);
Wyatt Heplerfac81132020-02-27 17:26:33 -0800560}
561
562Status KeyValueStore::FixedSizeGet(std::string_view key,
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700563 const EntryMetadata& metadata,
Wyatt Heplerfac81132020-02-27 17:26:33 -0800564 void* value,
Wyatt Hepler6e3a83b2020-02-04 07:36:45 -0800565 size_t size_bytes) const {
566 // Ensure that the size of the stored value matches the size of the type.
567 // Otherwise, report error. This check avoids potential memory corruption.
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700568 TRY_ASSIGN(const size_t actual_size, ValueSize(metadata));
Wyatt Heplerfac81132020-02-27 17:26:33 -0800569
570 if (actual_size != size_bytes) {
571 DBG("Requested %zu B read, but value is %zu B", size_bytes, actual_size);
Wyatt Hepler6e3a83b2020-02-04 07:36:45 -0800572 return Status::INVALID_ARGUMENT;
Wyatt Heplerbab0e202020-02-04 07:40:08 -0800573 }
Wyatt Heplerfac81132020-02-27 17:26:33 -0800574
575 StatusWithSize result =
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700576 Get(key, metadata, span(static_cast<byte*>(value), size_bytes), 0);
Wyatt Heplerfac81132020-02-27 17:26:33 -0800577
578 return result.status();
579}
580
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700581StatusWithSize KeyValueStore::ValueSize(const EntryMetadata& metadata) const {
Wyatt Heplerfac81132020-02-27 17:26:33 -0800582 Entry entry;
David Rogers98fea472020-04-01 15:43:48 -0700583 TRY_WITH_SIZE(ReadEntry(metadata, entry));
Wyatt Heplerfac81132020-02-27 17:26:33 -0800584
585 return StatusWithSize(entry.value_size());
Keir Mierle8c352dc2020-02-02 13:58:19 -0800586}
587
David Rogers9abe3c72020-03-24 19:03:13 -0700588Status KeyValueStore::CheckWriteOperation(string_view key) const {
Wyatt Hepleracaacf92020-01-24 10:58:30 -0800589 if (InvalidKey(key)) {
Wyatt Heplerb7609542020-01-24 10:29:54 -0800590 return Status::INVALID_ARGUMENT;
591 }
David Rogers9abe3c72020-03-24 19:03:13 -0700592
593 // For normal write operation the KVS must be fully ready.
Wyatt Heplerd2298282020-02-20 17:12:45 -0800594 if (!initialized()) {
Wyatt Heplerb7609542020-01-24 10:29:54 -0800595 return Status::FAILED_PRECONDITION;
596 }
Wyatt Heplerb7609542020-01-24 10:29:54 -0800597 return Status::OK;
598}
599
David Rogers9abe3c72020-03-24 19:03:13 -0700600Status KeyValueStore::CheckReadOperation(string_view key) const {
601 if (InvalidKey(key)) {
602 return Status::INVALID_ARGUMENT;
603 }
604
605 // Operations that are explicitly read-only can be done after init() has been
606 // called but not fully ready (when needing maintenance).
607 if (initialized_ == InitializationState::kNotInitialized) {
608 return Status::FAILED_PRECONDITION;
609 }
610 return Status::OK;
611}
612
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700613Status KeyValueStore::WriteEntryForExistingKey(EntryMetadata& metadata,
614 EntryState new_state,
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800615 string_view key,
616 span<const byte> value) {
Wyatt Heplerab3b2492020-03-11 16:15:16 -0700617 // Read the original entry to get the size for sector accounting purposes.
618 Entry entry;
David Rogers98fea472020-04-01 15:43:48 -0700619 TRY(ReadEntry(metadata, entry));
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800620
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700621 return WriteEntry(key, value, new_state, &metadata, entry.size());
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800622}
623
624Status KeyValueStore::WriteEntryForNewKey(string_view key,
625 span<const byte> value) {
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700626 if (entry_cache_.full()) {
Keir Mierle8c352dc2020-02-02 13:58:19 -0800627 WRN("KVS full: trying to store a new entry, but can't. Have %zu entries",
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700628 entry_cache_.total_entries());
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800629 return Status::RESOURCE_EXHAUSTED;
630 }
631
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700632 return WriteEntry(key, value, EntryState::kValid);
Wyatt Heplerab3b2492020-03-11 16:15:16 -0700633}
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800634
Wyatt Heplerab3b2492020-03-11 16:15:16 -0700635Status KeyValueStore::WriteEntry(string_view key,
636 span<const byte> value,
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700637 EntryState new_state,
638 EntryMetadata* prior_metadata,
Wyatt Heplerab3b2492020-03-11 16:15:16 -0700639 size_t prior_size) {
640 const size_t entry_size = Entry::size(partition_, key, value);
641
642 // List of addresses for sectors with space for this entry.
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700643 Address* reserved_addresses = entry_cache_.TempReservedAddressesForWrite();
Wyatt Heplerab3b2492020-03-11 16:15:16 -0700644
David Rogers31b358b2020-04-15 05:00:50 -0700645 // Find addresses to write the entry to. This may involve garbage collecting
646 // one or more sectors.
647 TRY(GetAddressesForWrite(reserved_addresses, entry_size));
Wyatt Heplerab3b2492020-03-11 16:15:16 -0700648
649 // Write the entry at the first address that was found.
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700650 Entry entry = CreateEntry(reserved_addresses[0], key, value, new_state);
Wyatt Heplerab3b2492020-03-11 16:15:16 -0700651 TRY(AppendEntry(entry, key, value));
652
653 // After writing the first entry successfully, update the key descriptors.
654 // Once a single new the entry is written, the old entries are invalidated.
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700655 EntryMetadata new_metadata =
David Rogers31b358b2020-04-15 05:00:50 -0700656 CreateOrUpdateKeyDescriptor(entry, key, prior_metadata, prior_size);
Wyatt Heplerab3b2492020-03-11 16:15:16 -0700657
658 // Write the additional copies of the entry, if redundancy is greater than 1.
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700659 for (size_t i = 1; i < redundancy(); ++i) {
660 entry.set_address(reserved_addresses[i]);
Wyatt Heplerab3b2492020-03-11 16:15:16 -0700661 TRY(AppendEntry(entry, key, value));
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700662 new_metadata.AddNewAddress(reserved_addresses[i]);
Wyatt Heplerab3b2492020-03-11 16:15:16 -0700663 }
Wyatt Heplerb7609542020-01-24 10:29:54 -0800664 return Status::OK;
665}
666
David Rogers31b358b2020-04-15 05:00:50 -0700667KeyValueStore::EntryMetadata KeyValueStore::CreateOrUpdateKeyDescriptor(
Wyatt Heplerab3b2492020-03-11 16:15:16 -0700668 const Entry& entry,
669 string_view key,
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700670 EntryMetadata* prior_metadata,
Wyatt Heplerab3b2492020-03-11 16:15:16 -0700671 size_t prior_size) {
672 // If there is no prior descriptor, create a new one.
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700673 if (prior_metadata == nullptr) {
674 return entry_cache_.AddNew(entry.descriptor(key), entry.address());
David Rogersa2562b52020-03-05 15:30:05 -0800675 }
676
David Rogers31b358b2020-04-15 05:00:50 -0700677 return UpdateKeyDescriptor(
678 entry, entry.address(), prior_metadata, prior_size);
679}
680
681KeyValueStore::EntryMetadata KeyValueStore::UpdateKeyDescriptor(
682 const Entry& entry,
683 Address new_address,
684 EntryMetadata* prior_metadata,
685 size_t prior_size) {
Wyatt Heplerab3b2492020-03-11 16:15:16 -0700686 // Remove valid bytes for the old entry and its copies, which are now stale.
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700687 for (Address address : prior_metadata->addresses()) {
Wyatt Heplerc84393f2020-03-20 11:23:24 -0700688 sectors_.FromAddress(address).RemoveValidBytes(prior_size);
David Rogersa2562b52020-03-05 15:30:05 -0800689 }
690
David Rogers31b358b2020-04-15 05:00:50 -0700691 prior_metadata->Reset(entry.descriptor(prior_metadata->hash()), new_address);
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700692 return *prior_metadata;
David Rogersa2562b52020-03-05 15:30:05 -0800693}
694
David Rogers31b358b2020-04-15 05:00:50 -0700695Status KeyValueStore::GetAddressesForWrite(Address* write_addresses,
696 size_t write_size) {
697 for (size_t i = 0; i < redundancy(); i++) {
698 SectorDescriptor* sector;
699 TRY(GetSectorForWrite(&sector, write_size, span(write_addresses, i)));
700 write_addresses[i] = sectors_.NextWritableAddress(*sector);
701
702 DBG("Found space for entry in sector %u at address %u",
703 sectors_.Index(sector),
704 unsigned(write_addresses[i]));
705 }
706
707 return Status::OK;
708}
709
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700710// Finds a sector to use for writing a new entry to. Does automatic garbage
David Rogersa2562b52020-03-05 15:30:05 -0800711// collection if needed and allowed.
712//
713// OK: Sector found with needed space.
714// RESOURCE_EXHAUSTED: No sector available with the needed space.
715Status KeyValueStore::GetSectorForWrite(SectorDescriptor** sector,
716 size_t entry_size,
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700717 span<const Address> reserved) {
Wyatt Heplerc84393f2020-03-20 11:23:24 -0700718 Status result = sectors_.FindSpace(sector, entry_size, reserved);
David Rogersa2562b52020-03-05 15:30:05 -0800719
David Rogersf3884eb2020-03-08 19:21:40 -0700720 size_t gc_sector_count = 0;
David Rogersa2562b52020-03-05 15:30:05 -0800721 bool do_auto_gc = options_.gc_on_write != GargbageCollectOnWrite::kDisabled;
722
723 // Do garbage collection as needed, so long as policy allows.
724 while (result == Status::RESOURCE_EXHAUSTED && do_auto_gc) {
725 if (options_.gc_on_write == GargbageCollectOnWrite::kOneSector) {
726 // If GC config option is kOneSector clear the flag to not do any more
727 // GC after this try.
728 do_auto_gc = false;
729 }
730 // Garbage collect and then try again to find the best sector.
David Rogers9abe3c72020-03-24 19:03:13 -0700731 Status gc_status = GarbageCollect(reserved);
David Rogersa2562b52020-03-05 15:30:05 -0800732 if (!gc_status.ok()) {
733 if (gc_status == Status::NOT_FOUND) {
734 // Not enough space, and no reclaimable bytes, this KVS is full!
735 return Status::RESOURCE_EXHAUSTED;
736 }
737 return gc_status;
738 }
739
Wyatt Heplerc84393f2020-03-20 11:23:24 -0700740 result = sectors_.FindSpace(sector, entry_size, reserved);
David Rogersf3884eb2020-03-08 19:21:40 -0700741
742 gc_sector_count++;
743 // Allow total sectors + 2 number of GC cycles so that once reclaimable
744 // bytes in all the sectors have been reclaimed can try and free up space by
745 // moving entries for keys other than the one being worked on in to sectors
746 // that have copies of the key trying to be written.
747 if (gc_sector_count > (partition_.sector_count() + 2)) {
748 ERR("Did more GC sectors than total sectors!!!!");
749 return Status::RESOURCE_EXHAUSTED;
750 }
David Rogersa2562b52020-03-05 15:30:05 -0800751 }
752
753 if (!result.ok()) {
754 WRN("Unable to find sector to write %zu B", entry_size);
755 }
756 return result;
757}
758
David Rogers9abe3c72020-03-24 19:03:13 -0700759Status KeyValueStore::MarkSectorCorruptIfNotOk(Status status,
760 SectorDescriptor* sector) {
761 if (!status.ok()) {
762 DBG(" Sector %u corrupt", sectors_.Index(sector));
763 sector->mark_corrupt();
764 error_detected_ = true;
765 }
766 return status;
767}
768
Wyatt Heplerab3b2492020-03-11 16:15:16 -0700769Status KeyValueStore::AppendEntry(const Entry& entry,
David Rogersa2562b52020-03-05 15:30:05 -0800770 string_view key,
771 span<const byte> value) {
Wyatt Heplerab3b2492020-03-11 16:15:16 -0700772 const StatusWithSize result = entry.Write(key, value);
David Rogersa2562b52020-03-05 15:30:05 -0800773
Wyatt Heplerc84393f2020-03-20 11:23:24 -0700774 SectorDescriptor& sector = sectors_.FromAddress(entry.address());
David Rogersa2562b52020-03-05 15:30:05 -0800775
776 if (!result.ok()) {
777 ERR("Failed to write %zu bytes at %#zx. %zu actually written",
778 entry.size(),
Wyatt Heplerab3b2492020-03-11 16:15:16 -0700779 size_t(entry.address()),
David Rogersa2562b52020-03-05 15:30:05 -0800780 result.size());
David Rogers9abe3c72020-03-24 19:03:13 -0700781 TRY(MarkSectorCorruptIfNotOk(result.status(), &sector));
David Rogersa2562b52020-03-05 15:30:05 -0800782 }
783
784 if (options_.verify_on_write) {
David Rogers9abe3c72020-03-24 19:03:13 -0700785 TRY(MarkSectorCorruptIfNotOk(entry.VerifyChecksumInFlash(), &sector));
David Rogersa2562b52020-03-05 15:30:05 -0800786 }
787
David Rogers98fea472020-04-01 15:43:48 -0700788 sector.RemoveWritableBytes(result.size());
Wyatt Heplerc84393f2020-03-20 11:23:24 -0700789 sector.AddValidBytes(result.size());
David Rogersa2562b52020-03-05 15:30:05 -0800790 return Status::OK;
791}
792
David Rogers98fea472020-04-01 15:43:48 -0700793StatusWithSize KeyValueStore::CopyEntryToSector(Entry& entry,
794 SectorDescriptor* new_sector,
David Rogers31b358b2020-04-15 05:00:50 -0700795 Address new_address) {
David Rogers98fea472020-04-01 15:43:48 -0700796 const StatusWithSize result = entry.Copy(new_address);
797
798 TRY_WITH_SIZE(MarkSectorCorruptIfNotOk(result.status(), new_sector));
799
800 if (options_.verify_on_write) {
David Rogers31b358b2020-04-15 05:00:50 -0700801 Entry new_entry;
802 TRY_WITH_SIZE(MarkSectorCorruptIfNotOk(
803 Entry::Read(partition_, new_address, formats_, &new_entry),
804 new_sector));
805 // TODO: add test that catches doing the verify on the old entry.
806 TRY_WITH_SIZE(MarkSectorCorruptIfNotOk(new_entry.VerifyChecksumInFlash(),
807 new_sector));
David Rogers98fea472020-04-01 15:43:48 -0700808 }
809 // Entry was written successfully; update descriptor's address and the sector
810 // descriptors to reflect the new entry.
811 new_sector->RemoveWritableBytes(result.size());
812 new_sector->AddValidBytes(result.size());
813
814 return result;
815}
816
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700817Status KeyValueStore::RelocateEntry(const EntryMetadata& metadata,
Wyatt Heplerab3b2492020-03-11 16:15:16 -0700818 KeyValueStore::Address& address,
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700819 span<const Address> reserved_addresses) {
David Rogersa2562b52020-03-05 15:30:05 -0800820 Entry entry;
David Rogers98fea472020-04-01 15:43:48 -0700821 TRY(ReadEntry(metadata, entry));
David Rogersa2562b52020-03-05 15:30:05 -0800822
823 // Find a new sector for the entry and write it to the new location. For
824 // relocation the find should not not be a sector already containing the key
825 // but can be the always empty sector, since this is part of the GC process
826 // that will result in a new empty sector. Also find a sector that does not
827 // have reclaimable space (mostly for the full GC, where that would result in
828 // an immediate extra relocation).
829 SectorDescriptor* new_sector;
830
Wyatt Heplerc84393f2020-03-20 11:23:24 -0700831 TRY(sectors_.FindSpaceDuringGarbageCollection(
832 &new_sector, entry.size(), metadata.addresses(), reserved_addresses));
Wyatt Heplerab3b2492020-03-11 16:15:16 -0700833
David Rogers31b358b2020-04-15 05:00:50 -0700834 Address new_address = sectors_.NextWritableAddress(*new_sector);
David Rogers98fea472020-04-01 15:43:48 -0700835 TRY_ASSIGN(const size_t result_size,
836 CopyEntryToSector(entry, new_sector, new_address));
837 sectors_.FromAddress(address).RemoveValidBytes(result_size);
Wyatt Heplerab3b2492020-03-11 16:15:16 -0700838 address = new_address;
David Rogersa2562b52020-03-05 15:30:05 -0800839
840 return Status::OK;
841}
842
David Rogers9abe3c72020-03-24 19:03:13 -0700843Status KeyValueStore::FullMaintenance() {
844 if (initialized_ == InitializationState::kNotInitialized) {
845 return Status::FAILED_PRECONDITION;
846 }
847
848 DBG("Do full maintenance");
David Rogers98fea472020-04-01 15:43:48 -0700849 CheckForErrors();
David Rogers9abe3c72020-03-24 19:03:13 -0700850
851 if (error_detected_) {
852 TRY(Repair());
853 }
Wyatt Heplerc84393f2020-03-20 11:23:24 -0700854
David Rogers31b358b2020-04-15 05:00:50 -0700855 // Make sure all the entries are on the primary format.
856 UpdateEntriesToPrimaryFormat();
857
Wyatt Heplerc84393f2020-03-20 11:23:24 -0700858 SectorDescriptor* sector = sectors_.last_new();
David Rogerscd87c322020-02-27 14:04:08 -0800859
860 // TODO: look in to making an iterator method for cycling through sectors
861 // starting from last_new_sector_.
862 for (size_t j = 0; j < sectors_.size(); j++) {
863 sector += 1;
864 if (sector == sectors_.end()) {
865 sector = sectors_.begin();
866 }
867
868 if (sector->RecoverableBytes(partition_.sector_size_bytes()) > 0) {
Wyatt Heplerc84393f2020-03-20 11:23:24 -0700869 TRY(GarbageCollectSector(*sector, {}));
David Rogerscd87c322020-02-27 14:04:08 -0800870 }
871 }
872
David Rogers9abe3c72020-03-24 19:03:13 -0700873 DBG("Full maintenance complete");
David Rogerscd87c322020-02-27 14:04:08 -0800874 return Status::OK;
875}
876
David Rogers9abe3c72020-03-24 19:03:13 -0700877Status KeyValueStore::GarbageCollect(span<const Address> reserved_addresses) {
878 if (initialized_ == InitializationState::kNotInitialized) {
879 return Status::FAILED_PRECONDITION;
880 }
881
David Rogersc9d545e2020-03-11 17:47:43 -0700882 DBG("Garbage Collect a single sector");
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700883 for (Address address : reserved_addresses) {
David Rogersc9d545e2020-03-11 17:47:43 -0700884 DBG(" Avoid address %u", unsigned(address));
885 }
David Rogers67f4b6c2020-02-06 16:17:09 -0800886
David Rogersfcea3252020-04-07 14:56:35 -0700887 // Do automatic repair, if KVS options allow for it.
888 if (error_detected_ && options_.recovery != ErrorRecovery::kManual) {
889 TRY(Repair());
890 }
891
David Rogersa12786b2020-01-31 16:02:33 -0800892 // Step 1: Find the sector to garbage collect
David Rogersc9d545e2020-03-11 17:47:43 -0700893 SectorDescriptor* sector_to_gc =
Wyatt Heplerc84393f2020-03-20 11:23:24 -0700894 sectors_.FindSectorToGarbageCollect(reserved_addresses);
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800895
David Rogersa12786b2020-01-31 16:02:33 -0800896 if (sector_to_gc == nullptr) {
David Rogersa2562b52020-03-05 15:30:05 -0800897 // Nothing to GC.
898 return Status::NOT_FOUND;
David Rogersa12786b2020-01-31 16:02:33 -0800899 }
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800900
David Rogersc9d545e2020-03-11 17:47:43 -0700901 // Step 2: Garbage collect the selected sector.
Wyatt Heplerc84393f2020-03-20 11:23:24 -0700902 return GarbageCollectSector(*sector_to_gc, reserved_addresses);
David Rogerscd87c322020-02-27 14:04:08 -0800903}
904
David Rogersf3884eb2020-03-08 19:21:40 -0700905Status KeyValueStore::RelocateKeyAddressesInSector(
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700906 SectorDescriptor& sector_to_gc,
David Rogersfcea3252020-04-07 14:56:35 -0700907 const EntryMetadata& metadata,
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700908 span<const Address> reserved_addresses) {
909 for (FlashPartition::Address& address : metadata.addresses()) {
Wyatt Heplerc84393f2020-03-20 11:23:24 -0700910 if (sectors_.AddressInSector(sector_to_gc, address)) {
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700911 DBG(" Relocate entry for Key 0x%08" PRIx32 ", sector %u",
912 metadata.hash(),
Wyatt Heplerc84393f2020-03-20 11:23:24 -0700913 sectors_.Index(sectors_.FromAddress(address)));
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700914 TRY(RelocateEntry(metadata, address, reserved_addresses));
David Rogersf3884eb2020-03-08 19:21:40 -0700915 }
916 }
Wyatt Heplerab3b2492020-03-11 16:15:16 -0700917
David Rogersf3884eb2020-03-08 19:21:40 -0700918 return Status::OK;
919};
920
Wyatt Heplerab3b2492020-03-11 16:15:16 -0700921Status KeyValueStore::GarbageCollectSector(
Wyatt Heplerc84393f2020-03-20 11:23:24 -0700922 SectorDescriptor& sector_to_gc, span<const Address> reserved_addresses) {
David Rogers9abe3c72020-03-24 19:03:13 -0700923 DBG(" Garbage Collect sector %u", sectors_.Index(sector_to_gc));
David Rogersf3884eb2020-03-08 19:21:40 -0700924 // Step 1: Move any valid entries in the GC sector to other sectors
Wyatt Heplerc84393f2020-03-20 11:23:24 -0700925 if (sector_to_gc.valid_bytes() != 0) {
David Rogers98fea472020-04-01 15:43:48 -0700926 for (EntryMetadata& metadata : entry_cache_) {
Wyatt Heplerab3b2492020-03-11 16:15:16 -0700927 TRY(RelocateKeyAddressesInSector(
Wyatt Heplerc84393f2020-03-20 11:23:24 -0700928 sector_to_gc, metadata, reserved_addresses));
David Rogersf3884eb2020-03-08 19:21:40 -0700929 }
930 }
931
Wyatt Heplerc84393f2020-03-20 11:23:24 -0700932 if (sector_to_gc.valid_bytes() != 0) {
David Rogers67f4b6c2020-02-06 16:17:09 -0800933 ERR(" Failed to relocate valid entries from sector being garbage "
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800934 "collected, %zu valid bytes remain",
Wyatt Heplerc84393f2020-03-20 11:23:24 -0700935 sector_to_gc.valid_bytes());
Wyatt Heplerb7609542020-01-24 10:29:54 -0800936 return Status::INTERNAL;
937 }
938
David Rogerscd87c322020-02-27 14:04:08 -0800939 // Step 2: Reinitialize the sector
David Rogers9abe3c72020-03-24 19:03:13 -0700940 sector_to_gc.mark_corrupt();
Wyatt Heplerc84393f2020-03-20 11:23:24 -0700941 TRY(partition_.Erase(sectors_.BaseAddress(sector_to_gc), 1));
942 sector_to_gc.set_writable_bytes(partition_.sector_size_bytes());
Wyatt Heplerb7609542020-01-24 10:29:54 -0800943
Wyatt Heplerc84393f2020-03-20 11:23:24 -0700944 DBG(" Garbage Collect sector %u complete", sectors_.Index(sector_to_gc));
David Rogersa12786b2020-01-31 16:02:33 -0800945 return Status::OK;
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800946}
947
David Rogers31b358b2020-04-15 05:00:50 -0700948Status KeyValueStore::UpdateEntriesToPrimaryFormat() {
949 for (EntryMetadata& prior_metadata : entry_cache_) {
950 Entry entry;
951 TRY(ReadEntry(prior_metadata, entry));
952 if (formats_.primary().magic == entry.magic()) {
953 // Ignore entries that are already on the primary format.
954 continue;
955 }
956
957 DBG("Updating entry 0x%08x from old format [0x%08x] to new format "
958 "[0x%08x]",
959 unsigned(prior_metadata.hash()),
960 unsigned(entry.magic()),
961 unsigned(formats_.primary().magic));
962
963 last_transaction_id_ += 1;
964 TRY(entry.Update(formats_.primary(), last_transaction_id_));
965
966 // List of addresses for sectors with space for this entry.
967 Address* reserved_addresses = entry_cache_.TempReservedAddressesForWrite();
968
969 // Find addresses to write the entry to. This may involve garbage collecting
970 // one or more sectors.
971 TRY(GetAddressesForWrite(reserved_addresses, entry.size()));
972
973 TRY(CopyEntryToSector(entry,
974 &sectors_.FromAddress(reserved_addresses[0]),
975 reserved_addresses[0]));
976
977 // After writing the first entry successfully, update the key descriptors.
978 // Once a single new the entry is written, the old entries are invalidated.
979 EntryMetadata new_metadata = UpdateKeyDescriptor(
980 entry, reserved_addresses[0], &prior_metadata, entry.size());
981
982 // Write the additional copies of the entry, if redundancy is greater
983 // than 1.
984 for (size_t i = 1; i < redundancy(); ++i) {
985 TRY(CopyEntryToSector(entry,
986 &sectors_.FromAddress(reserved_addresses[i]),
987 reserved_addresses[i]));
988 new_metadata.AddNewAddress(reserved_addresses[i]);
989 }
990 }
991 return Status::OK;
992}
993
David Rogers9abe3c72020-03-24 19:03:13 -0700994// Add any missing redundant entries/copies for a key.
995Status KeyValueStore::AddRedundantEntries(EntryMetadata& metadata) {
996 SectorDescriptor* new_sector;
997
998 Entry entry;
999
David Rogers98fea472020-04-01 15:43:48 -07001000 TRY(ReadEntry(metadata, entry));
David Rogers9abe3c72020-03-24 19:03:13 -07001001 TRY(entry.VerifyChecksumInFlash());
1002
1003 for (size_t i = metadata.addresses().size();
1004 metadata.addresses().size() < redundancy();
1005 i++) {
1006 TRY(sectors_.FindSpace(&new_sector, entry.size(), metadata.addresses()));
1007
David Rogers31b358b2020-04-15 05:00:50 -07001008 Address new_address = sectors_.NextWritableAddress(*new_sector);
David Rogers98fea472020-04-01 15:43:48 -07001009 TRY(CopyEntryToSector(entry, new_sector, new_address));
David Rogers9abe3c72020-03-24 19:03:13 -07001010
1011 metadata.AddNewAddress(new_address);
1012 }
1013 return Status::OK;
1014}
1015
1016Status KeyValueStore::RepairCorruptSectors() {
1017 // Try to GC each corrupt sector, even if previous sectors fail. If GC of a
1018 // sector failed on the first pass, then do a second pass, since a later
1019 // sector might have cleared up space or otherwise unblocked the earlier
1020 // failed sector.
1021 Status repair_status = Status::OK;
1022
1023 size_t loop_count = 0;
1024 do {
1025 loop_count++;
1026 // Error of RESOURCE_EXHAUSTED indicates no space found for relocation.
1027 // Reset back to OK for the next pass.
1028 if (repair_status == Status::RESOURCE_EXHAUSTED) {
1029 repair_status = Status::OK;
1030 }
1031
1032 DBG(" Pass %u", unsigned(loop_count));
1033 for (SectorDescriptor& sector : sectors_) {
1034 if (sector.corrupt()) {
1035 DBG(" Found sector %u with corruption", sectors_.Index(sector));
1036 Status sector_status = GarbageCollectSector(sector, {});
1037 if (sector_status.ok()) {
1038 error_stats_.corrupt_sectors_recovered += 1;
1039 } else if (repair_status.ok() ||
1040 repair_status == Status::RESOURCE_EXHAUSTED) {
1041 repair_status = sector_status;
1042 }
1043 }
1044 }
1045 DBG(" Pass %u complete", unsigned(loop_count));
1046 } while (!repair_status.ok() && loop_count < 2);
1047
1048 return repair_status;
1049}
1050
1051Status KeyValueStore::EnsureFreeSectorExists() {
1052 Status repair_status = Status::OK;
1053 bool empty_sector_found = false;
1054
1055 DBG(" Find empty sector");
1056 for (SectorDescriptor& sector : sectors_) {
1057 if (sector.Empty(partition_.sector_size_bytes())) {
1058 empty_sector_found = true;
1059 DBG(" Empty sector found");
1060 break;
1061 }
1062 }
1063 if (empty_sector_found == false) {
1064 DBG(" No empty sector found, attempting to GC a free sector");
1065 Status sector_status = GarbageCollect(span<const Address, 0>());
1066 if (repair_status.ok() && !sector_status.ok()) {
1067 DBG(" Unable to free an empty sector");
1068 repair_status = sector_status;
1069 }
1070 }
1071
1072 return repair_status;
1073}
1074
1075Status KeyValueStore::EnsureEntryRedundancy() {
1076 Status repair_status = Status::OK;
1077
1078 if (redundancy() == 1) {
David Rogers98fea472020-04-01 15:43:48 -07001079 DBG(" Redundancy not in use, nothting to check");
David Rogers9abe3c72020-03-24 19:03:13 -07001080 return Status::OK;
1081 }
1082
David Rogers98fea472020-04-01 15:43:48 -07001083 DBG(" Write any needed additional duplicate copies of keys to fulfill %u"
1084 " redundancy",
David Rogers9abe3c72020-03-24 19:03:13 -07001085 unsigned(redundancy()));
David Rogers98fea472020-04-01 15:43:48 -07001086 for (EntryMetadata& metadata : entry_cache_) {
David Rogers9abe3c72020-03-24 19:03:13 -07001087 if (metadata.addresses().size() >= redundancy()) {
1088 continue;
1089 }
1090
1091 DBG(" Key with %u of %u copies found, adding missing copies",
1092 unsigned(metadata.addresses().size()),
1093 unsigned(redundancy()));
David Rogers98fea472020-04-01 15:43:48 -07001094 Status fill_status = AddRedundantEntries(metadata);
David Rogers9abe3c72020-03-24 19:03:13 -07001095 if (fill_status.ok()) {
1096 error_stats_.missing_redundant_entries_recovered += 1;
1097 DBG(" Key missing copies added");
1098 } else {
1099 DBG(" Failed to add key missing copies");
1100 if (repair_status.ok()) {
1101 repair_status = fill_status;
1102 }
1103 }
1104 }
1105
1106 return repair_status;
1107}
1108
David Rogersfcea3252020-04-07 14:56:35 -07001109Status KeyValueStore::FixErrors() {
1110 DBG("Fixing KVS errors");
David Rogers9abe3c72020-03-24 19:03:13 -07001111
1112 // Step 1: Garbage collect any sectors marked as corrupt.
David Rogersfcea3252020-04-07 14:56:35 -07001113 Status overall_status = RepairCorruptSectors();
David Rogers9abe3c72020-03-24 19:03:13 -07001114
1115 // Step 2: Make sure there is at least 1 empty sector. This needs to be a
1116 // seperate check of sectors from step 1, because a found empty sector might
1117 // get written to by a later GC that fails and does not result in a free
1118 // sector.
David Rogersfcea3252020-04-07 14:56:35 -07001119 Status repair_status = EnsureFreeSectorExists();
David Rogers9abe3c72020-03-24 19:03:13 -07001120 if (overall_status.ok()) {
1121 overall_status = repair_status;
1122 }
1123
1124 // Step 3: Make sure each stored key has the full number of redundant
1125 // entries.
1126 repair_status = EnsureEntryRedundancy();
1127 if (overall_status.ok()) {
1128 overall_status = repair_status;
1129 }
1130
1131 if (overall_status.ok()) {
1132 error_detected_ = false;
1133 initialized_ = InitializationState::kReady;
1134 }
1135 return overall_status;
1136}
1137
David Rogersfcea3252020-04-07 14:56:35 -07001138Status KeyValueStore::Repair() {
1139 // If errors have been detected, just reinit the KVS metadata. This does a
1140 // full deep error check and any needed repairs. Then repair any errors.
1141 INF("Starting KVS repair");
1142
1143 DBG("Reinitialize KVS metadata");
1144 InitializeMetadata();
1145
1146 return FixErrors();
1147}
1148
Wyatt Heplerbdd8e5a2020-02-20 19:27:26 -08001149KeyValueStore::Entry KeyValueStore::CreateEntry(Address address,
Wyatt Heplerab3b2492020-03-11 16:15:16 -07001150 string_view key,
Wyatt Heplerbdd8e5a2020-02-20 19:27:26 -08001151 span<const byte> value,
Wyatt Hepler7ded6da2020-03-11 18:24:43 -07001152 EntryState state) {
Keir Mierle9e38b402020-02-21 13:06:21 -08001153 // Always bump the transaction ID when creating a new entry.
1154 //
1155 // Burning transaction IDs prevents inconsistencies between flash and memory
1156 // that which could happen if a write succeeds, but for some reason the read
1157 // and verify step fails. Here's how this would happen:
1158 //
1159 // 1. The entry is written but for some reason the flash reports failure OR
1160 // The write succeeds, but the read / verify operation fails.
1161 // 2. The transaction ID is NOT incremented, because of the failure
1162 // 3. (later) A new entry is written, re-using the transaction ID (oops)
1163 //
1164 // By always burning transaction IDs, the above problem can't happen.
1165 last_transaction_id_ += 1;
1166
Wyatt Hepler7ded6da2020-03-11 18:24:43 -07001167 if (state == EntryState::kDeleted) {
Wyatt Hepler7465be32020-02-21 15:30:53 -08001168 return Entry::Tombstone(
Wyatt Hepler22d0d9f2020-03-05 14:57:11 -08001169 partition_, address, formats_.primary(), key, last_transaction_id_);
Wyatt Hepler1fc11042020-02-19 17:17:51 -08001170 }
1171 return Entry::Valid(partition_,
1172 address,
Wyatt Hepler22d0d9f2020-03-05 14:57:11 -08001173 formats_.primary(),
Wyatt Hepler1fc11042020-02-19 17:17:51 -08001174 key,
1175 value,
Keir Mierle9e38b402020-02-21 13:06:21 -08001176 last_transaction_id_);
Wyatt Heplerd2298282020-02-20 17:12:45 -08001177}
1178
Wyatt Hepler7ded6da2020-03-11 18:24:43 -07001179void KeyValueStore::LogDebugInfo() const {
Keir Mierle8c352dc2020-02-02 13:58:19 -08001180 const size_t sector_size_bytes = partition_.sector_size_bytes();
1181 DBG("====================== KEY VALUE STORE DUMP =========================");
1182 DBG(" ");
1183 DBG("Flash partition:");
Wyatt Heplerad0a7932020-02-06 08:20:38 -08001184 DBG(" Sector count = %zu", partition_.sector_count());
Wyatt Hepler38ce30f2020-02-19 11:48:31 -08001185 DBG(" Sector max count = %zu", sectors_.max_size());
Wyatt Hepler1c329ca2020-02-07 18:07:23 -08001186 DBG(" Sectors in use = %zu", sectors_.size());
Keir Mierle8c352dc2020-02-02 13:58:19 -08001187 DBG(" Sector size = %zu", sector_size_bytes);
1188 DBG(" Total size = %zu", partition_.size_bytes());
1189 DBG(" Alignment = %zu", partition_.alignment_bytes());
1190 DBG(" ");
1191 DBG("Key descriptors:");
Wyatt Hepler7ded6da2020-03-11 18:24:43 -07001192 DBG(" Entry count = %zu", entry_cache_.total_entries());
1193 DBG(" Max entry count = %zu", entry_cache_.max_entries());
Keir Mierle8c352dc2020-02-02 13:58:19 -08001194 DBG(" ");
1195 DBG(" # hash version address address (hex)");
Wyatt Hepler7ded6da2020-03-11 18:24:43 -07001196 size_t i = 0;
1197 for (const EntryMetadata& metadata : entry_cache_) {
Keir Mierle8c352dc2020-02-02 13:58:19 -08001198 DBG(" |%3zu: | %8zx |%8zu | %8zu | %8zx",
Wyatt Hepler7ded6da2020-03-11 18:24:43 -07001199 i++,
1200 size_t(metadata.hash()),
1201 size_t(metadata.transaction_id()),
1202 size_t(metadata.first_address()),
1203 size_t(metadata.first_address()));
Keir Mierle8c352dc2020-02-02 13:58:19 -08001204 }
1205 DBG(" ");
1206
1207 DBG("Sector descriptors:");
1208 DBG(" # tail free valid has_space");
Wyatt Heplerc84393f2020-03-20 11:23:24 -07001209 for (const SectorDescriptor& sd : sectors_) {
1210 DBG(" |%3u: | %8zu |%8zu | %s",
1211 sectors_.Index(sd),
Wyatt Hepler2c7eca02020-02-18 16:01:42 -08001212 size_t(sd.writable_bytes()),
1213 sd.valid_bytes(),
1214 sd.writable_bytes() ? "YES" : "");
Keir Mierle8c352dc2020-02-02 13:58:19 -08001215 }
1216 DBG(" ");
1217
1218 // TODO: This should stop logging after some threshold.
1219 // size_t dumped_bytes = 0;
1220 DBG("Sector raw data:");
Wyatt Hepler1c329ca2020-02-07 18:07:23 -08001221 for (size_t sector_id = 0; sector_id < sectors_.size(); ++sector_id) {
Keir Mierle8c352dc2020-02-02 13:58:19 -08001222 // Read sector data. Yes, this will blow the stack on embedded.
Wyatt Hepler1c329ca2020-02-07 18:07:23 -08001223 std::array<byte, 500> raw_sector_data; // TODO!!!
Keir Mierle8c352dc2020-02-02 13:58:19 -08001224 StatusWithSize sws =
1225 partition_.Read(sector_id * sector_size_bytes, raw_sector_data);
1226 DBG("Read: %zu bytes", sws.size());
1227
1228 DBG(" base addr offs 0 1 2 3 4 5 6 7");
1229 for (size_t i = 0; i < sector_size_bytes; i += 8) {
1230 DBG(" %3zu %8zx %5zu | %02x %02x %02x %02x %02x %02x %02x %02x",
1231 sector_id,
1232 (sector_id * sector_size_bytes) + i,
1233 i,
1234 static_cast<unsigned int>(raw_sector_data[i + 0]),
1235 static_cast<unsigned int>(raw_sector_data[i + 1]),
1236 static_cast<unsigned int>(raw_sector_data[i + 2]),
1237 static_cast<unsigned int>(raw_sector_data[i + 3]),
1238 static_cast<unsigned int>(raw_sector_data[i + 4]),
1239 static_cast<unsigned int>(raw_sector_data[i + 5]),
1240 static_cast<unsigned int>(raw_sector_data[i + 6]),
1241 static_cast<unsigned int>(raw_sector_data[i + 7]));
1242
1243 // TODO: Fix exit condition.
1244 if (i > 128) {
1245 break;
1246 }
1247 }
1248 DBG(" ");
1249 }
1250
1251 DBG("////////////////////// KEY VALUE STORE DUMP END /////////////////////");
1252}
1253
David Rogerscf680ab2020-02-12 23:28:32 -08001254void KeyValueStore::LogSectors() const {
1255 DBG("Sector descriptors: count %zu", sectors_.size());
Wyatt Hepler1c329ca2020-02-07 18:07:23 -08001256 for (auto& sector : sectors_) {
Wyatt Hepler2c7eca02020-02-18 16:01:42 -08001257 DBG(" - Sector %u: valid %zu, recoverable %zu, free %zu",
Wyatt Heplerc84393f2020-03-20 11:23:24 -07001258 sectors_.Index(sector),
Wyatt Hepler2c7eca02020-02-18 16:01:42 -08001259 sector.valid_bytes(),
1260 sector.RecoverableBytes(partition_.sector_size_bytes()),
1261 sector.writable_bytes());
David Rogers50185ad2020-02-07 00:02:46 -08001262 }
1263}
1264
David Rogerscf680ab2020-02-12 23:28:32 -08001265void KeyValueStore::LogKeyDescriptor() const {
Wyatt Hepler7ded6da2020-03-11 18:24:43 -07001266 DBG("Key descriptors: count %zu", entry_cache_.total_entries());
David Rogers9abe3c72020-03-24 19:03:13 -07001267 for (const EntryMetadata& metadata : entry_cache_) {
Wyatt Hepler7ded6da2020-03-11 18:24:43 -07001268 DBG(" - Key: %s, hash %#zx, transaction ID %zu, first address %#zx",
Wyatt Hepler02946272020-03-18 10:36:22 -07001269 metadata.state() == EntryState::kDeleted ? "Deleted" : "Valid",
Wyatt Hepler7ded6da2020-03-11 18:24:43 -07001270 static_cast<size_t>(metadata.hash()),
1271 static_cast<size_t>(metadata.transaction_id()),
1272 static_cast<size_t>(metadata.first_address()));
David Rogerscf680ab2020-02-12 23:28:32 -08001273 }
1274}
1275
Wyatt Hepler2ad60672020-01-21 08:00:16 -08001276} // namespace pw::kvs