blob: 44dd3dc447d1fb355cff4982785421e19e561c30 [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
39} // namespace
40
Wyatt Heplerad0a7932020-02-06 08:20:38 -080041KeyValueStore::KeyValueStore(FlashPartition* partition,
Wyatt Hepler38ce30f2020-02-19 11:48:31 -080042 Vector<KeyDescriptor>& key_descriptor_list,
43 Vector<SectorDescriptor>& sector_descriptor_list,
David Rogersf3884eb2020-03-08 19:21:40 -070044 size_t redundancy,
Wyatt Hepler22d0d9f2020-03-05 14:57:11 -080045 span<const EntryFormat> formats,
Wyatt Heplerad0a7932020-02-06 08:20:38 -080046 const Options& options)
47 : partition_(*partition),
Wyatt Hepler22d0d9f2020-03-05 14:57:11 -080048 formats_(formats),
Wyatt Hepler38ce30f2020-02-19 11:48:31 -080049 key_descriptors_(key_descriptor_list),
Wyatt Heplerd2298282020-02-20 17:12:45 -080050 sectors_(sector_descriptor_list),
David Rogersf3884eb2020-03-08 19:21:40 -070051 redundancy_(redundancy),
Wyatt Heplerd2298282020-02-20 17:12:45 -080052 options_(options) {
53 Reset();
54}
Wyatt Heplerad0a7932020-02-06 08:20:38 -080055
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -080056Status KeyValueStore::Init() {
Wyatt Heplerd2298282020-02-20 17:12:45 -080057 Reset();
58
David Rogers2e9e0c82020-02-13 15:06:06 -080059 INF("Initializing key value store");
Wyatt Hepler38ce30f2020-02-19 11:48:31 -080060 if (partition_.sector_count() > sectors_.max_size()) {
David Rogers2e9e0c82020-02-13 15:06:06 -080061 ERR("KVS init failed: kMaxUsableSectors (=%zu) must be at least as "
62 "large as the number of sectors in the flash partition (=%zu)",
Wyatt Hepler38ce30f2020-02-19 11:48:31 -080063 sectors_.max_size(),
David Rogers2e9e0c82020-02-13 15:06:06 -080064 partition_.sector_count());
Wyatt Heplerad0a7932020-02-06 08:20:38 -080065 return Status::FAILED_PRECONDITION;
66 }
67
Keir Mierle8c352dc2020-02-02 13:58:19 -080068 const size_t sector_size_bytes = partition_.sector_size_bytes();
Keir Mierle8c352dc2020-02-02 13:58:19 -080069
David Rogersf0a35442020-02-04 12:16:38 -080070 if (working_buffer_.size() < sector_size_bytes) {
Wyatt Heplerce7b8df2020-02-21 10:38:39 -080071 ERR("KVS init failed: working_buffer_ (%zu B) is smaller than sector size "
72 "(%zu B)",
David Rogersf0a35442020-02-04 12:16:38 -080073 working_buffer_.size(),
74 sector_size_bytes);
75 return Status::INVALID_ARGUMENT;
76 }
77
Keir Mierle8c352dc2020-02-02 13:58:19 -080078 DBG("First pass: Read all entries from all sectors");
Wyatt Hepler2c7eca02020-02-18 16:01:42 -080079 Address sector_address = 0;
Keir Mierle8c352dc2020-02-02 13:58:19 -080080
Wyatt Heplerd2298282020-02-20 17:12:45 -080081 sectors_.assign(partition_.sector_count(),
82 SectorDescriptor(sector_size_bytes));
83
Alexei Frolovd4adf912020-02-21 13:29:15 -080084 size_t total_corrupt_bytes = 0;
85 int corrupt_entries = 0;
David Rogers91627482020-02-27 17:38:12 -080086 bool empty_sector_found = false;
Alexei Frolovd4adf912020-02-21 13:29:15 -080087
Wyatt Hepler2c7eca02020-02-18 16:01:42 -080088 for (SectorDescriptor& sector : sectors_) {
Keir Mierle8c352dc2020-02-02 13:58:19 -080089 Address entry_address = sector_address;
90
Alexei Frolovd4adf912020-02-21 13:29:15 -080091 size_t sector_corrupt_bytes = 0;
92
Wyatt Hepler2c7eca02020-02-18 16:01:42 -080093 for (int num_entries_in_sector = 0; true; num_entries_in_sector++) {
94 DBG("Load entry: sector=%" PRIx32 ", entry#=%d, address=%" PRIx32,
95 sector_address,
Keir Mierle8c352dc2020-02-02 13:58:19 -080096 num_entries_in_sector,
Wyatt Hepler2c7eca02020-02-18 16:01:42 -080097 entry_address);
Keir Mierle8c352dc2020-02-02 13:58:19 -080098
Wyatt Hepler2c7eca02020-02-18 16:01:42 -080099 if (!AddressInSector(sector, entry_address)) {
Keir Mierle8c352dc2020-02-02 13:58:19 -0800100 DBG("Fell off end of sector; moving to the next sector");
101 break;
102 }
103
104 Address next_entry_address;
105 Status status = LoadEntry(entry_address, &next_entry_address);
106 if (status == Status::NOT_FOUND) {
107 DBG("Hit un-written data in sector; moving to the next sector");
108 break;
109 }
110 if (status == Status::DATA_LOSS) {
Alexei Frolovd4adf912020-02-21 13:29:15 -0800111 // The entry could not be read, indicating data corruption within the
112 // sector. Try to scan the remainder of the sector for other entries.
David Rogersa2562b52020-03-05 15:30:05 -0800113 WRN("KVS init: data loss detected in sector %u at address %zu",
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800114 SectorIndex(&sector),
115 size_t(entry_address));
Alexei Frolovd4adf912020-02-21 13:29:15 -0800116
117 corrupt_entries++;
118
119 status = ScanForEntry(sector,
120 entry_address + Entry::kMinAlignmentBytes,
121 &next_entry_address);
122 if (status == Status::NOT_FOUND) {
123 // No further entries in this sector. Mark the remaining bytes in the
124 // sector as corrupt (since we can't reliably know the size of the
125 // corrupt entry).
126 sector_corrupt_bytes +=
127 sector_size_bytes - (entry_address - sector_address);
128 break;
129 }
130
131 if (!status.ok()) {
132 ERR("Unexpected error in KVS initialization: %s", status.str());
133 return Status::UNKNOWN;
134 }
135
136 sector_corrupt_bytes += next_entry_address - entry_address;
137 } else if (!status.ok()) {
138 ERR("Unexpected error in KVS initialization: %s", status.str());
139 return Status::UNKNOWN;
Keir Mierle8c352dc2020-02-02 13:58:19 -0800140 }
Keir Mierle8c352dc2020-02-02 13:58:19 -0800141
142 // Entry loaded successfully; so get ready to load the next one.
143 entry_address = next_entry_address;
144
145 // Update of the number of writable bytes in this sector.
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800146 sector.set_writable_bytes(sector_size_bytes -
147 (entry_address - sector_address));
Keir Mierle8c352dc2020-02-02 13:58:19 -0800148 }
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800149
Alexei Frolovd4adf912020-02-21 13:29:15 -0800150 if (sector_corrupt_bytes > 0) {
151 // If the sector contains corrupt data, prevent any further entries from
152 // being written to it by indicating that it has no space. This should
153 // also make it a decent GC candidate. Valid keys in the sector are still
154 // readable as normal.
155 sector.set_writable_bytes(0);
156
157 WRN("Sector %u contains %zuB of corrupt data",
158 SectorIndex(&sector),
159 sector_corrupt_bytes);
160 }
161
David Rogers91627482020-02-27 17:38:12 -0800162 if (sector.Empty(sector_size_bytes)) {
163 empty_sector_found = true;
164 }
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800165 sector_address += sector_size_bytes;
Alexei Frolovd4adf912020-02-21 13:29:15 -0800166 total_corrupt_bytes += sector_corrupt_bytes;
Keir Mierle8c352dc2020-02-02 13:58:19 -0800167 }
168
169 DBG("Second pass: Count valid bytes in each sector");
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800170 const KeyDescriptor* newest_key = nullptr;
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800171
Keir Mierle8c352dc2020-02-02 13:58:19 -0800172 // For every valid key, increment the valid bytes for that sector.
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800173 for (KeyDescriptor& key_descriptor : key_descriptors_) {
David Rogersf56131c2020-03-04 10:19:22 -0800174 for (auto& address : key_descriptor.addresses()) {
175 Entry entry;
David Rogersa2562b52020-03-05 15:30:05 -0800176 TRY(Entry::Read(partition_, address, formats_, &entry));
David Rogersf56131c2020-03-04 10:19:22 -0800177 SectorFromAddress(address)->AddValidBytes(entry.size());
178 }
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800179 if (key_descriptor.IsNewerThan(last_transaction_id_)) {
180 last_transaction_id_ = key_descriptor.transaction_id();
181 newest_key = &key_descriptor;
182 }
Keir Mierle8c352dc2020-02-02 13:58:19 -0800183 }
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800184
185 if (newest_key == nullptr) {
186 last_new_sector_ = sectors_.begin();
187 } else {
David Rogersf56131c2020-03-04 10:19:22 -0800188 last_new_sector_ = SectorFromAddress(newest_key->addresses().back());
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800189 }
190
David Rogers91627482020-02-27 17:38:12 -0800191 if (!empty_sector_found) {
192 // TODO: Record/report the error condition and recovery result.
193 Status gc_result = GarbageCollectPartial();
194
195 if (!gc_result.ok()) {
196 ERR("KVS init failed: Unable to maintain required free sector");
197 return Status::INTERNAL;
198 }
199 }
200
Wyatt Hepler729f28c2020-02-05 09:46:00 -0800201 initialized_ = true;
David Rogers2e9e0c82020-02-13 15:06:06 -0800202
Armando Montanez5464d5f2020-02-20 10:12:20 -0800203 INF("KeyValueStore init complete: active keys %zu, deleted keys %zu, sectors "
David Rogers2e9e0c82020-02-13 15:06:06 -0800204 "%zu, logical sector size %zu bytes",
205 size(),
206 (key_descriptors_.size() - size()),
207 sectors_.size(),
208 partition_.sector_size_bytes());
209
Alexei Frolovd4adf912020-02-21 13:29:15 -0800210 if (total_corrupt_bytes > 0) {
211 WRN("Found %zu corrupt bytes and %d corrupt entries during init process; "
212 "some keys may be missing",
213 total_corrupt_bytes,
214 corrupt_entries);
215 return Status::DATA_LOSS;
216 }
217
Keir Mierle8c352dc2020-02-02 13:58:19 -0800218 return Status::OK;
219}
220
Alexei Frolov9e235832020-02-24 12:44:45 -0800221KeyValueStore::StorageStats KeyValueStore::GetStorageStats() const {
222 StorageStats stats{0, 0, 0};
223 const size_t sector_size = partition_.sector_size_bytes();
224 bool found_empty_sector = false;
225
226 for (const SectorDescriptor& sector : sectors_) {
227 stats.in_use_bytes += sector.valid_bytes();
228 stats.reclaimable_bytes += sector.RecoverableBytes(sector_size);
229
230 if (!found_empty_sector && sector.Empty(sector_size)) {
231 // The KVS tries to always keep an empty sector for GC, so don't count
232 // the first empty sector seen as writable space. However, a free sector
233 // cannot always be assumed to exist; if a GC operation fails, all sectors
234 // may be partially written, in which case the space reported might be
235 // inaccurate.
236 found_empty_sector = true;
237 continue;
238 }
239
240 stats.writable_bytes += sector.writable_bytes();
241 }
242
243 return stats;
244}
245
Keir Mierle8c352dc2020-02-02 13:58:19 -0800246Status KeyValueStore::LoadEntry(Address entry_address,
247 Address* next_entry_address) {
Wyatt Heplere541e072020-02-14 09:10:53 -0800248 Entry entry;
Wyatt Hepler22d0d9f2020-03-05 14:57:11 -0800249 TRY(Entry::Read(partition_, entry_address, formats_, &entry));
Keir Mierle8c352dc2020-02-02 13:58:19 -0800250
251 // Read the key from flash & validate the entry (which reads the value).
Wyatt Heplera00d1ef2020-02-14 14:31:26 -0800252 Entry::KeyBuffer key_buffer;
Wyatt Heplere541e072020-02-14 09:10:53 -0800253 TRY_ASSIGN(size_t key_length, entry.ReadKey(key_buffer));
254 const string_view key(key_buffer.data(), key_length);
Wyatt Heplerbab0e202020-02-04 07:40:08 -0800255
Wyatt Hepler22d0d9f2020-03-05 14:57:11 -0800256 TRY(entry.VerifyChecksumInFlash());
David Rogersf56131c2020-03-04 10:19:22 -0800257
258 // A valid entry was found, so update the next entry address before doing any
259 // of the checks that happen in AppendNewOrOverwriteStaleExistingDescriptor().
260 *next_entry_address = entry.next_address();
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800261 TRY(AppendNewOrOverwriteStaleExistingDescriptor(entry.descriptor(key)));
Keir Mierle8c352dc2020-02-02 13:58:19 -0800262
Keir Mierle8c352dc2020-02-02 13:58:19 -0800263 return Status::OK;
264}
265
Alexei Frolovd4adf912020-02-21 13:29:15 -0800266// Scans flash memory within a sector to find a KVS entry magic.
Alexei Frolovd4adf912020-02-21 13:29:15 -0800267Status KeyValueStore::ScanForEntry(const SectorDescriptor& sector,
268 Address start_address,
269 Address* next_entry_address) {
270 DBG("Scanning sector %u for entries starting from address %zx",
271 SectorIndex(&sector),
272 size_t(start_address));
273
274 // Entries must start at addresses which are aligned on a multiple of
275 // Entry::kMinAlignmentBytes. However, that multiple can vary between entries.
276 // When scanning, we don't have an entry to tell us what the current alignment
277 // is, so the minimum alignment is used to be exhaustive.
278 for (Address address = AlignUp(start_address, Entry::kMinAlignmentBytes);
279 AddressInSector(sector, address);
280 address += Entry::kMinAlignmentBytes) {
Alexei Frolovd4adf912020-02-21 13:29:15 -0800281 uint32_t magic;
282 TRY(partition_.Read(address, as_writable_bytes(span(&magic, 1))));
Wyatt Hepler22d0d9f2020-03-05 14:57:11 -0800283 if (formats_.KnownMagic(magic)) {
Alexei Frolovd4adf912020-02-21 13:29:15 -0800284 DBG("Found entry magic at address %zx", size_t(address));
285 *next_entry_address = address;
286 return Status::OK;
287 }
288 }
289
290 return Status::NOT_FOUND;
291}
292
Keir Mierle8c352dc2020-02-02 13:58:19 -0800293// TODO: This method is the trigger of the O(valid_entries * all_entries) time
294// complexity for reading. At some cost to memory, this could be optimized by
295// using a hash table instead of scanning, but in practice this should be fine
296// for a small number of keys
297Status KeyValueStore::AppendNewOrOverwriteStaleExistingDescriptor(
298 const KeyDescriptor& key_descriptor) {
299 // With the new key descriptor, either add it to the descriptor table or
300 // overwrite an existing entry with an older version of the key.
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800301 KeyDescriptor* existing_descriptor = FindDescriptor(key_descriptor.hash());
Keir Mierle8c352dc2020-02-02 13:58:19 -0800302
Wyatt Hepler5406a672020-02-18 15:42:38 -0800303 // Write a new entry.
304 if (existing_descriptor == nullptr) {
305 if (key_descriptors_.full()) {
306 return Status::RESOURCE_EXHAUSTED;
307 }
308 key_descriptors_.push_back(key_descriptor);
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800309 } else if (key_descriptor.IsNewerThan(
310 existing_descriptor->transaction_id())) {
Wyatt Hepler5406a672020-02-18 15:42:38 -0800311 // Existing entry is old; replace the existing entry with the new one.
312 *existing_descriptor = key_descriptor;
David Rogersf56131c2020-03-04 10:19:22 -0800313 } else if (existing_descriptor->transaction_id() ==
314 key_descriptor.transaction_id()) {
315 // If the entries have a duplicate transaction ID, add the new (redundant)
316 // entry to the existing descriptor.
317 if (existing_descriptor->hash() != key_descriptor.hash()) {
David Rogersf3884eb2020-03-08 19:21:40 -0700318 ERR("Duplicate entry for key 0x%08" PRIx32 " with transaction ID %" PRIu32
David Rogersf56131c2020-03-04 10:19:22 -0800319 " has non-matching hash",
320 key_descriptor.hash(),
321 key_descriptor.transaction_id());
Wyatt Hepler5406a672020-02-18 15:42:38 -0800322 return Status::DATA_LOSS;
323 }
David Rogersf56131c2020-03-04 10:19:22 -0800324
325 // Verify that this entry is not in the same sector as an existing copy of
326 // this same key.
327 for (auto address : existing_descriptor->addresses()) {
328 if (SectorFromAddress(address) ==
329 SectorFromAddress(key_descriptor.address())) {
330 DBG("Multiple Redundant entries in same sector %u",
331 SectorIndex(SectorFromAddress(address)));
332 return Status::DATA_LOSS;
333 }
334 }
335 existing_descriptor->addresses().push_back(key_descriptor.address());
336 } else {
Wyatt Hepler5406a672020-02-18 15:42:38 -0800337 DBG("Found stale entry when appending; ignoring");
Keir Mierle8c352dc2020-02-02 13:58:19 -0800338 }
Keir Mierle8c352dc2020-02-02 13:58:19 -0800339 return Status::OK;
340}
341
Keir Mierle8c352dc2020-02-02 13:58:19 -0800342KeyValueStore::KeyDescriptor* KeyValueStore::FindDescriptor(uint32_t hash) {
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800343 for (KeyDescriptor& key_descriptor : key_descriptors_) {
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800344 if (key_descriptor.hash() == hash) {
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800345 return &key_descriptor;
Keir Mierle8c352dc2020-02-02 13:58:19 -0800346 }
347 }
348 return nullptr;
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800349}
350
351StatusWithSize KeyValueStore::Get(string_view key,
Wyatt Hepler5f6efc02020-02-18 16:54:31 -0800352 span<byte> value_buffer,
353 size_t offset_bytes) const {
Wyatt Hepler50f70772020-02-13 11:25:10 -0800354 TRY_WITH_SIZE(CheckOperation(key));
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800355
David Rogers2761aeb2020-01-31 17:09:00 -0800356 const KeyDescriptor* key_descriptor;
Wyatt Hepler2d401692020-02-13 16:01:23 -0800357 TRY_WITH_SIZE(FindExistingKeyDescriptor(key, &key_descriptor));
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800358
Wyatt Heplerfac81132020-02-27 17:26:33 -0800359 return Get(key, *key_descriptor, value_buffer, offset_bytes);
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800360}
361
Wyatt Heplerfac81132020-02-27 17:26:33 -0800362Status KeyValueStore::PutBytes(string_view key, span<const byte> value) {
Keir Mierle8c352dc2020-02-02 13:58:19 -0800363 DBG("Writing key/value; key length=%zu, value length=%zu",
364 key.size(),
365 value.size());
Wyatt Hepler729f28c2020-02-05 09:46:00 -0800366
367 TRY(CheckOperation(key));
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800368
Wyatt Hepler5406a672020-02-18 15:42:38 -0800369 if (Entry::size(partition_, key, value) > partition_.sector_size_bytes()) {
370 DBG("%zu B value with %zu B key cannot fit in one sector",
371 value.size(),
372 key.size());
373 return Status::INVALID_ARGUMENT;
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800374 }
375
David Rogers2761aeb2020-01-31 17:09:00 -0800376 KeyDescriptor* key_descriptor;
Wyatt Hepler2d401692020-02-13 16:01:23 -0800377 Status status = FindKeyDescriptor(key, &key_descriptor);
378
379 if (status.ok()) {
David Rogersf56131c2020-03-04 10:19:22 -0800380 // TODO: figure out logging how to support multiple addresses.
David Rogersf3884eb2020-03-08 19:21:40 -0700381 DBG("Overwriting entry for key 0x%08" PRIx32 " in %u sectors including %u",
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800382 key_descriptor->hash(),
David Rogersf56131c2020-03-04 10:19:22 -0800383 unsigned(key_descriptor->addresses().size()),
384 SectorIndex(SectorFromAddress(key_descriptor->address())));
Wyatt Hepler5a33d8c2020-02-06 09:32:58 -0800385 return WriteEntryForExistingKey(
386 key_descriptor, KeyDescriptor::kValid, key, value);
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800387 }
David Rogers2761aeb2020-01-31 17:09:00 -0800388
Wyatt Hepler2d401692020-02-13 16:01:23 -0800389 if (status == Status::NOT_FOUND) {
390 return WriteEntryForNewKey(key, value);
391 }
392
393 return status;
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800394}
395
396Status KeyValueStore::Delete(string_view key) {
Wyatt Hepler729f28c2020-02-05 09:46:00 -0800397 TRY(CheckOperation(key));
398
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800399 KeyDescriptor* key_descriptor;
Wyatt Hepler2d401692020-02-13 16:01:23 -0800400 TRY(FindExistingKeyDescriptor(key, &key_descriptor));
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800401
David Rogersf56131c2020-03-04 10:19:22 -0800402 // TODO: figure out logging how to support multiple addresses.
David Rogersf3884eb2020-03-08 19:21:40 -0700403 DBG("Writing tombstone for key 0x%08" PRIx32 " in %u sectors including %u",
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800404 key_descriptor->hash(),
David Rogersf56131c2020-03-04 10:19:22 -0800405 unsigned(key_descriptor->addresses().size()),
406 SectorIndex(SectorFromAddress(key_descriptor->address())));
Wyatt Hepler5a33d8c2020-02-06 09:32:58 -0800407 return WriteEntryForExistingKey(
408 key_descriptor, KeyDescriptor::kDeleted, key, {});
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800409}
410
Wyatt Hepler08d37d82020-02-27 15:45:37 -0800411void KeyValueStore::Item::ReadKey() {
412 key_buffer_.fill('\0');
413
414 Entry entry;
David Rogersf3884eb2020-03-08 19:21:40 -0700415 // TODO: add support for using one of the redundant entries if reading the
416 // first copy fails.
Wyatt Hepler22d0d9f2020-03-05 14:57:11 -0800417 if (Entry::Read(
418 kvs_.partition_, descriptor_->address(), kvs_.formats_, &entry)
419 .ok()) {
Wyatt Hepler08d37d82020-02-27 15:45:37 -0800420 entry.ReadKey(key_buffer_);
421 }
422}
423
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800424KeyValueStore::iterator& KeyValueStore::iterator::operator++() {
425 // Skip to the next entry that is valid (not deleted).
Wyatt Hepler08d37d82020-02-27 15:45:37 -0800426 while (++item_.descriptor_ != item_.kvs_.key_descriptors_.end() &&
427 item_.descriptor_->deleted()) {
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800428 }
429 return *this;
430}
431
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800432KeyValueStore::iterator KeyValueStore::begin() const {
Wyatt Hepler08d37d82020-02-27 15:45:37 -0800433 const KeyDescriptor* descriptor = key_descriptors_.begin();
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800434 // Skip over any deleted entries at the start of the descriptor list.
Wyatt Hepler08d37d82020-02-27 15:45:37 -0800435 while (descriptor != key_descriptors_.end() && descriptor->deleted()) {
436 ++descriptor;
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800437 }
Wyatt Hepler08d37d82020-02-27 15:45:37 -0800438 return iterator(*this, descriptor);
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800439}
440
441// TODO(hepler): The valid entry count could be tracked in the KVS to avoid the
442// need for this for-loop.
443size_t KeyValueStore::size() const {
444 size_t valid_entries = 0;
445
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800446 for (const KeyDescriptor& key_descriptor : key_descriptors_) {
447 if (!key_descriptor.deleted()) {
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800448 valid_entries += 1;
449 }
450 }
451
452 return valid_entries;
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800453}
454
Wyatt Heplered163b02020-02-03 17:49:32 -0800455StatusWithSize KeyValueStore::ValueSize(std::string_view key) const {
Wyatt Hepler50f70772020-02-13 11:25:10 -0800456 TRY_WITH_SIZE(CheckOperation(key));
Wyatt Heplered163b02020-02-03 17:49:32 -0800457
458 const KeyDescriptor* key_descriptor;
Wyatt Hepler2d401692020-02-13 16:01:23 -0800459 TRY_WITH_SIZE(FindExistingKeyDescriptor(key, &key_descriptor));
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800460
Wyatt Heplerfac81132020-02-27 17:26:33 -0800461 return ValueSize(*key_descriptor);
462}
Wyatt Heplered163b02020-02-03 17:49:32 -0800463
Wyatt Heplerfac81132020-02-27 17:26:33 -0800464StatusWithSize KeyValueStore::Get(string_view key,
465 const KeyDescriptor& descriptor,
466 span<std::byte> value_buffer,
467 size_t offset_bytes) const {
468 Entry entry;
David Rogersa2562b52020-03-05 15:30:05 -0800469 // TODO: add support for using one of the redundant entries if reading the
470 // first copy fails.
Wyatt Hepler22d0d9f2020-03-05 14:57:11 -0800471 TRY_WITH_SIZE(
472 Entry::Read(partition_, descriptor.address(), formats_, &entry));
Wyatt Heplerfac81132020-02-27 17:26:33 -0800473
474 StatusWithSize result = entry.ReadValue(value_buffer, offset_bytes);
475 if (result.ok() && options_.verify_on_read && offset_bytes == 0u) {
Wyatt Hepler22d0d9f2020-03-05 14:57:11 -0800476 Status verify_result =
477 entry.VerifyChecksum(key, value_buffer.first(result.size()));
Wyatt Heplerfac81132020-02-27 17:26:33 -0800478 if (!verify_result.ok()) {
479 std::memset(value_buffer.data(), 0, result.size());
480 return StatusWithSize(verify_result, 0);
481 }
482
483 return StatusWithSize(verify_result, result.size());
484 }
485 return result;
Wyatt Heplered163b02020-02-03 17:49:32 -0800486}
487
Wyatt Hepler6e3a83b2020-02-04 07:36:45 -0800488Status KeyValueStore::FixedSizeGet(std::string_view key,
Wyatt Heplerfac81132020-02-27 17:26:33 -0800489 void* value,
490 size_t size_bytes) const {
491 TRY(CheckOperation(key));
492
493 const KeyDescriptor* descriptor;
494 TRY(FindExistingKeyDescriptor(key, &descriptor));
495
496 return FixedSizeGet(key, *descriptor, value, size_bytes);
497}
498
499Status KeyValueStore::FixedSizeGet(std::string_view key,
500 const KeyDescriptor& descriptor,
501 void* value,
Wyatt Hepler6e3a83b2020-02-04 07:36:45 -0800502 size_t size_bytes) const {
503 // Ensure that the size of the stored value matches the size of the type.
504 // Otherwise, report error. This check avoids potential memory corruption.
Wyatt Heplerfac81132020-02-27 17:26:33 -0800505 TRY_ASSIGN(const size_t actual_size, ValueSize(descriptor));
506
507 if (actual_size != size_bytes) {
508 DBG("Requested %zu B read, but value is %zu B", size_bytes, actual_size);
Wyatt Hepler6e3a83b2020-02-04 07:36:45 -0800509 return Status::INVALID_ARGUMENT;
Wyatt Heplerbab0e202020-02-04 07:40:08 -0800510 }
Wyatt Heplerfac81132020-02-27 17:26:33 -0800511
512 StatusWithSize result =
513 Get(key, descriptor, span(static_cast<byte*>(value), size_bytes), 0);
514
515 return result.status();
516}
517
518StatusWithSize KeyValueStore::ValueSize(const KeyDescriptor& descriptor) const {
519 Entry entry;
David Rogersf3884eb2020-03-08 19:21:40 -0700520 // TODO: add support for using one of the redundant entries if reading the
521 // first copy fails.
Wyatt Hepler22d0d9f2020-03-05 14:57:11 -0800522 TRY_WITH_SIZE(
523 Entry::Read(partition_, descriptor.address(), formats_, &entry));
Wyatt Heplerfac81132020-02-27 17:26:33 -0800524
525 return StatusWithSize(entry.value_size());
Keir Mierle8c352dc2020-02-02 13:58:19 -0800526}
527
Wyatt Hepler729f28c2020-02-05 09:46:00 -0800528Status KeyValueStore::CheckOperation(string_view key) const {
Wyatt Hepleracaacf92020-01-24 10:58:30 -0800529 if (InvalidKey(key)) {
Wyatt Heplerb7609542020-01-24 10:29:54 -0800530 return Status::INVALID_ARGUMENT;
531 }
Wyatt Heplerd2298282020-02-20 17:12:45 -0800532 if (!initialized()) {
Wyatt Heplerb7609542020-01-24 10:29:54 -0800533 return Status::FAILED_PRECONDITION;
534 }
Wyatt Heplerb7609542020-01-24 10:29:54 -0800535 return Status::OK;
536}
537
Wyatt Hepler2d401692020-02-13 16:01:23 -0800538// Searches for a KeyDescriptor that matches this key and sets *result to point
539// to it if one is found.
540//
541// OK: there is a matching descriptor and *result is set
542// NOT_FOUND: there is no descriptor that matches this key, but this key
543// has a unique hash (and could potentially be added to the KVS)
544// ALREADY_EXISTS: there is no descriptor that matches this key, but the
545// key's hash collides with the hash for an existing descriptor
546//
David Rogers2761aeb2020-01-31 17:09:00 -0800547Status KeyValueStore::FindKeyDescriptor(string_view key,
548 const KeyDescriptor** result) const {
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800549 const uint32_t hash = internal::Hash(key);
Wyatt Heplera00d1ef2020-02-14 14:31:26 -0800550 Entry::KeyBuffer key_buffer;
Wyatt Heplerb7609542020-01-24 10:29:54 -0800551
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800552 for (auto& descriptor : key_descriptors_) {
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800553 if (descriptor.hash() == hash) {
David Rogersf3884eb2020-03-08 19:21:40 -0700554 // TODO: add support for using one of the redundant entries if reading the
555 // first copy fails.
Wyatt Heplere541e072020-02-14 09:10:53 -0800556 TRY(Entry::ReadKey(
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800557 partition_, descriptor.address(), key.size(), key_buffer.data()));
Wyatt Heplerb7609542020-01-24 10:29:54 -0800558
Wyatt Heplere541e072020-02-14 09:10:53 -0800559 if (key == string_view(key_buffer.data(), key.size())) {
Wyatt Hepler5a33d8c2020-02-06 09:32:58 -0800560 DBG("Found match for key hash 0x%08" PRIx32, hash);
David Rogers2761aeb2020-01-31 17:09:00 -0800561 *result = &descriptor;
Wyatt Heplerb7609542020-01-24 10:29:54 -0800562 return Status::OK;
Wyatt Hepler2d401692020-02-13 16:01:23 -0800563 } else {
564 WRN("Found key hash collision for 0x%08" PRIx32, hash);
565 return Status::ALREADY_EXISTS;
Wyatt Heplerb7609542020-01-24 10:29:54 -0800566 }
Wyatt Heplerb7609542020-01-24 10:29:54 -0800567 }
568 }
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800569 return Status::NOT_FOUND;
570}
571
Wyatt Hepler2d401692020-02-13 16:01:23 -0800572// Searches for a KeyDescriptor that matches this key and sets *result to point
573// to it if one is found.
574//
575// OK: there is a matching descriptor and *result is set
576// NOT_FOUND: there is no descriptor that matches this key
577//
578Status KeyValueStore::FindExistingKeyDescriptor(
579 string_view key, const KeyDescriptor** result) const {
580 Status status = FindKeyDescriptor(key, result);
581
582 // If the key's hash collides with an existing key or if the key is deleted,
583 // treat it as if it is not in the KVS.
584 if (status == Status::ALREADY_EXISTS ||
585 (status.ok() && (*result)->deleted())) {
586 return Status::NOT_FOUND;
587 }
588 return status;
589}
590
David Rogers2761aeb2020-01-31 17:09:00 -0800591Status KeyValueStore::WriteEntryForExistingKey(KeyDescriptor* key_descriptor,
Wyatt Hepler5a33d8c2020-02-06 09:32:58 -0800592 KeyDescriptor::State new_state,
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800593 string_view key,
594 span<const byte> value) {
Wyatt Hepler30a52152020-02-12 11:26:05 -0800595 Entry original_entry;
David Rogersa2562b52020-03-05 15:30:05 -0800596 // TODO: add support for using one of the redundant entries if reading the
597 // first copy fails.
Wyatt Hepler22d0d9f2020-03-05 14:57:11 -0800598 TRY(Entry::Read(
599 partition_, key_descriptor->address(), formats_, &original_entry));
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800600
David Rogersa2562b52020-03-05 15:30:05 -0800601 // Create a new temporary key descriptor to use while writing the new
602 // key-value out to flash. Once the writing is done, update the main
603 // descriptor for this key with the new information.
604 KeyDescriptor new_key_descriptor(key);
605 TRY(WriteEntry(&new_key_descriptor, key, value, new_state));
David Rogers3464d0a2020-02-07 11:45:46 -0800606
David Rogersa2562b52020-03-05 15:30:05 -0800607 // Update the main descriptor for the new key version.
David Rogersf56131c2020-03-04 10:19:22 -0800608 KeyDescriptor old_key_descriptor = *key_descriptor;
David Rogersa2562b52020-03-05 15:30:05 -0800609 *key_descriptor = new_key_descriptor;
David Rogers3464d0a2020-02-07 11:45:46 -0800610
David Rogersa2562b52020-03-05 15:30:05 -0800611 // Remove all the valid bytes for the old key version, which are now stale.
David Rogersf56131c2020-03-04 10:19:22 -0800612 for (auto& address : old_key_descriptor.addresses()) {
613 SectorFromAddress(address)->RemoveValidBytes(original_entry.size());
614 }
615
Wyatt Hepler5a33d8c2020-02-06 09:32:58 -0800616 return Status::OK;
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800617}
618
619Status KeyValueStore::WriteEntryForNewKey(string_view key,
620 span<const byte> value) {
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800621 if (key_descriptors_.full()) {
Keir Mierle8c352dc2020-02-02 13:58:19 -0800622 WRN("KVS full: trying to store a new entry, but can't. Have %zu entries",
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800623 key_descriptors_.size());
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800624 return Status::RESOURCE_EXHAUSTED;
625 }
626
David Rogersa2562b52020-03-05 15:30:05 -0800627 // Create the KeyDescriptor that will be added to the list and write it to
628 // flash.
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800629 KeyDescriptor key_descriptor(key);
David Rogersa2562b52020-03-05 15:30:05 -0800630 TRY(WriteEntry(&key_descriptor, key, value, KeyDescriptor::kValid));
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800631
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800632 // Only add the entry when we are certain the write succeeded.
633 key_descriptors_.push_back(key_descriptor);
Wyatt Heplerb7609542020-01-24 10:29:54 -0800634 return Status::OK;
635}
636
David Rogersa2562b52020-03-05 15:30:05 -0800637Status KeyValueStore::WriteEntry(KeyDescriptor* key_descriptor,
638 string_view key,
639 span<const byte> value,
640 KeyDescriptor::State new_state) {
641 size_t entry_size = Entry::size(partition_, key, value);
642
643 Entry entry = CreateEntry(0, key, value, new_state);
644 *key_descriptor = entry.descriptor(key);
645 key_descriptor->addresses().clear();
646
647 // For number of redundany entries to be written, do the following:
648 // - Find a sector to write an individual entry to. This optionally will
649 // include garbage collecting one or more sectors if needed.
650 // - Write the entry to the sector.
651 // - Repeat for redundancy number of total entries.
David Rogersf3884eb2020-03-08 19:21:40 -0700652 for (size_t i = 0; i < redundancy_; i++) {
David Rogersa2562b52020-03-05 15:30:05 -0800653 SectorDescriptor* sector;
654 TRY(GetSectorForWrite(&sector, entry_size, key_descriptor));
655
656 DBG("Writing entry %zu; found sector: %u", i, SectorIndex(sector));
657 const Address write_address = NextWritableAddress(sector);
658 TRY(AppendEntry(write_address, entry, key, value));
659
660 // Entry copy was written successfully; update the key descriptor to reflect
661 // the new entry.
662 key_descriptor->addresses().push_back(write_address);
663 }
664
665 // Once all the entries are written, add valid bytes to each of the sectors
666 // that entries were written to.
667 for (auto new_address : key_descriptor->addresses()) {
668 SectorFromAddress(new_address)->AddValidBytes(entry.size());
669 }
670
671 return Status::OK;
672}
673
674// Find a sector to use for writing a new entry to. Do automatic garbage
675// collection if needed and allowed.
676//
677// OK: Sector found with needed space.
678// RESOURCE_EXHAUSTED: No sector available with the needed space.
679Status KeyValueStore::GetSectorForWrite(SectorDescriptor** sector,
680 size_t entry_size,
681 KeyDescriptor* key_descriptor) {
682 Status result = FindSectorWithSpace(
683 sector, entry_size, kAppendEntry, key_descriptor->addresses());
684
David Rogersf3884eb2020-03-08 19:21:40 -0700685 size_t gc_sector_count = 0;
David Rogersa2562b52020-03-05 15:30:05 -0800686 bool do_auto_gc = options_.gc_on_write != GargbageCollectOnWrite::kDisabled;
687
688 // Do garbage collection as needed, so long as policy allows.
689 while (result == Status::RESOURCE_EXHAUSTED && do_auto_gc) {
690 if (options_.gc_on_write == GargbageCollectOnWrite::kOneSector) {
691 // If GC config option is kOneSector clear the flag to not do any more
692 // GC after this try.
693 do_auto_gc = false;
694 }
695 // Garbage collect and then try again to find the best sector.
David Rogersf3884eb2020-03-08 19:21:40 -0700696 Status gc_status = GarbageCollectPartial(key_descriptor);
David Rogersa2562b52020-03-05 15:30:05 -0800697 if (!gc_status.ok()) {
698 if (gc_status == Status::NOT_FOUND) {
699 // Not enough space, and no reclaimable bytes, this KVS is full!
700 return Status::RESOURCE_EXHAUSTED;
701 }
702 return gc_status;
703 }
704
705 result = FindSectorWithSpace(
706 sector, entry_size, kAppendEntry, key_descriptor->addresses());
David Rogersf3884eb2020-03-08 19:21:40 -0700707
708 gc_sector_count++;
709 // Allow total sectors + 2 number of GC cycles so that once reclaimable
710 // bytes in all the sectors have been reclaimed can try and free up space by
711 // moving entries for keys other than the one being worked on in to sectors
712 // that have copies of the key trying to be written.
713 if (gc_sector_count > (partition_.sector_count() + 2)) {
714 ERR("Did more GC sectors than total sectors!!!!");
715 return Status::RESOURCE_EXHAUSTED;
716 }
David Rogersa2562b52020-03-05 15:30:05 -0800717 }
718
719 if (!result.ok()) {
720 WRN("Unable to find sector to write %zu B", entry_size);
721 }
722 return result;
723}
724
725Status KeyValueStore::AppendEntry(Address write_address,
726 Entry& entry,
727 string_view key,
728 span<const byte> value) {
729 entry.UpdateAddress(write_address);
730
731 StatusWithSize result = entry.Write(key, value);
732 // Remove any bytes that were written, even if the write was not successful.
733 // This is important to retain the writable space invariant on the sectors.
734 SectorFromAddress(write_address)->RemoveWritableBytes(result.size());
735
736 if (!result.ok()) {
737 ERR("Failed to write %zu bytes at %#zx. %zu actually written",
738 entry.size(),
739 size_t(write_address),
740 result.size());
741 return result.status();
742 }
743
744 if (options_.verify_on_write) {
745 TRY(entry.VerifyChecksumInFlash());
746 }
747
748 return Status::OK;
749}
750
David Rogersf3884eb2020-03-08 19:21:40 -0700751Status KeyValueStore::RelocateEntry(KeyDescriptor* key_descriptor,
David Rogersa2562b52020-03-05 15:30:05 -0800752 KeyValueStore::Address old_address) {
753 Entry entry;
754 TRY(Entry::Read(partition_, old_address, formats_, &entry));
755
756 // Find a new sector for the entry and write it to the new location. For
757 // relocation the find should not not be a sector already containing the key
758 // but can be the always empty sector, since this is part of the GC process
759 // that will result in a new empty sector. Also find a sector that does not
760 // have reclaimable space (mostly for the full GC, where that would result in
761 // an immediate extra relocation).
762 SectorDescriptor* new_sector;
763
764 TRY(FindSectorWithSpace(
David Rogersf3884eb2020-03-08 19:21:40 -0700765 &new_sector, entry.size(), kGarbageCollect, key_descriptor->addresses()));
David Rogersa2562b52020-03-05 15:30:05 -0800766 const Address new_address = NextWritableAddress(new_sector);
767 TRY(MoveEntry(new_address, entry));
768
769 // TODO: Perhaps add check that the entry matches the key descriptor (key
770 // hash, ID, checksum).
771
772 // Entry was written successfully; update the key descriptor and the sector
773 // descriptors to reflect the new entry.
David Rogersf3884eb2020-03-08 19:21:40 -0700774 TRY(key_descriptor->UpdateAddress(old_address, new_address));
775
776 if ((key_descriptor >= key_descriptors_.begin()) &&
777 (key_descriptor < key_descriptors_.end())) {
778 // If the key_descriptor is in the main key_descriptors_ list, it has been
779 // accounted for in valid bytes, so only do valid byte updates for those
780 // descriptors.
781 new_sector->AddValidBytes(entry.size());
782 SectorFromAddress(old_address)->RemoveValidBytes(entry.size());
783 }
David Rogersa2562b52020-03-05 15:30:05 -0800784
785 return Status::OK;
786}
787
788Status KeyValueStore::MoveEntry(Address new_address, Entry& entry) {
789 // Step 1: Read the old entry.
David Rogersf0a35442020-02-04 12:16:38 -0800790 struct TempEntry {
Wyatt Heplere541e072020-02-14 09:10:53 -0800791 Entry::KeyBuffer key;
Wyatt Heplerce7b8df2020-02-21 10:38:39 -0800792 std::array<byte, sizeof(working_buffer_) - sizeof(key)> value;
David Rogersf0a35442020-02-04 12:16:38 -0800793 };
Wyatt Heplerce7b8df2020-02-21 10:38:39 -0800794 auto [key_buffer, value_buffer] =
795 *std::launder(reinterpret_cast<TempEntry*>(working_buffer_.data()));
David Rogersf0a35442020-02-04 12:16:38 -0800796
Wyatt Heplere541e072020-02-14 09:10:53 -0800797 // Read the entry to be relocated. Store the entry in a local variable and
David Rogersf0a35442020-02-04 12:16:38 -0800798 // store the key and value in the TempEntry stored in the static allocated
799 // working_buffer_.
Wyatt Heplerce7b8df2020-02-21 10:38:39 -0800800 TRY_ASSIGN(size_t key_length, entry.ReadKey(key_buffer));
801 string_view key = string_view(key_buffer.data(), key_length);
802
803 StatusWithSize result = entry.ReadValue(value_buffer);
804 if (!result.ok()) {
David Rogersf0a35442020-02-04 12:16:38 -0800805 return Status::INTERNAL;
806 }
807
Wyatt Heplerce7b8df2020-02-21 10:38:39 -0800808 const span value = span(value_buffer.data(), result.size());
Wyatt Hepler22d0d9f2020-03-05 14:57:11 -0800809 TRY(entry.VerifyChecksum(key, value));
David Rogersf0a35442020-02-04 12:16:38 -0800810
David Rogersf3884eb2020-03-08 19:21:40 -0700811 DBG("Moving %zu B entry with transaction ID %zu to to sector %u address %#zx",
David Rogersa2562b52020-03-05 15:30:05 -0800812 entry.size(),
813 size_t(entry.transaction_id()),
David Rogersf3884eb2020-03-08 19:21:40 -0700814 SectorIndex(SectorFromAddress(new_address)),
David Rogersa2562b52020-03-05 15:30:05 -0800815 size_t(new_address));
David Rogerscd87c322020-02-27 14:04:08 -0800816
David Rogersa2562b52020-03-05 15:30:05 -0800817 // Step 2: Write the entry to the new location.
818 entry.UpdateAddress(new_address);
819 result = entry.Write(key, value);
820
821 // Remove any bytes that were written, even if the write was not successful.
822 // This is important to retain the writable space invariant on the sectors.
823 SectorFromAddress(new_address)->RemoveWritableBytes(result.size());
824
825 if (!result.ok()) {
826 ERR("Failed to write %zu bytes at %" PRIx32 ". %zu actually written",
827 entry.size(),
828 new_address,
829 result.size());
830 return result.status();
David Rogersf56131c2020-03-04 10:19:22 -0800831 }
832
David Rogersa2562b52020-03-05 15:30:05 -0800833 // Step 3: Verify write to the new location.
834 if (options_.verify_on_write) {
835 TRY(entry.VerifyChecksumInFlash());
David Rogersf56131c2020-03-04 10:19:22 -0800836 }
David Rogersdf025cd2020-02-06 17:05:34 -0800837
838 return Status::OK;
David Rogersa12786b2020-01-31 16:02:33 -0800839}
840
David Rogersf3884eb2020-03-08 19:21:40 -0700841// Find if search_set contains value.
842// TODO: At some point move this to pw_containers, along with adding tests for
843// it.
844template <typename Container, typename T>
845bool Contains(const Container& search_set, const T& value) {
846 return std::find(std::begin(search_set), std::end(search_set), value) !=
847 std::end(search_set);
848}
849
David Rogers8db5a722020-02-03 18:28:34 -0800850// Find either an existing sector with enough space that is not the sector to
851// skip, or an empty sector. Maintains the invariant that there is always at
David Rogersc8fe1f52020-02-27 14:04:08 -0800852// least 1 empty sector except during GC. On GC, skip sectors that have
853// reclaimable bytes.
Wyatt Hepler5a33d8c2020-02-06 09:32:58 -0800854Status KeyValueStore::FindSectorWithSpace(
855 SectorDescriptor** found_sector,
856 size_t size,
David Rogersc8fe1f52020-02-27 14:04:08 -0800857 FindSectorMode find_mode,
David Rogersa2562b52020-03-05 15:30:05 -0800858 span<const Address> addresses_to_skip) {
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800859 SectorDescriptor* first_empty_sector = nullptr;
David Rogersc8fe1f52020-02-27 14:04:08 -0800860 bool at_least_two_empty_sectors = (find_mode == kGarbageCollect);
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800861
David Rogersf3884eb2020-03-08 19:21:40 -0700862 // Used for the GC reclaimable bytes check
863 SectorDescriptor* non_empty_least_reclaimable_sector = nullptr;
864 const size_t sector_size_bytes = partition_.sector_size_bytes();
865
David Rogersa2562b52020-03-05 15:30:05 -0800866 // Build a vector of sectors to avoid.
David Rogersf3884eb2020-03-08 19:21:40 -0700867 Vector<SectorDescriptor*, internal::kEntryRedundancy> sectors_to_skip;
David Rogersa2562b52020-03-05 15:30:05 -0800868 for (auto& address : addresses_to_skip) {
869 sectors_to_skip.push_back(SectorFromAddress(address));
870 }
871
David Rogersf3884eb2020-03-08 19:21:40 -0700872 DBG("Find sector with %zu bytes available, starting with sector %u, %s",
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800873 size,
David Rogersf3884eb2020-03-08 19:21:40 -0700874 SectorIndex(last_new_sector_),
875 (find_mode == kAppendEntry) ? "Append" : "GC");
David Rogerscd87c322020-02-27 14:04:08 -0800876 for (auto& skip_sector : sectors_to_skip) {
877 DBG(" Skip sector %u", SectorIndex(skip_sector));
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800878 }
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800879
David Rogers8ce55cd2020-02-04 19:41:48 -0800880 // The last_new_sector_ is the sector that was last selected as the "new empty
881 // sector" to write to. This last new sector is used as the starting point for
882 // the next "find a new empty sector to write to" operation. By using the last
883 // new sector as the start point we will cycle which empty sector is selected
884 // next, spreading the wear across all the empty sectors and get a wear
885 // leveling benefit, rather than putting more wear on the lower number
886 // sectors.
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800887 SectorDescriptor* sector = last_new_sector_;
David Rogers67f4b6c2020-02-06 16:17:09 -0800888
David Rogersf3884eb2020-03-08 19:21:40 -0700889 // Look for a sector to use with enough space. The search uses a 3 priority
David Rogerscd87c322020-02-27 14:04:08 -0800890 // tier process.
891 //
David Rogersc8fe1f52020-02-27 14:04:08 -0800892 // Tier 1 is sector that already has valid data. During GC only select a
893 // sector that has no reclaimable bytes. Immediately use the first matching
894 // sector that is found.
David Rogerscd87c322020-02-27 14:04:08 -0800895 //
David Rogersc8fe1f52020-02-27 14:04:08 -0800896 // Tier 2 is find sectors that are empty/erased. While scanning for a partial
897 // sector, keep track of the first empty sector and if a second empty sector
898 // was seen. If during GC then count the second empty sector as always seen.
David Rogersf3884eb2020-03-08 19:21:40 -0700899 //
900 // Tier 3 is during garbage collection, find sectors with enough space that
901 // are not empty but have recoverable bytes. Pick the sector with the least
902 // recoverable bytes to minimize the likelyhood of this sector needing to be
903 // garbage collected soon.
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800904 for (size_t j = 0; j < sectors_.size(); j++) {
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800905 sector += 1;
906 if (sector == sectors_.end()) {
907 sector = sectors_.begin();
908 }
Keir Mierle8c352dc2020-02-02 13:58:19 -0800909
David Rogersf3884eb2020-03-08 19:21:40 -0700910 // Skip sectors in the skip list.
911 if (Contains(sectors_to_skip, sector)) {
David Rogers8db5a722020-02-03 18:28:34 -0800912 continue;
913 }
914
David Rogersf3884eb2020-03-08 19:21:40 -0700915 if (!sector->Empty(sector_size_bytes) && sector->HasSpace(size)) {
916 if ((find_mode == kAppendEntry) ||
917 (sector->RecoverableBytes(sector_size_bytes) == 0)) {
918 *found_sector = sector;
919 return Status::OK;
920 } else {
921 if ((non_empty_least_reclaimable_sector == nullptr) ||
922 (non_empty_least_reclaimable_sector->RecoverableBytes(
923 sector_size_bytes) <
924 sector->RecoverableBytes(sector_size_bytes))) {
925 non_empty_least_reclaimable_sector = sector;
926 }
927 }
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800928 }
929
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800930 if (sector->Empty(sector_size_bytes)) {
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800931 if (first_empty_sector == nullptr) {
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800932 first_empty_sector = sector;
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800933 } else {
934 at_least_two_empty_sectors = true;
Wyatt Hepler2ad60672020-01-21 08:00:16 -0800935 }
Wyatt Heplerb7609542020-01-24 10:29:54 -0800936 }
937 }
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800938
David Rogersf3884eb2020-03-08 19:21:40 -0700939 // Tier 2 check: If the scan for a partial sector does not find a suitable
940 // sector, use the first empty sector that was found. Normally it is required
941 // to keep 1 empty sector after the sector found here, but that rule does not
942 // apply during GC.
943 if (first_empty_sector != nullptr && at_least_two_empty_sectors) {
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800944 DBG(" Found a usable empty sector; returning the first found (%u)",
David Rogers8ce55cd2020-02-04 19:41:48 -0800945 SectorIndex(first_empty_sector));
946 last_new_sector_ = first_empty_sector;
947 *found_sector = first_empty_sector;
948 return Status::OK;
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800949 }
David Rogers8ce55cd2020-02-04 19:41:48 -0800950
David Rogersf3884eb2020-03-08 19:21:40 -0700951 // Tier 3 check: If we got this far, use the sector with least recoverable
952 // bytes
953 if (non_empty_least_reclaimable_sector != nullptr) {
954 *found_sector = non_empty_least_reclaimable_sector;
955 DBG(" Found a usable sector %u, with %zu B recoverable, in GC",
956 SectorIndex(*found_sector),
957 (*found_sector)->RecoverableBytes(sector_size_bytes));
958 return Status::OK;
959 }
960
David Rogers8ce55cd2020-02-04 19:41:48 -0800961 // No sector was found.
David Rogers67f4b6c2020-02-06 16:17:09 -0800962 DBG(" Unable to find a usable sector");
David Rogers8ce55cd2020-02-04 19:41:48 -0800963 *found_sector = nullptr;
964 return Status::RESOURCE_EXHAUSTED;
Wyatt Heplerb7609542020-01-24 10:29:54 -0800965}
966
David Rogersf3884eb2020-03-08 19:21:40 -0700967// TODO: Break up this function in to smaller sub-chunks including create an
968// abstraction for the sector list. Look in to being able to unit test this as
969// its own thing
970KeyValueStore::SectorDescriptor* KeyValueStore::FindSectorToGarbageCollect(
971 span<const Address> addresses_to_avoid) {
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800972 const size_t sector_size_bytes = partition_.sector_size_bytes();
David Rogers2761aeb2020-01-31 17:09:00 -0800973 SectorDescriptor* sector_candidate = nullptr;
David Rogersa12786b2020-01-31 16:02:33 -0800974 size_t candidate_bytes = 0;
975
David Rogersf3884eb2020-03-08 19:21:40 -0700976 // Build a vector of sectors to avoid.
977 Vector<const SectorDescriptor*, internal::kEntryRedundancy> sectors_to_skip;
978 for (auto& address : addresses_to_avoid) {
979 sectors_to_skip.push_back(SectorFromAddress(address));
980 DBG(" Skip sector %u", SectorIndex(SectorFromAddress(address)));
981 }
982
David Rogersa12786b2020-01-31 16:02:33 -0800983 // Step 1: Try to find a sectors with stale keys and no valid keys (no
984 // relocation needed). If any such sectors are found, use the sector with the
985 // most reclaimable bytes.
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800986 for (auto& sector : sectors_) {
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800987 if ((sector.valid_bytes() == 0) &&
David Rogersf3884eb2020-03-08 19:21:40 -0700988 (sector.RecoverableBytes(sector_size_bytes) > candidate_bytes) &&
989 !Contains(sectors_to_skip, &sector)) {
David Rogersa12786b2020-01-31 16:02:33 -0800990 sector_candidate = &sector;
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800991 candidate_bytes = sector.RecoverableBytes(sector_size_bytes);
David Rogersa12786b2020-01-31 16:02:33 -0800992 }
993 }
994
David Rogersf3884eb2020-03-08 19:21:40 -0700995 // Step 2a: If step 1 yields no sectors, just find the sector with the most
996 // reclaimable bytes but no addresses to avoid.
997 if (sector_candidate == nullptr) {
998 for (auto& sector : sectors_) {
999 if ((sector.RecoverableBytes(sector_size_bytes) > candidate_bytes) &&
1000 !Contains(sectors_to_skip, &sector)) {
1001 sector_candidate = &sector;
1002 candidate_bytes = sector.RecoverableBytes(sector_size_bytes);
1003 }
1004 }
1005 }
1006
1007 // Step 2b: If step 1 yields no sectors, just find the sector with the most
David Rogersa12786b2020-01-31 16:02:33 -08001008 // reclaimable bytes.
1009 if (sector_candidate == nullptr) {
Wyatt Hepler1c329ca2020-02-07 18:07:23 -08001010 for (auto& sector : sectors_) {
Wyatt Hepler2c7eca02020-02-18 16:01:42 -08001011 if (sector.RecoverableBytes(sector_size_bytes) > candidate_bytes) {
David Rogersa12786b2020-01-31 16:02:33 -08001012 sector_candidate = &sector;
Wyatt Hepler2c7eca02020-02-18 16:01:42 -08001013 candidate_bytes = sector.RecoverableBytes(sector_size_bytes);
David Rogersa12786b2020-01-31 16:02:33 -08001014 }
1015 }
1016 }
1017
David Rogersf3884eb2020-03-08 19:21:40 -07001018 // Step 3: If no sectors with reclaimable bytes, select the sector with the
1019 // most free bytes. This at least will allow entries of existing keys to get
1020 // spread to other sectors, including sectors that already have copies of the
1021 // current key being written.
1022 if (sector_candidate == nullptr) {
1023 for (auto& sector : sectors_) {
1024 if ((sector.valid_bytes() > candidate_bytes) &&
1025 !Contains(sectors_to_skip, &sector)) {
1026 sector_candidate = &sector;
1027 candidate_bytes = sector.valid_bytes();
1028 DBG(" Doing GC on sector with no reclaimable bytes!");
1029 }
1030 }
1031 }
1032
David Rogers5981f312020-02-13 13:33:56 -08001033 if (sector_candidate != nullptr) {
Wyatt Hepler2c7eca02020-02-18 16:01:42 -08001034 DBG("Found sector %u to Garbage Collect, %zu recoverable bytes",
David Rogers5981f312020-02-13 13:33:56 -08001035 SectorIndex(sector_candidate),
Wyatt Hepler2c7eca02020-02-18 16:01:42 -08001036 sector_candidate->RecoverableBytes(sector_size_bytes));
David Rogers5981f312020-02-13 13:33:56 -08001037 } else {
1038 DBG("Unable to find sector to garbage collect!");
1039 }
David Rogersa12786b2020-01-31 16:02:33 -08001040 return sector_candidate;
1041}
1042
David Rogerscd87c322020-02-27 14:04:08 -08001043Status KeyValueStore::GarbageCollectFull() {
1044 DBG("Garbage Collect all sectors");
David Rogerscd87c322020-02-27 14:04:08 -08001045 SectorDescriptor* sector = last_new_sector_;
1046
1047 // TODO: look in to making an iterator method for cycling through sectors
1048 // starting from last_new_sector_.
1049 for (size_t j = 0; j < sectors_.size(); j++) {
1050 sector += 1;
1051 if (sector == sectors_.end()) {
1052 sector = sectors_.begin();
1053 }
1054
1055 if (sector->RecoverableBytes(partition_.sector_size_bytes()) > 0) {
1056 TRY(GarbageCollectSector(sector));
1057 }
1058 }
1059
1060 DBG("Garbage Collect all complete");
David Rogerscd87c322020-02-27 14:04:08 -08001061 return Status::OK;
1062}
1063
David Rogersf3884eb2020-03-08 19:21:40 -07001064Status KeyValueStore::GarbageCollectPartial(KeyDescriptor* key_in_progress) {
1065 DBG("Garbage Collect a single sector%s",
1066 (key_in_progress == nullptr) ? "" : ", with key in progress");
David Rogers67f4b6c2020-02-06 16:17:09 -08001067
David Rogersa12786b2020-01-31 16:02:33 -08001068 // Step 1: Find the sector to garbage collect
David Rogersf3884eb2020-03-08 19:21:40 -07001069 auto addresses = span<const Address>();
1070 if (key_in_progress != nullptr) {
1071 DBG(" Use addresses to avoid");
1072 addresses = key_in_progress->addresses();
1073 }
1074 SectorDescriptor* sector_to_gc = FindSectorToGarbageCollect(addresses);
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -08001075
David Rogersa12786b2020-01-31 16:02:33 -08001076 if (sector_to_gc == nullptr) {
David Rogersa2562b52020-03-05 15:30:05 -08001077 // Nothing to GC.
1078 return Status::NOT_FOUND;
David Rogersa12786b2020-01-31 16:02:33 -08001079 }
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -08001080
David Rogersf3884eb2020-03-08 19:21:40 -07001081 TRY(GarbageCollectSector(sector_to_gc, key_in_progress));
David Rogerscd87c322020-02-27 14:04:08 -08001082 return Status::OK;
1083}
1084
David Rogersf3884eb2020-03-08 19:21:40 -07001085Status KeyValueStore::RelocateKeyAddressesInSector(
1086 internal::SectorDescriptor* sector_to_gc,
1087 internal::KeyDescriptor* descriptor) {
1088 for (auto address : descriptor->addresses()) {
1089 if (AddressInSector(*sector_to_gc, address)) {
1090 DBG(" Relocate entry for Key 0x%08zx, address %zu",
1091 size_t(descriptor->hash()),
1092 size_t(address));
1093 TRY(RelocateEntry(descriptor, address));
1094 }
1095 }
1096 return Status::OK;
1097};
1098
1099Status KeyValueStore::GarbageCollectSector(SectorDescriptor* sector_to_gc,
1100 KeyDescriptor* key_in_progress) {
1101 // Pre-step: Check if the key in progress has any addresses in the sector to
1102 // GC.
1103 bool key_in_progress_in_sector = false;
1104 if (key_in_progress != nullptr) {
1105 for (Address address : key_in_progress->addresses()) {
1106 if (AddressInSector(*sector_to_gc, address)) {
1107 key_in_progress_in_sector = true;
1108 break;
David Rogersa12786b2020-01-31 16:02:33 -08001109 }
Wyatt Heplerb7609542020-01-24 10:29:54 -08001110 }
1111 }
Wyatt Heplerb7609542020-01-24 10:29:54 -08001112
David Rogersf3884eb2020-03-08 19:21:40 -07001113 // Step 1: Move any valid entries in the GC sector to other sectors
1114 if ((sector_to_gc->valid_bytes() != 0 || key_in_progress_in_sector)) {
1115 if (key_in_progress != nullptr) {
1116 TRY(RelocateKeyAddressesInSector(sector_to_gc, key_in_progress));
1117 }
1118 for (auto& descriptor : key_descriptors_) {
1119 TRY(RelocateKeyAddressesInSector(sector_to_gc, &descriptor));
1120 }
1121 }
1122
Wyatt Hepler2c7eca02020-02-18 16:01:42 -08001123 if (sector_to_gc->valid_bytes() != 0) {
David Rogers67f4b6c2020-02-06 16:17:09 -08001124 ERR(" Failed to relocate valid entries from sector being garbage "
Wyatt Hepler2c7eca02020-02-18 16:01:42 -08001125 "collected, %zu valid bytes remain",
1126 sector_to_gc->valid_bytes());
Wyatt Heplerb7609542020-01-24 10:29:54 -08001127 return Status::INTERNAL;
1128 }
1129
David Rogerscd87c322020-02-27 14:04:08 -08001130 // Step 2: Reinitialize the sector
Wyatt Hepler2c7eca02020-02-18 16:01:42 -08001131 sector_to_gc->set_writable_bytes(0);
David Rogersa12786b2020-01-31 16:02:33 -08001132 TRY(partition_.Erase(SectorBaseAddress(sector_to_gc), 1));
Wyatt Hepler2c7eca02020-02-18 16:01:42 -08001133 sector_to_gc->set_writable_bytes(partition_.sector_size_bytes());
Wyatt Heplerb7609542020-01-24 10:29:54 -08001134
David Rogerscd87c322020-02-27 14:04:08 -08001135 DBG(" Garbage Collect sector %u complete", SectorIndex(sector_to_gc));
David Rogersa12786b2020-01-31 16:02:33 -08001136 return Status::OK;
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -08001137}
1138
Wyatt Heplerbdd8e5a2020-02-20 19:27:26 -08001139KeyValueStore::Entry KeyValueStore::CreateEntry(Address address,
1140 std::string_view key,
1141 span<const byte> value,
1142 KeyDescriptor::State state) {
Keir Mierle9e38b402020-02-21 13:06:21 -08001143 // Always bump the transaction ID when creating a new entry.
1144 //
1145 // Burning transaction IDs prevents inconsistencies between flash and memory
1146 // that which could happen if a write succeeds, but for some reason the read
1147 // and verify step fails. Here's how this would happen:
1148 //
1149 // 1. The entry is written but for some reason the flash reports failure OR
1150 // The write succeeds, but the read / verify operation fails.
1151 // 2. The transaction ID is NOT incremented, because of the failure
1152 // 3. (later) A new entry is written, re-using the transaction ID (oops)
1153 //
1154 // By always burning transaction IDs, the above problem can't happen.
1155 last_transaction_id_ += 1;
1156
Wyatt Hepler1fc11042020-02-19 17:17:51 -08001157 if (state == KeyDescriptor::kDeleted) {
Wyatt Hepler7465be32020-02-21 15:30:53 -08001158 return Entry::Tombstone(
Wyatt Hepler22d0d9f2020-03-05 14:57:11 -08001159 partition_, address, formats_.primary(), key, last_transaction_id_);
Wyatt Hepler1fc11042020-02-19 17:17:51 -08001160 }
1161 return Entry::Valid(partition_,
1162 address,
Wyatt Hepler22d0d9f2020-03-05 14:57:11 -08001163 formats_.primary(),
Wyatt Hepler1fc11042020-02-19 17:17:51 -08001164 key,
1165 value,
Keir Mierle9e38b402020-02-21 13:06:21 -08001166 last_transaction_id_);
Wyatt Heplerd2298282020-02-20 17:12:45 -08001167}
1168
1169void KeyValueStore::Reset() {
1170 initialized_ = false;
1171 key_descriptors_.clear();
1172 last_new_sector_ = nullptr;
1173 last_transaction_id_ = 0;
Wyatt Hepler1fc11042020-02-19 17:17:51 -08001174}
1175
Keir Mierle8c352dc2020-02-02 13:58:19 -08001176void KeyValueStore::LogDebugInfo() {
Keir Mierle8c352dc2020-02-02 13:58:19 -08001177 const size_t sector_size_bytes = partition_.sector_size_bytes();
1178 DBG("====================== KEY VALUE STORE DUMP =========================");
1179 DBG(" ");
1180 DBG("Flash partition:");
Wyatt Heplerad0a7932020-02-06 08:20:38 -08001181 DBG(" Sector count = %zu", partition_.sector_count());
Wyatt Hepler38ce30f2020-02-19 11:48:31 -08001182 DBG(" Sector max count = %zu", sectors_.max_size());
Wyatt Hepler1c329ca2020-02-07 18:07:23 -08001183 DBG(" Sectors in use = %zu", sectors_.size());
Keir Mierle8c352dc2020-02-02 13:58:19 -08001184 DBG(" Sector size = %zu", sector_size_bytes);
1185 DBG(" Total size = %zu", partition_.size_bytes());
1186 DBG(" Alignment = %zu", partition_.alignment_bytes());
1187 DBG(" ");
1188 DBG("Key descriptors:");
Wyatt Hepler1c329ca2020-02-07 18:07:23 -08001189 DBG(" Entry count = %zu", key_descriptors_.size());
Wyatt Hepler38ce30f2020-02-19 11:48:31 -08001190 DBG(" Max entry count = %zu", key_descriptors_.max_size());
Keir Mierle8c352dc2020-02-02 13:58:19 -08001191 DBG(" ");
1192 DBG(" # hash version address address (hex)");
Wyatt Hepler1c329ca2020-02-07 18:07:23 -08001193 for (size_t i = 0; i < key_descriptors_.size(); ++i) {
1194 const KeyDescriptor& kd = key_descriptors_[i];
Keir Mierle8c352dc2020-02-02 13:58:19 -08001195 DBG(" |%3zu: | %8zx |%8zu | %8zu | %8zx",
1196 i,
Wyatt Hepler1fc11042020-02-19 17:17:51 -08001197 size_t(kd.hash()),
1198 size_t(kd.transaction_id()),
1199 size_t(kd.address()),
1200 size_t(kd.address()));
Keir Mierle8c352dc2020-02-02 13:58:19 -08001201 }
1202 DBG(" ");
1203
1204 DBG("Sector descriptors:");
1205 DBG(" # tail free valid has_space");
Wyatt Hepler1c329ca2020-02-07 18:07:23 -08001206 for (size_t sector_id = 0; sector_id < sectors_.size(); ++sector_id) {
1207 const SectorDescriptor& sd = sectors_[sector_id];
Keir Mierle8c352dc2020-02-02 13:58:19 -08001208 DBG(" |%3zu: | %8zu |%8zu | %s",
1209 sector_id,
Wyatt Hepler2c7eca02020-02-18 16:01:42 -08001210 size_t(sd.writable_bytes()),
1211 sd.valid_bytes(),
1212 sd.writable_bytes() ? "YES" : "");
Keir Mierle8c352dc2020-02-02 13:58:19 -08001213 }
1214 DBG(" ");
1215
1216 // TODO: This should stop logging after some threshold.
1217 // size_t dumped_bytes = 0;
1218 DBG("Sector raw data:");
Wyatt Hepler1c329ca2020-02-07 18:07:23 -08001219 for (size_t sector_id = 0; sector_id < sectors_.size(); ++sector_id) {
Keir Mierle8c352dc2020-02-02 13:58:19 -08001220 // Read sector data. Yes, this will blow the stack on embedded.
Wyatt Hepler1c329ca2020-02-07 18:07:23 -08001221 std::array<byte, 500> raw_sector_data; // TODO!!!
Keir Mierle8c352dc2020-02-02 13:58:19 -08001222 StatusWithSize sws =
1223 partition_.Read(sector_id * sector_size_bytes, raw_sector_data);
1224 DBG("Read: %zu bytes", sws.size());
1225
1226 DBG(" base addr offs 0 1 2 3 4 5 6 7");
1227 for (size_t i = 0; i < sector_size_bytes; i += 8) {
1228 DBG(" %3zu %8zx %5zu | %02x %02x %02x %02x %02x %02x %02x %02x",
1229 sector_id,
1230 (sector_id * sector_size_bytes) + i,
1231 i,
1232 static_cast<unsigned int>(raw_sector_data[i + 0]),
1233 static_cast<unsigned int>(raw_sector_data[i + 1]),
1234 static_cast<unsigned int>(raw_sector_data[i + 2]),
1235 static_cast<unsigned int>(raw_sector_data[i + 3]),
1236 static_cast<unsigned int>(raw_sector_data[i + 4]),
1237 static_cast<unsigned int>(raw_sector_data[i + 5]),
1238 static_cast<unsigned int>(raw_sector_data[i + 6]),
1239 static_cast<unsigned int>(raw_sector_data[i + 7]));
1240
1241 // TODO: Fix exit condition.
1242 if (i > 128) {
1243 break;
1244 }
1245 }
1246 DBG(" ");
1247 }
1248
1249 DBG("////////////////////// KEY VALUE STORE DUMP END /////////////////////");
1250}
1251
David Rogerscf680ab2020-02-12 23:28:32 -08001252void KeyValueStore::LogSectors() const {
1253 DBG("Sector descriptors: count %zu", sectors_.size());
Wyatt Hepler1c329ca2020-02-07 18:07:23 -08001254 for (auto& sector : sectors_) {
Wyatt Hepler2c7eca02020-02-18 16:01:42 -08001255 DBG(" - Sector %u: valid %zu, recoverable %zu, free %zu",
David Rogers50185ad2020-02-07 00:02:46 -08001256 SectorIndex(&sector),
Wyatt Hepler2c7eca02020-02-18 16:01:42 -08001257 sector.valid_bytes(),
1258 sector.RecoverableBytes(partition_.sector_size_bytes()),
1259 sector.writable_bytes());
David Rogers50185ad2020-02-07 00:02:46 -08001260 }
1261}
1262
David Rogerscf680ab2020-02-12 23:28:32 -08001263void KeyValueStore::LogKeyDescriptor() const {
1264 DBG("Key descriptors: count %zu", key_descriptors_.size());
1265 for (auto& key : key_descriptors_) {
Wyatt Hepler1fc11042020-02-19 17:17:51 -08001266 DBG(" - Key: %s, hash %#zx, transaction ID %zu, address %#zx",
David Rogerscf680ab2020-02-12 23:28:32 -08001267 key.deleted() ? "Deleted" : "Valid",
Wyatt Hepler1fc11042020-02-19 17:17:51 -08001268 static_cast<size_t>(key.hash()),
1269 static_cast<size_t>(key.transaction_id()),
1270 static_cast<size_t>(key.address()));
David Rogerscf680ab2020-02-12 23:28:32 -08001271 }
1272}
1273
Wyatt Hepler2ad60672020-01-21 08:00:16 -08001274} // namespace pw::kvs