blob: d76323ed22efeacbfe821f22ddc159166a0b085f [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
Wyatt Hepler22d0d9f2020-03-05 14:57:11 -080022#include "pw_kvs/format.h"
23
Keir Mierle8c352dc2020-02-02 13:58:19 -080024#define PW_LOG_USE_ULTRA_SHORT_NAMES 1
Wyatt Heplerbdd8e5a2020-02-20 19:27:26 -080025#include "pw_kvs/internal/entry.h"
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -080026#include "pw_kvs_private/macros.h"
Keir Mierle8c352dc2020-02-02 13:58:19 -080027#include "pw_log/log.h"
Wyatt Heplerb7609542020-01-24 10:29:54 -080028
Wyatt Hepler2ad60672020-01-21 08:00:16 -080029namespace pw::kvs {
Wyatt Heplera00d1ef2020-02-14 14:31:26 -080030namespace {
Wyatt Heplerb7609542020-01-24 10:29:54 -080031
Wyatt Hepleracaacf92020-01-24 10:58:30 -080032using std::byte;
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -080033using std::string_view;
Wyatt Hepleracaacf92020-01-24 10:58:30 -080034
Wyatt Heplera00d1ef2020-02-14 14:31:26 -080035constexpr bool InvalidKey(std::string_view key) {
Wyatt Heplerbdd8e5a2020-02-20 19:27:26 -080036 return key.empty() || (key.size() > internal::Entry::kMaxKeyLength);
Wyatt Heplera00d1ef2020-02-14 14:31:26 -080037}
38
Wyatt Heplerab3b2492020-03-11 16:15:16 -070039// Returns true if the container conatins the value.
40// TODO: At some point move this to pw_containers, along with adding tests.
41template <typename Container, typename T>
42bool Contains(const Container& container, const T& value) {
43 return std::find(std::begin(container), std::end(container), value) !=
44 std::end(container);
45}
46
Wyatt Heplera00d1ef2020-02-14 14:31:26 -080047} // namespace
48
Wyatt Heplerad0a7932020-02-06 08:20:38 -080049KeyValueStore::KeyValueStore(FlashPartition* partition,
Wyatt Hepler38ce30f2020-02-19 11:48:31 -080050 Vector<KeyDescriptor>& key_descriptor_list,
51 Vector<SectorDescriptor>& sector_descriptor_list,
David Rogersf3884eb2020-03-08 19:21:40 -070052 size_t redundancy,
Wyatt Hepler22d0d9f2020-03-05 14:57:11 -080053 span<const EntryFormat> formats,
Wyatt Heplerad0a7932020-02-06 08:20:38 -080054 const Options& options)
55 : partition_(*partition),
Wyatt Hepler22d0d9f2020-03-05 14:57:11 -080056 formats_(formats),
Wyatt Hepler38ce30f2020-02-19 11:48:31 -080057 key_descriptors_(key_descriptor_list),
Wyatt Heplerd2298282020-02-20 17:12:45 -080058 sectors_(sector_descriptor_list),
David Rogersf3884eb2020-03-08 19:21:40 -070059 redundancy_(redundancy),
Wyatt Heplerd2298282020-02-20 17:12:45 -080060 options_(options) {
Keir Mierlebf904812020-03-11 17:28:22 -070061 initialized_ = false;
62 last_new_sector_ = nullptr;
63 last_transaction_id_ = 0;
Wyatt Heplerd2298282020-02-20 17:12:45 -080064}
Wyatt Heplerad0a7932020-02-06 08:20:38 -080065
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -080066Status KeyValueStore::Init() {
Keir Mierlebf904812020-03-11 17:28:22 -070067 initialized_ = false;
68 last_new_sector_ = nullptr;
69 last_transaction_id_ = 0;
70 key_descriptors_.clear();
Wyatt Heplerd2298282020-02-20 17:12:45 -080071
David Rogers2e9e0c82020-02-13 15:06:06 -080072 INF("Initializing key value store");
Wyatt Hepler38ce30f2020-02-19 11:48:31 -080073 if (partition_.sector_count() > sectors_.max_size()) {
David Rogers2e9e0c82020-02-13 15:06:06 -080074 ERR("KVS init failed: kMaxUsableSectors (=%zu) must be at least as "
75 "large as the number of sectors in the flash partition (=%zu)",
Wyatt Hepler38ce30f2020-02-19 11:48:31 -080076 sectors_.max_size(),
David Rogers2e9e0c82020-02-13 15:06:06 -080077 partition_.sector_count());
Wyatt Heplerad0a7932020-02-06 08:20:38 -080078 return Status::FAILED_PRECONDITION;
79 }
80
Keir Mierle8c352dc2020-02-02 13:58:19 -080081 const size_t sector_size_bytes = partition_.sector_size_bytes();
Keir Mierle8c352dc2020-02-02 13:58:19 -080082
83 DBG("First pass: Read all entries from all sectors");
Wyatt Hepler2c7eca02020-02-18 16:01:42 -080084 Address sector_address = 0;
Keir Mierle8c352dc2020-02-02 13:58:19 -080085
Wyatt Heplerd2298282020-02-20 17:12:45 -080086 sectors_.assign(partition_.sector_count(),
87 SectorDescriptor(sector_size_bytes));
88
Alexei Frolovd4adf912020-02-21 13:29:15 -080089 size_t total_corrupt_bytes = 0;
90 int corrupt_entries = 0;
David Rogers91627482020-02-27 17:38:12 -080091 bool empty_sector_found = false;
Alexei Frolovd4adf912020-02-21 13:29:15 -080092
Wyatt Hepler2c7eca02020-02-18 16:01:42 -080093 for (SectorDescriptor& sector : sectors_) {
Keir Mierle8c352dc2020-02-02 13:58:19 -080094 Address entry_address = sector_address;
95
Alexei Frolovd4adf912020-02-21 13:29:15 -080096 size_t sector_corrupt_bytes = 0;
97
Wyatt Hepler2c7eca02020-02-18 16:01:42 -080098 for (int num_entries_in_sector = 0; true; num_entries_in_sector++) {
99 DBG("Load entry: sector=%" PRIx32 ", entry#=%d, address=%" PRIx32,
100 sector_address,
Keir Mierle8c352dc2020-02-02 13:58:19 -0800101 num_entries_in_sector,
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800102 entry_address);
Keir Mierle8c352dc2020-02-02 13:58:19 -0800103
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800104 if (!AddressInSector(sector, entry_address)) {
Keir Mierle8c352dc2020-02-02 13:58:19 -0800105 DBG("Fell off end of sector; moving to the next sector");
106 break;
107 }
108
109 Address next_entry_address;
110 Status status = LoadEntry(entry_address, &next_entry_address);
111 if (status == Status::NOT_FOUND) {
112 DBG("Hit un-written data in sector; moving to the next sector");
113 break;
114 }
115 if (status == Status::DATA_LOSS) {
Alexei Frolovd4adf912020-02-21 13:29:15 -0800116 // The entry could not be read, indicating data corruption within the
117 // sector. Try to scan the remainder of the sector for other entries.
David Rogersa2562b52020-03-05 15:30:05 -0800118 WRN("KVS init: data loss detected in sector %u at address %zu",
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800119 SectorIndex(&sector),
120 size_t(entry_address));
Alexei Frolovd4adf912020-02-21 13:29:15 -0800121
122 corrupt_entries++;
123
124 status = ScanForEntry(sector,
125 entry_address + Entry::kMinAlignmentBytes,
126 &next_entry_address);
127 if (status == Status::NOT_FOUND) {
128 // No further entries in this sector. Mark the remaining bytes in the
129 // sector as corrupt (since we can't reliably know the size of the
130 // corrupt entry).
131 sector_corrupt_bytes +=
132 sector_size_bytes - (entry_address - sector_address);
133 break;
134 }
135
136 if (!status.ok()) {
137 ERR("Unexpected error in KVS initialization: %s", status.str());
138 return Status::UNKNOWN;
139 }
140
141 sector_corrupt_bytes += next_entry_address - entry_address;
142 } else if (!status.ok()) {
143 ERR("Unexpected error in KVS initialization: %s", status.str());
144 return Status::UNKNOWN;
Keir Mierle8c352dc2020-02-02 13:58:19 -0800145 }
Keir Mierle8c352dc2020-02-02 13:58:19 -0800146
147 // Entry loaded successfully; so get ready to load the next one.
148 entry_address = next_entry_address;
149
150 // Update of the number of writable bytes in this sector.
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800151 sector.set_writable_bytes(sector_size_bytes -
152 (entry_address - sector_address));
Keir Mierle8c352dc2020-02-02 13:58:19 -0800153 }
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800154
Alexei Frolovd4adf912020-02-21 13:29:15 -0800155 if (sector_corrupt_bytes > 0) {
156 // If the sector contains corrupt data, prevent any further entries from
157 // being written to it by indicating that it has no space. This should
158 // also make it a decent GC candidate. Valid keys in the sector are still
159 // readable as normal.
160 sector.set_writable_bytes(0);
161
162 WRN("Sector %u contains %zuB of corrupt data",
163 SectorIndex(&sector),
164 sector_corrupt_bytes);
165 }
166
David Rogers91627482020-02-27 17:38:12 -0800167 if (sector.Empty(sector_size_bytes)) {
168 empty_sector_found = true;
169 }
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800170 sector_address += sector_size_bytes;
Alexei Frolovd4adf912020-02-21 13:29:15 -0800171 total_corrupt_bytes += sector_corrupt_bytes;
Keir Mierle8c352dc2020-02-02 13:58:19 -0800172 }
173
174 DBG("Second pass: Count valid bytes in each sector");
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800175 const KeyDescriptor* newest_key = nullptr;
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800176
Keir Mierle8c352dc2020-02-02 13:58:19 -0800177 // For every valid key, increment the valid bytes for that sector.
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800178 for (KeyDescriptor& key_descriptor : key_descriptors_) {
David Rogersf56131c2020-03-04 10:19:22 -0800179 for (auto& address : key_descriptor.addresses()) {
180 Entry entry;
David Rogersa2562b52020-03-05 15:30:05 -0800181 TRY(Entry::Read(partition_, address, formats_, &entry));
David Rogersf56131c2020-03-04 10:19:22 -0800182 SectorFromAddress(address)->AddValidBytes(entry.size());
183 }
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800184 if (key_descriptor.IsNewerThan(last_transaction_id_)) {
185 last_transaction_id_ = key_descriptor.transaction_id();
186 newest_key = &key_descriptor;
187 }
Keir Mierle8c352dc2020-02-02 13:58:19 -0800188 }
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800189
190 if (newest_key == nullptr) {
191 last_new_sector_ = sectors_.begin();
192 } else {
David Rogersf56131c2020-03-04 10:19:22 -0800193 last_new_sector_ = SectorFromAddress(newest_key->addresses().back());
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800194 }
195
David Rogers91627482020-02-27 17:38:12 -0800196 if (!empty_sector_found) {
197 // TODO: Record/report the error condition and recovery result.
198 Status gc_result = GarbageCollectPartial();
199
200 if (!gc_result.ok()) {
201 ERR("KVS init failed: Unable to maintain required free sector");
202 return Status::INTERNAL;
203 }
204 }
205
Wyatt Hepler729f28c2020-02-05 09:46:00 -0800206 initialized_ = true;
David Rogers2e9e0c82020-02-13 15:06:06 -0800207
Armando Montanez5464d5f2020-02-20 10:12:20 -0800208 INF("KeyValueStore init complete: active keys %zu, deleted keys %zu, sectors "
David Rogers2e9e0c82020-02-13 15:06:06 -0800209 "%zu, logical sector size %zu bytes",
210 size(),
211 (key_descriptors_.size() - size()),
212 sectors_.size(),
213 partition_.sector_size_bytes());
214
Alexei Frolovd4adf912020-02-21 13:29:15 -0800215 if (total_corrupt_bytes > 0) {
216 WRN("Found %zu corrupt bytes and %d corrupt entries during init process; "
217 "some keys may be missing",
218 total_corrupt_bytes,
219 corrupt_entries);
220 return Status::DATA_LOSS;
221 }
222
Keir Mierle8c352dc2020-02-02 13:58:19 -0800223 return Status::OK;
224}
225
Alexei Frolov9e235832020-02-24 12:44:45 -0800226KeyValueStore::StorageStats KeyValueStore::GetStorageStats() const {
227 StorageStats stats{0, 0, 0};
228 const size_t sector_size = partition_.sector_size_bytes();
229 bool found_empty_sector = false;
230
231 for (const SectorDescriptor& sector : sectors_) {
232 stats.in_use_bytes += sector.valid_bytes();
233 stats.reclaimable_bytes += sector.RecoverableBytes(sector_size);
234
235 if (!found_empty_sector && sector.Empty(sector_size)) {
236 // The KVS tries to always keep an empty sector for GC, so don't count
237 // the first empty sector seen as writable space. However, a free sector
238 // cannot always be assumed to exist; if a GC operation fails, all sectors
239 // may be partially written, in which case the space reported might be
240 // inaccurate.
241 found_empty_sector = true;
242 continue;
243 }
244
245 stats.writable_bytes += sector.writable_bytes();
246 }
247
248 return stats;
249}
250
Keir Mierle8c352dc2020-02-02 13:58:19 -0800251Status KeyValueStore::LoadEntry(Address entry_address,
252 Address* next_entry_address) {
Wyatt Heplere541e072020-02-14 09:10:53 -0800253 Entry entry;
Wyatt Hepler22d0d9f2020-03-05 14:57:11 -0800254 TRY(Entry::Read(partition_, entry_address, formats_, &entry));
Keir Mierle8c352dc2020-02-02 13:58:19 -0800255
256 // Read the key from flash & validate the entry (which reads the value).
Wyatt Heplera00d1ef2020-02-14 14:31:26 -0800257 Entry::KeyBuffer key_buffer;
Wyatt Heplere541e072020-02-14 09:10:53 -0800258 TRY_ASSIGN(size_t key_length, entry.ReadKey(key_buffer));
259 const string_view key(key_buffer.data(), key_length);
Wyatt Heplerbab0e202020-02-04 07:40:08 -0800260
Wyatt Hepler22d0d9f2020-03-05 14:57:11 -0800261 TRY(entry.VerifyChecksumInFlash());
David Rogersf56131c2020-03-04 10:19:22 -0800262
263 // A valid entry was found, so update the next entry address before doing any
264 // of the checks that happen in AppendNewOrOverwriteStaleExistingDescriptor().
265 *next_entry_address = entry.next_address();
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800266 TRY(AppendNewOrOverwriteStaleExistingDescriptor(entry.descriptor(key)));
Keir Mierle8c352dc2020-02-02 13:58:19 -0800267
Keir Mierle8c352dc2020-02-02 13:58:19 -0800268 return Status::OK;
269}
270
Alexei Frolovd4adf912020-02-21 13:29:15 -0800271// Scans flash memory within a sector to find a KVS entry magic.
Alexei Frolovd4adf912020-02-21 13:29:15 -0800272Status KeyValueStore::ScanForEntry(const SectorDescriptor& sector,
273 Address start_address,
274 Address* next_entry_address) {
275 DBG("Scanning sector %u for entries starting from address %zx",
276 SectorIndex(&sector),
277 size_t(start_address));
278
279 // Entries must start at addresses which are aligned on a multiple of
280 // Entry::kMinAlignmentBytes. However, that multiple can vary between entries.
281 // When scanning, we don't have an entry to tell us what the current alignment
282 // is, so the minimum alignment is used to be exhaustive.
283 for (Address address = AlignUp(start_address, Entry::kMinAlignmentBytes);
284 AddressInSector(sector, address);
285 address += Entry::kMinAlignmentBytes) {
Alexei Frolovd4adf912020-02-21 13:29:15 -0800286 uint32_t magic;
287 TRY(partition_.Read(address, as_writable_bytes(span(&magic, 1))));
Wyatt Hepler22d0d9f2020-03-05 14:57:11 -0800288 if (formats_.KnownMagic(magic)) {
Alexei Frolovd4adf912020-02-21 13:29:15 -0800289 DBG("Found entry magic at address %zx", size_t(address));
290 *next_entry_address = address;
291 return Status::OK;
292 }
293 }
294
295 return Status::NOT_FOUND;
296}
297
Keir Mierle8c352dc2020-02-02 13:58:19 -0800298// TODO: This method is the trigger of the O(valid_entries * all_entries) time
299// complexity for reading. At some cost to memory, this could be optimized by
300// using a hash table instead of scanning, but in practice this should be fine
301// for a small number of keys
302Status KeyValueStore::AppendNewOrOverwriteStaleExistingDescriptor(
303 const KeyDescriptor& key_descriptor) {
304 // With the new key descriptor, either add it to the descriptor table or
305 // overwrite an existing entry with an older version of the key.
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800306 KeyDescriptor* existing_descriptor = FindDescriptor(key_descriptor.hash());
Keir Mierle8c352dc2020-02-02 13:58:19 -0800307
Wyatt Hepler5406a672020-02-18 15:42:38 -0800308 // Write a new entry.
309 if (existing_descriptor == nullptr) {
310 if (key_descriptors_.full()) {
311 return Status::RESOURCE_EXHAUSTED;
312 }
313 key_descriptors_.push_back(key_descriptor);
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800314 } else if (key_descriptor.IsNewerThan(
315 existing_descriptor->transaction_id())) {
Wyatt Hepler5406a672020-02-18 15:42:38 -0800316 // Existing entry is old; replace the existing entry with the new one.
317 *existing_descriptor = key_descriptor;
David Rogersf56131c2020-03-04 10:19:22 -0800318 } else if (existing_descriptor->transaction_id() ==
319 key_descriptor.transaction_id()) {
320 // If the entries have a duplicate transaction ID, add the new (redundant)
321 // entry to the existing descriptor.
322 if (existing_descriptor->hash() != key_descriptor.hash()) {
David Rogersf3884eb2020-03-08 19:21:40 -0700323 ERR("Duplicate entry for key 0x%08" PRIx32 " with transaction ID %" PRIu32
David Rogersf56131c2020-03-04 10:19:22 -0800324 " has non-matching hash",
325 key_descriptor.hash(),
326 key_descriptor.transaction_id());
Wyatt Hepler5406a672020-02-18 15:42:38 -0800327 return Status::DATA_LOSS;
328 }
David Rogersf56131c2020-03-04 10:19:22 -0800329
330 // Verify that this entry is not in the same sector as an existing copy of
331 // this same key.
332 for (auto address : existing_descriptor->addresses()) {
333 if (SectorFromAddress(address) ==
334 SectorFromAddress(key_descriptor.address())) {
335 DBG("Multiple Redundant entries in same sector %u",
336 SectorIndex(SectorFromAddress(address)));
337 return Status::DATA_LOSS;
338 }
339 }
340 existing_descriptor->addresses().push_back(key_descriptor.address());
341 } else {
Wyatt Hepler5406a672020-02-18 15:42:38 -0800342 DBG("Found stale entry when appending; ignoring");
Keir Mierle8c352dc2020-02-02 13:58:19 -0800343 }
Keir Mierle8c352dc2020-02-02 13:58:19 -0800344 return Status::OK;
345}
346
Keir Mierle8c352dc2020-02-02 13:58:19 -0800347KeyValueStore::KeyDescriptor* KeyValueStore::FindDescriptor(uint32_t hash) {
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800348 for (KeyDescriptor& key_descriptor : key_descriptors_) {
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800349 if (key_descriptor.hash() == hash) {
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800350 return &key_descriptor;
Keir Mierle8c352dc2020-02-02 13:58:19 -0800351 }
352 }
353 return nullptr;
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800354}
355
356StatusWithSize KeyValueStore::Get(string_view key,
Wyatt Hepler5f6efc02020-02-18 16:54:31 -0800357 span<byte> value_buffer,
358 size_t offset_bytes) const {
Wyatt Hepler50f70772020-02-13 11:25:10 -0800359 TRY_WITH_SIZE(CheckOperation(key));
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800360
David Rogers2761aeb2020-01-31 17:09:00 -0800361 const KeyDescriptor* key_descriptor;
Wyatt Hepler2d401692020-02-13 16:01:23 -0800362 TRY_WITH_SIZE(FindExistingKeyDescriptor(key, &key_descriptor));
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800363
Wyatt Heplerfac81132020-02-27 17:26:33 -0800364 return Get(key, *key_descriptor, value_buffer, offset_bytes);
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800365}
366
Wyatt Heplerfac81132020-02-27 17:26:33 -0800367Status KeyValueStore::PutBytes(string_view key, span<const byte> value) {
Keir Mierle8c352dc2020-02-02 13:58:19 -0800368 DBG("Writing key/value; key length=%zu, value length=%zu",
369 key.size(),
370 value.size());
Wyatt Hepler729f28c2020-02-05 09:46:00 -0800371
372 TRY(CheckOperation(key));
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800373
Wyatt Hepler5406a672020-02-18 15:42:38 -0800374 if (Entry::size(partition_, key, value) > partition_.sector_size_bytes()) {
375 DBG("%zu B value with %zu B key cannot fit in one sector",
376 value.size(),
377 key.size());
378 return Status::INVALID_ARGUMENT;
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800379 }
380
David Rogers2761aeb2020-01-31 17:09:00 -0800381 KeyDescriptor* key_descriptor;
Wyatt Hepler2d401692020-02-13 16:01:23 -0800382 Status status = FindKeyDescriptor(key, &key_descriptor);
383
384 if (status.ok()) {
David Rogersf56131c2020-03-04 10:19:22 -0800385 // TODO: figure out logging how to support multiple addresses.
David Rogersf3884eb2020-03-08 19:21:40 -0700386 DBG("Overwriting entry for key 0x%08" PRIx32 " in %u sectors including %u",
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800387 key_descriptor->hash(),
David Rogersf56131c2020-03-04 10:19:22 -0800388 unsigned(key_descriptor->addresses().size()),
389 SectorIndex(SectorFromAddress(key_descriptor->address())));
Wyatt Hepler5a33d8c2020-02-06 09:32:58 -0800390 return WriteEntryForExistingKey(
391 key_descriptor, KeyDescriptor::kValid, key, value);
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800392 }
David Rogers2761aeb2020-01-31 17:09:00 -0800393
Wyatt Hepler2d401692020-02-13 16:01:23 -0800394 if (status == Status::NOT_FOUND) {
395 return WriteEntryForNewKey(key, value);
396 }
397
398 return status;
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800399}
400
401Status KeyValueStore::Delete(string_view key) {
Wyatt Hepler729f28c2020-02-05 09:46:00 -0800402 TRY(CheckOperation(key));
403
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800404 KeyDescriptor* key_descriptor;
Wyatt Hepler2d401692020-02-13 16:01:23 -0800405 TRY(FindExistingKeyDescriptor(key, &key_descriptor));
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800406
David Rogersf56131c2020-03-04 10:19:22 -0800407 // TODO: figure out logging how to support multiple addresses.
David Rogersf3884eb2020-03-08 19:21:40 -0700408 DBG("Writing tombstone for key 0x%08" PRIx32 " in %u sectors including %u",
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800409 key_descriptor->hash(),
David Rogersf56131c2020-03-04 10:19:22 -0800410 unsigned(key_descriptor->addresses().size()),
411 SectorIndex(SectorFromAddress(key_descriptor->address())));
Wyatt Hepler5a33d8c2020-02-06 09:32:58 -0800412 return WriteEntryForExistingKey(
413 key_descriptor, KeyDescriptor::kDeleted, key, {});
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800414}
415
Wyatt Hepler08d37d82020-02-27 15:45:37 -0800416void KeyValueStore::Item::ReadKey() {
417 key_buffer_.fill('\0');
418
419 Entry entry;
David Rogersf3884eb2020-03-08 19:21:40 -0700420 // TODO: add support for using one of the redundant entries if reading the
421 // first copy fails.
Wyatt Hepler22d0d9f2020-03-05 14:57:11 -0800422 if (Entry::Read(
423 kvs_.partition_, descriptor_->address(), kvs_.formats_, &entry)
424 .ok()) {
Wyatt Hepler08d37d82020-02-27 15:45:37 -0800425 entry.ReadKey(key_buffer_);
426 }
427}
428
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800429KeyValueStore::iterator& KeyValueStore::iterator::operator++() {
430 // Skip to the next entry that is valid (not deleted).
Wyatt Hepler08d37d82020-02-27 15:45:37 -0800431 while (++item_.descriptor_ != item_.kvs_.key_descriptors_.end() &&
432 item_.descriptor_->deleted()) {
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800433 }
434 return *this;
435}
436
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800437KeyValueStore::iterator KeyValueStore::begin() const {
Wyatt Hepler08d37d82020-02-27 15:45:37 -0800438 const KeyDescriptor* descriptor = key_descriptors_.begin();
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800439 // Skip over any deleted entries at the start of the descriptor list.
Wyatt Hepler08d37d82020-02-27 15:45:37 -0800440 while (descriptor != key_descriptors_.end() && descriptor->deleted()) {
441 ++descriptor;
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800442 }
Wyatt Hepler08d37d82020-02-27 15:45:37 -0800443 return iterator(*this, descriptor);
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800444}
445
446// TODO(hepler): The valid entry count could be tracked in the KVS to avoid the
447// need for this for-loop.
448size_t KeyValueStore::size() const {
449 size_t valid_entries = 0;
450
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800451 for (const KeyDescriptor& key_descriptor : key_descriptors_) {
452 if (!key_descriptor.deleted()) {
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800453 valid_entries += 1;
454 }
455 }
456
457 return valid_entries;
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800458}
459
Wyatt Heplerab3b2492020-03-11 16:15:16 -0700460StatusWithSize KeyValueStore::ValueSize(string_view key) const {
Wyatt Hepler50f70772020-02-13 11:25:10 -0800461 TRY_WITH_SIZE(CheckOperation(key));
Wyatt Heplered163b02020-02-03 17:49:32 -0800462
463 const KeyDescriptor* key_descriptor;
Wyatt Hepler2d401692020-02-13 16:01:23 -0800464 TRY_WITH_SIZE(FindExistingKeyDescriptor(key, &key_descriptor));
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800465
Wyatt Heplerfac81132020-02-27 17:26:33 -0800466 return ValueSize(*key_descriptor);
467}
Wyatt Heplered163b02020-02-03 17:49:32 -0800468
Wyatt Heplerfac81132020-02-27 17:26:33 -0800469StatusWithSize KeyValueStore::Get(string_view key,
470 const KeyDescriptor& descriptor,
471 span<std::byte> value_buffer,
472 size_t offset_bytes) const {
473 Entry entry;
David Rogersa2562b52020-03-05 15:30:05 -0800474 // TODO: add support for using one of the redundant entries if reading the
475 // first copy fails.
Wyatt Hepler22d0d9f2020-03-05 14:57:11 -0800476 TRY_WITH_SIZE(
477 Entry::Read(partition_, descriptor.address(), formats_, &entry));
Wyatt Heplerfac81132020-02-27 17:26:33 -0800478
479 StatusWithSize result = entry.ReadValue(value_buffer, offset_bytes);
480 if (result.ok() && options_.verify_on_read && offset_bytes == 0u) {
Wyatt Hepler22d0d9f2020-03-05 14:57:11 -0800481 Status verify_result =
482 entry.VerifyChecksum(key, value_buffer.first(result.size()));
Wyatt Heplerfac81132020-02-27 17:26:33 -0800483 if (!verify_result.ok()) {
484 std::memset(value_buffer.data(), 0, result.size());
485 return StatusWithSize(verify_result, 0);
486 }
487
488 return StatusWithSize(verify_result, result.size());
489 }
490 return result;
Wyatt Heplered163b02020-02-03 17:49:32 -0800491}
492
Wyatt Hepler6e3a83b2020-02-04 07:36:45 -0800493Status KeyValueStore::FixedSizeGet(std::string_view key,
Wyatt Heplerfac81132020-02-27 17:26:33 -0800494 void* value,
495 size_t size_bytes) const {
496 TRY(CheckOperation(key));
497
498 const KeyDescriptor* descriptor;
499 TRY(FindExistingKeyDescriptor(key, &descriptor));
500
501 return FixedSizeGet(key, *descriptor, value, size_bytes);
502}
503
504Status KeyValueStore::FixedSizeGet(std::string_view key,
505 const KeyDescriptor& descriptor,
506 void* value,
Wyatt Hepler6e3a83b2020-02-04 07:36:45 -0800507 size_t size_bytes) const {
508 // Ensure that the size of the stored value matches the size of the type.
509 // Otherwise, report error. This check avoids potential memory corruption.
Wyatt Heplerfac81132020-02-27 17:26:33 -0800510 TRY_ASSIGN(const size_t actual_size, ValueSize(descriptor));
511
512 if (actual_size != size_bytes) {
513 DBG("Requested %zu B read, but value is %zu B", size_bytes, actual_size);
Wyatt Hepler6e3a83b2020-02-04 07:36:45 -0800514 return Status::INVALID_ARGUMENT;
Wyatt Heplerbab0e202020-02-04 07:40:08 -0800515 }
Wyatt Heplerfac81132020-02-27 17:26:33 -0800516
517 StatusWithSize result =
518 Get(key, descriptor, span(static_cast<byte*>(value), size_bytes), 0);
519
520 return result.status();
521}
522
523StatusWithSize KeyValueStore::ValueSize(const KeyDescriptor& descriptor) const {
524 Entry entry;
David Rogersf3884eb2020-03-08 19:21:40 -0700525 // TODO: add support for using one of the redundant entries if reading the
526 // first copy fails.
Wyatt Hepler22d0d9f2020-03-05 14:57:11 -0800527 TRY_WITH_SIZE(
528 Entry::Read(partition_, descriptor.address(), formats_, &entry));
Wyatt Heplerfac81132020-02-27 17:26:33 -0800529
530 return StatusWithSize(entry.value_size());
Keir Mierle8c352dc2020-02-02 13:58:19 -0800531}
532
Wyatt Hepler729f28c2020-02-05 09:46:00 -0800533Status KeyValueStore::CheckOperation(string_view key) const {
Wyatt Hepleracaacf92020-01-24 10:58:30 -0800534 if (InvalidKey(key)) {
Wyatt Heplerb7609542020-01-24 10:29:54 -0800535 return Status::INVALID_ARGUMENT;
536 }
Wyatt Heplerd2298282020-02-20 17:12:45 -0800537 if (!initialized()) {
Wyatt Heplerb7609542020-01-24 10:29:54 -0800538 return Status::FAILED_PRECONDITION;
539 }
Wyatt Heplerb7609542020-01-24 10:29:54 -0800540 return Status::OK;
541}
542
Wyatt Hepler2d401692020-02-13 16:01:23 -0800543// Searches for a KeyDescriptor that matches this key and sets *result to point
544// to it if one is found.
545//
546// OK: there is a matching descriptor and *result is set
547// NOT_FOUND: there is no descriptor that matches this key, but this key
548// has a unique hash (and could potentially be added to the KVS)
549// ALREADY_EXISTS: there is no descriptor that matches this key, but the
550// key's hash collides with the hash for an existing descriptor
551//
David Rogers2761aeb2020-01-31 17:09:00 -0800552Status KeyValueStore::FindKeyDescriptor(string_view key,
553 const KeyDescriptor** result) const {
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800554 const uint32_t hash = internal::Hash(key);
Wyatt Heplera00d1ef2020-02-14 14:31:26 -0800555 Entry::KeyBuffer key_buffer;
Wyatt Heplerb7609542020-01-24 10:29:54 -0800556
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800557 for (auto& descriptor : key_descriptors_) {
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800558 if (descriptor.hash() == hash) {
David Rogersf3884eb2020-03-08 19:21:40 -0700559 // TODO: add support for using one of the redundant entries if reading the
560 // first copy fails.
Wyatt Heplere541e072020-02-14 09:10:53 -0800561 TRY(Entry::ReadKey(
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800562 partition_, descriptor.address(), key.size(), key_buffer.data()));
Wyatt Heplerb7609542020-01-24 10:29:54 -0800563
Wyatt Heplere541e072020-02-14 09:10:53 -0800564 if (key == string_view(key_buffer.data(), key.size())) {
Wyatt Hepler5a33d8c2020-02-06 09:32:58 -0800565 DBG("Found match for key hash 0x%08" PRIx32, hash);
David Rogers2761aeb2020-01-31 17:09:00 -0800566 *result = &descriptor;
Wyatt Heplerb7609542020-01-24 10:29:54 -0800567 return Status::OK;
Wyatt Hepler2d401692020-02-13 16:01:23 -0800568 } else {
569 WRN("Found key hash collision for 0x%08" PRIx32, hash);
570 return Status::ALREADY_EXISTS;
Wyatt Heplerb7609542020-01-24 10:29:54 -0800571 }
Wyatt Heplerb7609542020-01-24 10:29:54 -0800572 }
573 }
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800574 return Status::NOT_FOUND;
575}
576
Wyatt Hepler2d401692020-02-13 16:01:23 -0800577// Searches for a KeyDescriptor that matches this key and sets *result to point
578// to it if one is found.
579//
580// OK: there is a matching descriptor and *result is set
581// NOT_FOUND: there is no descriptor that matches this key
582//
583Status KeyValueStore::FindExistingKeyDescriptor(
584 string_view key, const KeyDescriptor** result) const {
585 Status status = FindKeyDescriptor(key, result);
586
587 // If the key's hash collides with an existing key or if the key is deleted,
588 // treat it as if it is not in the KVS.
589 if (status == Status::ALREADY_EXISTS ||
590 (status.ok() && (*result)->deleted())) {
591 return Status::NOT_FOUND;
592 }
593 return status;
594}
595
David Rogers2761aeb2020-01-31 17:09:00 -0800596Status KeyValueStore::WriteEntryForExistingKey(KeyDescriptor* key_descriptor,
Wyatt Hepler5a33d8c2020-02-06 09:32:58 -0800597 KeyDescriptor::State new_state,
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800598 string_view key,
599 span<const byte> value) {
Wyatt Heplerab3b2492020-03-11 16:15:16 -0700600 // Read the original entry to get the size for sector accounting purposes.
601 Entry entry;
David Rogersa2562b52020-03-05 15:30:05 -0800602 // TODO: add support for using one of the redundant entries if reading the
603 // first copy fails.
Wyatt Heplerab3b2492020-03-11 16:15:16 -0700604 TRY(Entry::Read(partition_, key_descriptor->address(), formats_, &entry));
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800605
Wyatt Heplerab3b2492020-03-11 16:15:16 -0700606 return WriteEntry(key, value, new_state, key_descriptor, entry.size());
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800607}
608
609Status KeyValueStore::WriteEntryForNewKey(string_view key,
610 span<const byte> value) {
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800611 if (key_descriptors_.full()) {
Keir Mierle8c352dc2020-02-02 13:58:19 -0800612 WRN("KVS full: trying to store a new entry, but can't. Have %zu entries",
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800613 key_descriptors_.size());
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800614 return Status::RESOURCE_EXHAUSTED;
615 }
616
Wyatt Heplerab3b2492020-03-11 16:15:16 -0700617 return WriteEntry(key, value, KeyDescriptor::kValid);
618}
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800619
Wyatt Heplerab3b2492020-03-11 16:15:16 -0700620Status KeyValueStore::WriteEntry(string_view key,
621 span<const byte> value,
622 KeyDescriptor::State new_state,
623 KeyDescriptor* prior_descriptor,
624 size_t prior_size) {
625 const size_t entry_size = Entry::size(partition_, key, value);
626
627 // List of addresses for sectors with space for this entry.
628 // TODO: The derived class should allocate space for this address list.
629 Vector<Address, internal::kEntryRedundancy> addresses;
630
631 // Find sectors to write the entry to. This may involve garbage collecting one
632 // or more sectors.
633 for (size_t i = 0; i < redundancy_; i++) {
634 SectorDescriptor* sector;
635 TRY(GetSectorForWrite(&sector, entry_size, addresses));
636
637 DBG("Found space for entry in sector %u", SectorIndex(sector));
638 addresses.push_back(NextWritableAddress(sector));
639 }
640
641 // Write the entry at the first address that was found.
642 Entry entry = CreateEntry(addresses.front(), key, value, new_state);
643 TRY(AppendEntry(entry, key, value));
644
645 // After writing the first entry successfully, update the key descriptors.
646 // Once a single new the entry is written, the old entries are invalidated.
647 KeyDescriptor& new_descriptor =
648 UpdateKeyDescriptor(entry, key, prior_descriptor, prior_size);
649
650 // Write the additional copies of the entry, if redundancy is greater than 1.
651 for (size_t i = 1; i < addresses.size(); ++i) {
652 entry.set_address(addresses[i]);
653 TRY(AppendEntry(entry, key, value));
654 new_descriptor.addresses().push_back(addresses[i]);
655 }
Wyatt Heplerb7609542020-01-24 10:29:54 -0800656 return Status::OK;
657}
658
Wyatt Heplerab3b2492020-03-11 16:15:16 -0700659internal::KeyDescriptor& KeyValueStore::UpdateKeyDescriptor(
660 const Entry& entry,
661 string_view key,
662 KeyDescriptor* prior_descriptor,
663 size_t prior_size) {
664 // If there is no prior descriptor, create a new one.
665 if (prior_descriptor == nullptr) {
666 key_descriptors_.push_back(entry.descriptor(key));
667 return key_descriptors_.back();
David Rogersa2562b52020-03-05 15:30:05 -0800668 }
669
Wyatt Heplerab3b2492020-03-11 16:15:16 -0700670 // Remove valid bytes for the old entry and its copies, which are now stale.
671 for (Address address : prior_descriptor->addresses()) {
672 SectorFromAddress(address)->RemoveValidBytes(prior_size);
David Rogersa2562b52020-03-05 15:30:05 -0800673 }
674
Wyatt Heplerab3b2492020-03-11 16:15:16 -0700675 *prior_descriptor = entry.descriptor(prior_descriptor->hash());
676 return *prior_descriptor;
David Rogersa2562b52020-03-05 15:30:05 -0800677}
678
679// Find a sector to use for writing a new entry to. Do automatic garbage
680// collection if needed and allowed.
681//
682// OK: Sector found with needed space.
683// RESOURCE_EXHAUSTED: No sector available with the needed space.
684Status KeyValueStore::GetSectorForWrite(SectorDescriptor** sector,
685 size_t entry_size,
David Rogersc9d545e2020-03-11 17:47:43 -0700686 span<const Address> addresses_to_skip) {
687 Status result =
688 FindSectorWithSpace(sector, entry_size, kAppendEntry, addresses_to_skip);
David Rogersa2562b52020-03-05 15:30:05 -0800689
David Rogersf3884eb2020-03-08 19:21:40 -0700690 size_t gc_sector_count = 0;
David Rogersa2562b52020-03-05 15:30:05 -0800691 bool do_auto_gc = options_.gc_on_write != GargbageCollectOnWrite::kDisabled;
692
693 // Do garbage collection as needed, so long as policy allows.
694 while (result == Status::RESOURCE_EXHAUSTED && do_auto_gc) {
695 if (options_.gc_on_write == GargbageCollectOnWrite::kOneSector) {
696 // If GC config option is kOneSector clear the flag to not do any more
697 // GC after this try.
698 do_auto_gc = false;
699 }
700 // Garbage collect and then try again to find the best sector.
David Rogersc9d545e2020-03-11 17:47:43 -0700701 Status gc_status = GarbageCollectPartial(addresses_to_skip);
David Rogersa2562b52020-03-05 15:30:05 -0800702 if (!gc_status.ok()) {
703 if (gc_status == Status::NOT_FOUND) {
704 // Not enough space, and no reclaimable bytes, this KVS is full!
705 return Status::RESOURCE_EXHAUSTED;
706 }
707 return gc_status;
708 }
709
710 result = FindSectorWithSpace(
David Rogersc9d545e2020-03-11 17:47:43 -0700711 sector, entry_size, kAppendEntry, addresses_to_skip);
David Rogersf3884eb2020-03-08 19:21:40 -0700712
713 gc_sector_count++;
714 // Allow total sectors + 2 number of GC cycles so that once reclaimable
715 // bytes in all the sectors have been reclaimed can try and free up space by
716 // moving entries for keys other than the one being worked on in to sectors
717 // that have copies of the key trying to be written.
718 if (gc_sector_count > (partition_.sector_count() + 2)) {
719 ERR("Did more GC sectors than total sectors!!!!");
720 return Status::RESOURCE_EXHAUSTED;
721 }
David Rogersa2562b52020-03-05 15:30:05 -0800722 }
723
724 if (!result.ok()) {
725 WRN("Unable to find sector to write %zu B", entry_size);
726 }
727 return result;
728}
729
Wyatt Heplerab3b2492020-03-11 16:15:16 -0700730Status KeyValueStore::AppendEntry(const Entry& entry,
David Rogersa2562b52020-03-05 15:30:05 -0800731 string_view key,
732 span<const byte> value) {
Wyatt Heplerab3b2492020-03-11 16:15:16 -0700733 const StatusWithSize result = entry.Write(key, value);
David Rogersa2562b52020-03-05 15:30:05 -0800734
David Rogersa2562b52020-03-05 15:30:05 -0800735 // Remove any bytes that were written, even if the write was not successful.
736 // This is important to retain the writable space invariant on the sectors.
Wyatt Heplerab3b2492020-03-11 16:15:16 -0700737 SectorDescriptor* const sector = SectorFromAddress(entry.address());
738 sector->RemoveWritableBytes(result.size());
David Rogersa2562b52020-03-05 15:30:05 -0800739
740 if (!result.ok()) {
741 ERR("Failed to write %zu bytes at %#zx. %zu actually written",
742 entry.size(),
Wyatt Heplerab3b2492020-03-11 16:15:16 -0700743 size_t(entry.address()),
David Rogersa2562b52020-03-05 15:30:05 -0800744 result.size());
745 return result.status();
746 }
747
748 if (options_.verify_on_write) {
749 TRY(entry.VerifyChecksumInFlash());
750 }
751
Wyatt Heplerab3b2492020-03-11 16:15:16 -0700752 sector->AddValidBytes(result.size());
David Rogersa2562b52020-03-05 15:30:05 -0800753 return Status::OK;
754}
755
Wyatt Heplerab3b2492020-03-11 16:15:16 -0700756Status KeyValueStore::RelocateEntry(KeyDescriptor& key_descriptor,
757 KeyValueStore::Address& address,
758 span<const Address> addresses_to_skip) {
David Rogersa2562b52020-03-05 15:30:05 -0800759 Entry entry;
Wyatt Heplerab3b2492020-03-11 16:15:16 -0700760 TRY(Entry::Read(partition_, address, formats_, &entry));
David Rogersa2562b52020-03-05 15:30:05 -0800761
762 // Find a new sector for the entry and write it to the new location. For
763 // relocation the find should not not be a sector already containing the key
764 // but can be the always empty sector, since this is part of the GC process
765 // that will result in a new empty sector. Also find a sector that does not
766 // have reclaimable space (mostly for the full GC, where that would result in
767 // an immediate extra relocation).
768 SectorDescriptor* new_sector;
769
Wyatt Heplerab3b2492020-03-11 16:15:16 -0700770 // Avoid both this entry's sectors and sectors in addresses_to_skip.
771 //
772 // This is overly strict. addresses_to_skip is populated when there are
773 // sectors reserved for a new entry. It is safe to garbage collect into these
774 // sectors, as long as there remains room for the pending entry. These
775 // reserved sectors could also be garbage collected if they have recoverable
776 // space.
777 // TODO(hepler): Look into improving garbage collection.
778 //
779 // TODO: The derived class should allocate space for this address list.
780 Vector<Address, internal::kEntryRedundancy* 2> all_addresses_to_skip =
781 key_descriptor.addresses();
782 for (Address address : addresses_to_skip) {
783 if (!Contains(all_addresses_to_skip, address)) {
784 // TODO: DCHECK(!all_addresses_to_skip.full)
785 all_addresses_to_skip.push_back(address);
786 }
787 }
David Rogersa2562b52020-03-05 15:30:05 -0800788
Wyatt Heplerab3b2492020-03-11 16:15:16 -0700789 TRY(FindSectorWithSpace(
790 &new_sector, entry.size(), kGarbageCollect, all_addresses_to_skip));
791
792 const Address new_address = NextWritableAddress(new_sector);
793 const StatusWithSize result = entry.Copy(new_address);
794 new_sector->RemoveWritableBytes(result.size());
795 TRY(result);
David Rogersa2562b52020-03-05 15:30:05 -0800796
797 // Entry was written successfully; update the key descriptor and the sector
798 // descriptors to reflect the new entry.
Wyatt Heplerab3b2492020-03-11 16:15:16 -0700799 SectorFromAddress(address)->RemoveValidBytes(result.size());
800 new_sector->AddValidBytes(result.size());
801 address = new_address;
David Rogersa2562b52020-03-05 15:30:05 -0800802
803 return Status::OK;
804}
805
David Rogers8db5a722020-02-03 18:28:34 -0800806// Find either an existing sector with enough space that is not the sector to
807// skip, or an empty sector. Maintains the invariant that there is always at
David Rogersc8fe1f52020-02-27 14:04:08 -0800808// least 1 empty sector except during GC. On GC, skip sectors that have
809// reclaimable bytes.
Wyatt Hepler5a33d8c2020-02-06 09:32:58 -0800810Status KeyValueStore::FindSectorWithSpace(
811 SectorDescriptor** found_sector,
812 size_t size,
David Rogersc8fe1f52020-02-27 14:04:08 -0800813 FindSectorMode find_mode,
David Rogersa2562b52020-03-05 15:30:05 -0800814 span<const Address> addresses_to_skip) {
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800815 SectorDescriptor* first_empty_sector = nullptr;
David Rogersc8fe1f52020-02-27 14:04:08 -0800816 bool at_least_two_empty_sectors = (find_mode == kGarbageCollect);
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800817
David Rogersf3884eb2020-03-08 19:21:40 -0700818 // Used for the GC reclaimable bytes check
819 SectorDescriptor* non_empty_least_reclaimable_sector = nullptr;
820 const size_t sector_size_bytes = partition_.sector_size_bytes();
821
David Rogersa2562b52020-03-05 15:30:05 -0800822 // Build a vector of sectors to avoid.
Wyatt Heplerab3b2492020-03-11 16:15:16 -0700823 // TODO(hepler): Consolidate the different address / sector lists.
824 Vector<SectorDescriptor*, internal::kEntryRedundancy * 2> sectors_to_skip;
825 for (Address address : addresses_to_skip) {
David Rogersa2562b52020-03-05 15:30:05 -0800826 sectors_to_skip.push_back(SectorFromAddress(address));
827 }
828
David Rogersf3884eb2020-03-08 19:21:40 -0700829 DBG("Find sector with %zu bytes available, starting with sector %u, %s",
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800830 size,
David Rogersf3884eb2020-03-08 19:21:40 -0700831 SectorIndex(last_new_sector_),
832 (find_mode == kAppendEntry) ? "Append" : "GC");
David Rogerscd87c322020-02-27 14:04:08 -0800833 for (auto& skip_sector : sectors_to_skip) {
834 DBG(" Skip sector %u", SectorIndex(skip_sector));
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800835 }
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800836
David Rogers8ce55cd2020-02-04 19:41:48 -0800837 // The last_new_sector_ is the sector that was last selected as the "new empty
838 // sector" to write to. This last new sector is used as the starting point for
839 // the next "find a new empty sector to write to" operation. By using the last
840 // new sector as the start point we will cycle which empty sector is selected
841 // next, spreading the wear across all the empty sectors and get a wear
842 // leveling benefit, rather than putting more wear on the lower number
843 // sectors.
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800844 SectorDescriptor* sector = last_new_sector_;
David Rogers67f4b6c2020-02-06 16:17:09 -0800845
David Rogersf3884eb2020-03-08 19:21:40 -0700846 // Look for a sector to use with enough space. The search uses a 3 priority
David Rogerscd87c322020-02-27 14:04:08 -0800847 // tier process.
848 //
David Rogersc8fe1f52020-02-27 14:04:08 -0800849 // Tier 1 is sector that already has valid data. During GC only select a
850 // sector that has no reclaimable bytes. Immediately use the first matching
851 // sector that is found.
David Rogerscd87c322020-02-27 14:04:08 -0800852 //
David Rogersc8fe1f52020-02-27 14:04:08 -0800853 // Tier 2 is find sectors that are empty/erased. While scanning for a partial
854 // sector, keep track of the first empty sector and if a second empty sector
855 // was seen. If during GC then count the second empty sector as always seen.
David Rogersf3884eb2020-03-08 19:21:40 -0700856 //
857 // Tier 3 is during garbage collection, find sectors with enough space that
858 // are not empty but have recoverable bytes. Pick the sector with the least
859 // recoverable bytes to minimize the likelyhood of this sector needing to be
860 // garbage collected soon.
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800861 for (size_t j = 0; j < sectors_.size(); j++) {
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800862 sector += 1;
863 if (sector == sectors_.end()) {
864 sector = sectors_.begin();
865 }
Keir Mierle8c352dc2020-02-02 13:58:19 -0800866
David Rogersf3884eb2020-03-08 19:21:40 -0700867 // Skip sectors in the skip list.
868 if (Contains(sectors_to_skip, sector)) {
David Rogers8db5a722020-02-03 18:28:34 -0800869 continue;
870 }
871
David Rogersf3884eb2020-03-08 19:21:40 -0700872 if (!sector->Empty(sector_size_bytes) && sector->HasSpace(size)) {
873 if ((find_mode == kAppendEntry) ||
874 (sector->RecoverableBytes(sector_size_bytes) == 0)) {
875 *found_sector = sector;
876 return Status::OK;
877 } else {
878 if ((non_empty_least_reclaimable_sector == nullptr) ||
879 (non_empty_least_reclaimable_sector->RecoverableBytes(
880 sector_size_bytes) <
881 sector->RecoverableBytes(sector_size_bytes))) {
882 non_empty_least_reclaimable_sector = sector;
883 }
884 }
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800885 }
886
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800887 if (sector->Empty(sector_size_bytes)) {
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800888 if (first_empty_sector == nullptr) {
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800889 first_empty_sector = sector;
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800890 } else {
891 at_least_two_empty_sectors = true;
Wyatt Hepler2ad60672020-01-21 08:00:16 -0800892 }
Wyatt Heplerb7609542020-01-24 10:29:54 -0800893 }
894 }
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800895
David Rogersf3884eb2020-03-08 19:21:40 -0700896 // Tier 2 check: If the scan for a partial sector does not find a suitable
897 // sector, use the first empty sector that was found. Normally it is required
898 // to keep 1 empty sector after the sector found here, but that rule does not
899 // apply during GC.
900 if (first_empty_sector != nullptr && at_least_two_empty_sectors) {
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800901 DBG(" Found a usable empty sector; returning the first found (%u)",
David Rogers8ce55cd2020-02-04 19:41:48 -0800902 SectorIndex(first_empty_sector));
903 last_new_sector_ = first_empty_sector;
904 *found_sector = first_empty_sector;
905 return Status::OK;
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800906 }
David Rogers8ce55cd2020-02-04 19:41:48 -0800907
David Rogersf3884eb2020-03-08 19:21:40 -0700908 // Tier 3 check: If we got this far, use the sector with least recoverable
909 // bytes
910 if (non_empty_least_reclaimable_sector != nullptr) {
911 *found_sector = non_empty_least_reclaimable_sector;
912 DBG(" Found a usable sector %u, with %zu B recoverable, in GC",
913 SectorIndex(*found_sector),
914 (*found_sector)->RecoverableBytes(sector_size_bytes));
915 return Status::OK;
916 }
917
David Rogers8ce55cd2020-02-04 19:41:48 -0800918 // No sector was found.
David Rogers67f4b6c2020-02-06 16:17:09 -0800919 DBG(" Unable to find a usable sector");
David Rogers8ce55cd2020-02-04 19:41:48 -0800920 *found_sector = nullptr;
921 return Status::RESOURCE_EXHAUSTED;
Wyatt Heplerb7609542020-01-24 10:29:54 -0800922}
923
David Rogersf3884eb2020-03-08 19:21:40 -0700924// TODO: Break up this function in to smaller sub-chunks including create an
925// abstraction for the sector list. Look in to being able to unit test this as
926// its own thing
927KeyValueStore::SectorDescriptor* KeyValueStore::FindSectorToGarbageCollect(
928 span<const Address> addresses_to_avoid) {
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800929 const size_t sector_size_bytes = partition_.sector_size_bytes();
David Rogers2761aeb2020-01-31 17:09:00 -0800930 SectorDescriptor* sector_candidate = nullptr;
David Rogersa12786b2020-01-31 16:02:33 -0800931 size_t candidate_bytes = 0;
932
David Rogersf3884eb2020-03-08 19:21:40 -0700933 // Build a vector of sectors to avoid.
Wyatt Heplerab3b2492020-03-11 16:15:16 -0700934 // TODO(hepler): Consolidate the three address / sector lists.
David Rogersf3884eb2020-03-08 19:21:40 -0700935 Vector<const SectorDescriptor*, internal::kEntryRedundancy> sectors_to_skip;
936 for (auto& address : addresses_to_avoid) {
937 sectors_to_skip.push_back(SectorFromAddress(address));
938 DBG(" Skip sector %u", SectorIndex(SectorFromAddress(address)));
939 }
940
David Rogersa12786b2020-01-31 16:02:33 -0800941 // Step 1: Try to find a sectors with stale keys and no valid keys (no
942 // relocation needed). If any such sectors are found, use the sector with the
943 // most reclaimable bytes.
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800944 for (auto& sector : sectors_) {
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800945 if ((sector.valid_bytes() == 0) &&
David Rogersf3884eb2020-03-08 19:21:40 -0700946 (sector.RecoverableBytes(sector_size_bytes) > candidate_bytes) &&
947 !Contains(sectors_to_skip, &sector)) {
David Rogersa12786b2020-01-31 16:02:33 -0800948 sector_candidate = &sector;
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800949 candidate_bytes = sector.RecoverableBytes(sector_size_bytes);
David Rogersa12786b2020-01-31 16:02:33 -0800950 }
951 }
952
David Rogersc9d545e2020-03-11 17:47:43 -0700953 // Step 2: If step 1 yields no sectors, just find the sector with the most
David Rogersf3884eb2020-03-08 19:21:40 -0700954 // reclaimable bytes but no addresses to avoid.
955 if (sector_candidate == nullptr) {
956 for (auto& sector : sectors_) {
957 if ((sector.RecoverableBytes(sector_size_bytes) > candidate_bytes) &&
958 !Contains(sectors_to_skip, &sector)) {
959 sector_candidate = &sector;
960 candidate_bytes = sector.RecoverableBytes(sector_size_bytes);
961 }
962 }
963 }
964
David Rogersf3884eb2020-03-08 19:21:40 -0700965 // Step 3: If no sectors with reclaimable bytes, select the sector with the
966 // most free bytes. This at least will allow entries of existing keys to get
967 // spread to other sectors, including sectors that already have copies of the
968 // current key being written.
969 if (sector_candidate == nullptr) {
970 for (auto& sector : sectors_) {
971 if ((sector.valid_bytes() > candidate_bytes) &&
972 !Contains(sectors_to_skip, &sector)) {
973 sector_candidate = &sector;
974 candidate_bytes = sector.valid_bytes();
975 DBG(" Doing GC on sector with no reclaimable bytes!");
976 }
977 }
978 }
979
David Rogers5981f312020-02-13 13:33:56 -0800980 if (sector_candidate != nullptr) {
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800981 DBG("Found sector %u to Garbage Collect, %zu recoverable bytes",
David Rogers5981f312020-02-13 13:33:56 -0800982 SectorIndex(sector_candidate),
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800983 sector_candidate->RecoverableBytes(sector_size_bytes));
David Rogers5981f312020-02-13 13:33:56 -0800984 } else {
985 DBG("Unable to find sector to garbage collect!");
986 }
David Rogersa12786b2020-01-31 16:02:33 -0800987 return sector_candidate;
988}
989
David Rogerscd87c322020-02-27 14:04:08 -0800990Status KeyValueStore::GarbageCollectFull() {
991 DBG("Garbage Collect all sectors");
David Rogerscd87c322020-02-27 14:04:08 -0800992 SectorDescriptor* sector = last_new_sector_;
993
994 // TODO: look in to making an iterator method for cycling through sectors
995 // starting from last_new_sector_.
996 for (size_t j = 0; j < sectors_.size(); j++) {
997 sector += 1;
998 if (sector == sectors_.end()) {
999 sector = sectors_.begin();
1000 }
1001
1002 if (sector->RecoverableBytes(partition_.sector_size_bytes()) > 0) {
Wyatt Heplerab3b2492020-03-11 16:15:16 -07001003 TRY(GarbageCollectSector(sector, {}));
David Rogerscd87c322020-02-27 14:04:08 -08001004 }
1005 }
1006
1007 DBG("Garbage Collect all complete");
David Rogerscd87c322020-02-27 14:04:08 -08001008 return Status::OK;
1009}
1010
David Rogersc9d545e2020-03-11 17:47:43 -07001011Status KeyValueStore::GarbageCollectPartial(
1012 span<const Address> addresses_to_skip) {
1013 DBG("Garbage Collect a single sector");
1014 for (auto address : addresses_to_skip) {
1015 DBG(" Avoid address %u", unsigned(address));
1016 }
David Rogers67f4b6c2020-02-06 16:17:09 -08001017
David Rogersa12786b2020-01-31 16:02:33 -08001018 // Step 1: Find the sector to garbage collect
David Rogersc9d545e2020-03-11 17:47:43 -07001019 SectorDescriptor* sector_to_gc =
1020 FindSectorToGarbageCollect(addresses_to_skip);
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -08001021
David Rogersa12786b2020-01-31 16:02:33 -08001022 if (sector_to_gc == nullptr) {
David Rogersa2562b52020-03-05 15:30:05 -08001023 // Nothing to GC.
1024 return Status::NOT_FOUND;
David Rogersa12786b2020-01-31 16:02:33 -08001025 }
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -08001026
David Rogersc9d545e2020-03-11 17:47:43 -07001027 // Step 2: Garbage collect the selected sector.
Wyatt Heplerab3b2492020-03-11 16:15:16 -07001028 return GarbageCollectSector(sector_to_gc, addresses_to_skip);
David Rogerscd87c322020-02-27 14:04:08 -08001029}
1030
David Rogersf3884eb2020-03-08 19:21:40 -07001031Status KeyValueStore::RelocateKeyAddressesInSector(
Wyatt Heplerab3b2492020-03-11 16:15:16 -07001032 internal::SectorDescriptor& sector_to_gc,
1033 internal::KeyDescriptor& descriptor,
1034 span<const Address> addresses_to_skip) {
1035 for (FlashPartition::Address& address : descriptor.addresses()) {
1036 if (AddressInSector(sector_to_gc, address)) {
1037 DBG(" Relocate entry for Key 0x%08zx, sector %u",
1038 size_t(descriptor.hash()),
1039 SectorIndex(SectorFromAddress(address)));
1040 TRY(RelocateEntry(descriptor, address, addresses_to_skip));
David Rogersf3884eb2020-03-08 19:21:40 -07001041 }
1042 }
Wyatt Heplerab3b2492020-03-11 16:15:16 -07001043
David Rogersf3884eb2020-03-08 19:21:40 -07001044 return Status::OK;
1045};
1046
Wyatt Heplerab3b2492020-03-11 16:15:16 -07001047Status KeyValueStore::GarbageCollectSector(
1048 SectorDescriptor* sector_to_gc, span<const Address> addresses_to_skip) {
David Rogersf3884eb2020-03-08 19:21:40 -07001049 // Step 1: Move any valid entries in the GC sector to other sectors
Wyatt Heplerab3b2492020-03-11 16:15:16 -07001050 if (sector_to_gc->valid_bytes() != 0) {
1051 for (KeyDescriptor& descriptor : key_descriptors_) {
1052 TRY(RelocateKeyAddressesInSector(
1053 *sector_to_gc, descriptor, addresses_to_skip));
David Rogersf3884eb2020-03-08 19:21:40 -07001054 }
1055 }
1056
Wyatt Hepler2c7eca02020-02-18 16:01:42 -08001057 if (sector_to_gc->valid_bytes() != 0) {
David Rogers67f4b6c2020-02-06 16:17:09 -08001058 ERR(" Failed to relocate valid entries from sector being garbage "
Wyatt Hepler2c7eca02020-02-18 16:01:42 -08001059 "collected, %zu valid bytes remain",
1060 sector_to_gc->valid_bytes());
Wyatt Heplerb7609542020-01-24 10:29:54 -08001061 return Status::INTERNAL;
1062 }
1063
David Rogerscd87c322020-02-27 14:04:08 -08001064 // Step 2: Reinitialize the sector
Wyatt Hepler2c7eca02020-02-18 16:01:42 -08001065 sector_to_gc->set_writable_bytes(0);
David Rogersa12786b2020-01-31 16:02:33 -08001066 TRY(partition_.Erase(SectorBaseAddress(sector_to_gc), 1));
Wyatt Hepler2c7eca02020-02-18 16:01:42 -08001067 sector_to_gc->set_writable_bytes(partition_.sector_size_bytes());
Wyatt Heplerb7609542020-01-24 10:29:54 -08001068
David Rogerscd87c322020-02-27 14:04:08 -08001069 DBG(" Garbage Collect sector %u complete", SectorIndex(sector_to_gc));
David Rogersa12786b2020-01-31 16:02:33 -08001070 return Status::OK;
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -08001071}
1072
Wyatt Heplerbdd8e5a2020-02-20 19:27:26 -08001073KeyValueStore::Entry KeyValueStore::CreateEntry(Address address,
Wyatt Heplerab3b2492020-03-11 16:15:16 -07001074 string_view key,
Wyatt Heplerbdd8e5a2020-02-20 19:27:26 -08001075 span<const byte> value,
1076 KeyDescriptor::State state) {
Keir Mierle9e38b402020-02-21 13:06:21 -08001077 // Always bump the transaction ID when creating a new entry.
1078 //
1079 // Burning transaction IDs prevents inconsistencies between flash and memory
1080 // that which could happen if a write succeeds, but for some reason the read
1081 // and verify step fails. Here's how this would happen:
1082 //
1083 // 1. The entry is written but for some reason the flash reports failure OR
1084 // The write succeeds, but the read / verify operation fails.
1085 // 2. The transaction ID is NOT incremented, because of the failure
1086 // 3. (later) A new entry is written, re-using the transaction ID (oops)
1087 //
1088 // By always burning transaction IDs, the above problem can't happen.
1089 last_transaction_id_ += 1;
1090
Wyatt Hepler1fc11042020-02-19 17:17:51 -08001091 if (state == KeyDescriptor::kDeleted) {
Wyatt Hepler7465be32020-02-21 15:30:53 -08001092 return Entry::Tombstone(
Wyatt Hepler22d0d9f2020-03-05 14:57:11 -08001093 partition_, address, formats_.primary(), key, last_transaction_id_);
Wyatt Hepler1fc11042020-02-19 17:17:51 -08001094 }
1095 return Entry::Valid(partition_,
1096 address,
Wyatt Hepler22d0d9f2020-03-05 14:57:11 -08001097 formats_.primary(),
Wyatt Hepler1fc11042020-02-19 17:17:51 -08001098 key,
1099 value,
Keir Mierle9e38b402020-02-21 13:06:21 -08001100 last_transaction_id_);
Wyatt Heplerd2298282020-02-20 17:12:45 -08001101}
1102
Keir Mierle8c352dc2020-02-02 13:58:19 -08001103void KeyValueStore::LogDebugInfo() {
Keir Mierle8c352dc2020-02-02 13:58:19 -08001104 const size_t sector_size_bytes = partition_.sector_size_bytes();
1105 DBG("====================== KEY VALUE STORE DUMP =========================");
1106 DBG(" ");
1107 DBG("Flash partition:");
Wyatt Heplerad0a7932020-02-06 08:20:38 -08001108 DBG(" Sector count = %zu", partition_.sector_count());
Wyatt Hepler38ce30f2020-02-19 11:48:31 -08001109 DBG(" Sector max count = %zu", sectors_.max_size());
Wyatt Hepler1c329ca2020-02-07 18:07:23 -08001110 DBG(" Sectors in use = %zu", sectors_.size());
Keir Mierle8c352dc2020-02-02 13:58:19 -08001111 DBG(" Sector size = %zu", sector_size_bytes);
1112 DBG(" Total size = %zu", partition_.size_bytes());
1113 DBG(" Alignment = %zu", partition_.alignment_bytes());
1114 DBG(" ");
1115 DBG("Key descriptors:");
Wyatt Hepler1c329ca2020-02-07 18:07:23 -08001116 DBG(" Entry count = %zu", key_descriptors_.size());
Wyatt Hepler38ce30f2020-02-19 11:48:31 -08001117 DBG(" Max entry count = %zu", key_descriptors_.max_size());
Keir Mierle8c352dc2020-02-02 13:58:19 -08001118 DBG(" ");
1119 DBG(" # hash version address address (hex)");
Wyatt Hepler1c329ca2020-02-07 18:07:23 -08001120 for (size_t i = 0; i < key_descriptors_.size(); ++i) {
1121 const KeyDescriptor& kd = key_descriptors_[i];
Keir Mierle8c352dc2020-02-02 13:58:19 -08001122 DBG(" |%3zu: | %8zx |%8zu | %8zu | %8zx",
1123 i,
Wyatt Hepler1fc11042020-02-19 17:17:51 -08001124 size_t(kd.hash()),
1125 size_t(kd.transaction_id()),
1126 size_t(kd.address()),
1127 size_t(kd.address()));
Keir Mierle8c352dc2020-02-02 13:58:19 -08001128 }
1129 DBG(" ");
1130
1131 DBG("Sector descriptors:");
1132 DBG(" # tail free valid has_space");
Wyatt Hepler1c329ca2020-02-07 18:07:23 -08001133 for (size_t sector_id = 0; sector_id < sectors_.size(); ++sector_id) {
1134 const SectorDescriptor& sd = sectors_[sector_id];
Keir Mierle8c352dc2020-02-02 13:58:19 -08001135 DBG(" |%3zu: | %8zu |%8zu | %s",
1136 sector_id,
Wyatt Hepler2c7eca02020-02-18 16:01:42 -08001137 size_t(sd.writable_bytes()),
1138 sd.valid_bytes(),
1139 sd.writable_bytes() ? "YES" : "");
Keir Mierle8c352dc2020-02-02 13:58:19 -08001140 }
1141 DBG(" ");
1142
1143 // TODO: This should stop logging after some threshold.
1144 // size_t dumped_bytes = 0;
1145 DBG("Sector raw data:");
Wyatt Hepler1c329ca2020-02-07 18:07:23 -08001146 for (size_t sector_id = 0; sector_id < sectors_.size(); ++sector_id) {
Keir Mierle8c352dc2020-02-02 13:58:19 -08001147 // Read sector data. Yes, this will blow the stack on embedded.
Wyatt Hepler1c329ca2020-02-07 18:07:23 -08001148 std::array<byte, 500> raw_sector_data; // TODO!!!
Keir Mierle8c352dc2020-02-02 13:58:19 -08001149 StatusWithSize sws =
1150 partition_.Read(sector_id * sector_size_bytes, raw_sector_data);
1151 DBG("Read: %zu bytes", sws.size());
1152
1153 DBG(" base addr offs 0 1 2 3 4 5 6 7");
1154 for (size_t i = 0; i < sector_size_bytes; i += 8) {
1155 DBG(" %3zu %8zx %5zu | %02x %02x %02x %02x %02x %02x %02x %02x",
1156 sector_id,
1157 (sector_id * sector_size_bytes) + i,
1158 i,
1159 static_cast<unsigned int>(raw_sector_data[i + 0]),
1160 static_cast<unsigned int>(raw_sector_data[i + 1]),
1161 static_cast<unsigned int>(raw_sector_data[i + 2]),
1162 static_cast<unsigned int>(raw_sector_data[i + 3]),
1163 static_cast<unsigned int>(raw_sector_data[i + 4]),
1164 static_cast<unsigned int>(raw_sector_data[i + 5]),
1165 static_cast<unsigned int>(raw_sector_data[i + 6]),
1166 static_cast<unsigned int>(raw_sector_data[i + 7]));
1167
1168 // TODO: Fix exit condition.
1169 if (i > 128) {
1170 break;
1171 }
1172 }
1173 DBG(" ");
1174 }
1175
1176 DBG("////////////////////// KEY VALUE STORE DUMP END /////////////////////");
1177}
1178
David Rogerscf680ab2020-02-12 23:28:32 -08001179void KeyValueStore::LogSectors() const {
1180 DBG("Sector descriptors: count %zu", sectors_.size());
Wyatt Hepler1c329ca2020-02-07 18:07:23 -08001181 for (auto& sector : sectors_) {
Wyatt Hepler2c7eca02020-02-18 16:01:42 -08001182 DBG(" - Sector %u: valid %zu, recoverable %zu, free %zu",
David Rogers50185ad2020-02-07 00:02:46 -08001183 SectorIndex(&sector),
Wyatt Hepler2c7eca02020-02-18 16:01:42 -08001184 sector.valid_bytes(),
1185 sector.RecoverableBytes(partition_.sector_size_bytes()),
1186 sector.writable_bytes());
David Rogers50185ad2020-02-07 00:02:46 -08001187 }
1188}
1189
David Rogerscf680ab2020-02-12 23:28:32 -08001190void KeyValueStore::LogKeyDescriptor() const {
1191 DBG("Key descriptors: count %zu", key_descriptors_.size());
1192 for (auto& key : key_descriptors_) {
Wyatt Hepler1fc11042020-02-19 17:17:51 -08001193 DBG(" - Key: %s, hash %#zx, transaction ID %zu, address %#zx",
David Rogerscf680ab2020-02-12 23:28:32 -08001194 key.deleted() ? "Deleted" : "Valid",
Wyatt Hepler1fc11042020-02-19 17:17:51 -08001195 static_cast<size_t>(key.hash()),
1196 static_cast<size_t>(key.transaction_id()),
1197 static_cast<size_t>(key.address()));
David Rogerscf680ab2020-02-12 23:28:32 -08001198 }
1199}
1200
Wyatt Hepler2ad60672020-01-21 08:00:16 -08001201} // namespace pw::kvs