blob: 32fbfc2f9dfa3051619cd9449b5573752cf98afa [file] [log] [blame]
Wyatt Heplerb7609542020-01-24 10:29:54 -08001// Copyright 2020 The Pigweed Authors
2//
3// Licensed under the Apache License, Version 2.0 (the "License"); you may not
4// use this file except in compliance with the License. You may obtain a copy of
5// the License at
6//
7// https://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
11// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12// License for the specific language governing permissions and limitations under
13// the License.
14
Wyatt Heplerb7609542020-01-24 10:29:54 -080015#include "pw_kvs/key_value_store.h"
16
Wyatt Heplerbab0e202020-02-04 07:40:08 -080017#include <algorithm>
Wyatt Hepler5a33d8c2020-02-06 09:32:58 -080018#include <cinttypes>
Wyatt Heplerb7609542020-01-24 10:29:54 -080019#include <cstring>
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -080020#include <type_traits>
Wyatt Heplerb7609542020-01-24 10:29:54 -080021
Keir Mierle8c352dc2020-02-02 13:58:19 -080022#define PW_LOG_USE_ULTRA_SHORT_NAMES 1
Wyatt Heplerd31d9702020-02-14 08:46:36 -080023#include "pw_kvs_private/entry.h"
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -080024#include "pw_kvs_private/macros.h"
Keir Mierle8c352dc2020-02-02 13:58:19 -080025#include "pw_log/log.h"
Wyatt Heplerb7609542020-01-24 10:29:54 -080026
Wyatt Hepler2ad60672020-01-21 08:00:16 -080027namespace pw::kvs {
Wyatt Heplera00d1ef2020-02-14 14:31:26 -080028namespace {
Wyatt Heplerb7609542020-01-24 10:29:54 -080029
Wyatt Hepleracaacf92020-01-24 10:58:30 -080030using std::byte;
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -080031using std::string_view;
Wyatt Hepleracaacf92020-01-24 10:58:30 -080032
Wyatt Heplera00d1ef2020-02-14 14:31:26 -080033constexpr bool InvalidKey(std::string_view key) {
34 return key.empty() || (key.size() > Entry::kMaxKeyLength);
35}
36
37} // namespace
38
Wyatt Heplerad0a7932020-02-06 08:20:38 -080039KeyValueStore::KeyValueStore(FlashPartition* partition,
40 const EntryHeaderFormat& format,
41 const Options& options)
42 : partition_(*partition),
43 entry_header_format_(format),
44 options_(options),
Wyatt Hepler1c329ca2020-02-07 18:07:23 -080045 sectors_(partition_.sector_count()),
Wyatt Hepler5406a672020-02-18 15:42:38 -080046 last_new_sector_(sectors_.data()) {}
Wyatt Heplerad0a7932020-02-06 08:20:38 -080047
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -080048Status KeyValueStore::Init() {
David Rogers2e9e0c82020-02-13 15:06:06 -080049 INF("Initializing key value store");
50 if (kMaxUsableSectors < partition_.sector_count()) {
51 ERR("KVS init failed: kMaxUsableSectors (=%zu) must be at least as "
52 "large as the number of sectors in the flash partition (=%zu)",
53 kMaxUsableSectors,
54 partition_.sector_count());
Wyatt Heplerad0a7932020-02-06 08:20:38 -080055 return Status::FAILED_PRECONDITION;
56 }
57
Wyatt Hepler1c329ca2020-02-07 18:07:23 -080058 if (kMaxUsableSectors > sectors_.size()) {
Wyatt Heplerad0a7932020-02-06 08:20:38 -080059 DBG("KeyValueStore::kMaxUsableSectors is %zu sectors larger than needed",
Wyatt Hepler1c329ca2020-02-07 18:07:23 -080060 kMaxUsableSectors - sectors_.size());
Wyatt Heplerad0a7932020-02-06 08:20:38 -080061 }
62
Keir Mierle8c352dc2020-02-02 13:58:19 -080063 // Reset the number of occupied key descriptors; we will fill them later.
Wyatt Hepler1c329ca2020-02-07 18:07:23 -080064 key_descriptors_.clear();
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -080065
David Rogers8ce55cd2020-02-04 19:41:48 -080066 // TODO: init last_new_sector_ to a random sector. Since the on-flash stored
67 // information does not allow recovering the previous last_new_sector_ after
68 // clean start, random is a good second choice.
69
Keir Mierle8c352dc2020-02-02 13:58:19 -080070 const size_t sector_size_bytes = partition_.sector_size_bytes();
Keir Mierle8c352dc2020-02-02 13:58:19 -080071
David Rogersf0a35442020-02-04 12:16:38 -080072 if (working_buffer_.size() < sector_size_bytes) {
David Rogers2e9e0c82020-02-13 15:06:06 -080073 ERR("KVS init failed: working_buffer_ (%zu bytes) is smaller than sector "
74 "size (%zu bytes)",
David Rogersf0a35442020-02-04 12:16:38 -080075 working_buffer_.size(),
76 sector_size_bytes);
77 return Status::INVALID_ARGUMENT;
78 }
79
Keir Mierle8c352dc2020-02-02 13:58:19 -080080 DBG("First pass: Read all entries from all sectors");
Wyatt Hepler1c329ca2020-02-07 18:07:23 -080081 for (size_t sector_id = 0; sector_id < sectors_.size(); ++sector_id) {
Keir Mierle8c352dc2020-02-02 13:58:19 -080082 // Track writable bytes in this sector. Updated after reading each entry.
Wyatt Hepler1c329ca2020-02-07 18:07:23 -080083 sectors_[sector_id].tail_free_bytes = sector_size_bytes;
Keir Mierle8c352dc2020-02-02 13:58:19 -080084
85 const Address sector_address = sector_id * sector_size_bytes;
86 Address entry_address = sector_address;
87
88 for (int num_entries_in_sector = 0;; num_entries_in_sector++) {
89 DBG("Load entry: sector=%zu, entry#=%d, address=%zu",
90 sector_id,
91 num_entries_in_sector,
92 size_t(entry_address));
93
Wyatt Hepler1c329ca2020-02-07 18:07:23 -080094 if (!AddressInSector(sectors_[sector_id], entry_address)) {
Keir Mierle8c352dc2020-02-02 13:58:19 -080095 DBG("Fell off end of sector; moving to the next sector");
96 break;
97 }
98
99 Address next_entry_address;
100 Status status = LoadEntry(entry_address, &next_entry_address);
101 if (status == Status::NOT_FOUND) {
102 DBG("Hit un-written data in sector; moving to the next sector");
103 break;
104 }
105 if (status == Status::DATA_LOSS) {
106 // It's not clear KVS can make a unilateral decision about what to do
107 // in corruption cases. It's an application decision, for which we
108 // should offer some configurability. For now, entirely bail out of
109 // loading and give up.
110 //
111 // Later, scan for remaining valid keys; since it's entirely possible
112 // that there is a duplicate of the key elsewhere and everything is
113 // fine. Later, we can wipe and maybe recover the sector.
114 //
115 // TODO: Implement rest-of-sector scanning for valid entries.
David Rogers2e9e0c82020-02-13 15:06:06 -0800116 ERR("KVS init failed: data loss detected in sector %zu at address %zu",
117 sector_id,
118 static_cast<size_t>(entry_address));
Keir Mierle8c352dc2020-02-02 13:58:19 -0800119 return Status::DATA_LOSS;
120 }
121 TRY(status);
122
123 // Entry loaded successfully; so get ready to load the next one.
124 entry_address = next_entry_address;
125
126 // Update of the number of writable bytes in this sector.
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800127 sectors_[sector_id].tail_free_bytes =
Keir Mierle8c352dc2020-02-02 13:58:19 -0800128 sector_size_bytes - (entry_address - sector_address);
129 }
130 }
131
132 DBG("Second pass: Count valid bytes in each sector");
133 // Initialize the sector sizes.
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800134 for (SectorDescriptor& sector : sectors_) {
135 sector.valid_bytes = 0;
Keir Mierle8c352dc2020-02-02 13:58:19 -0800136 }
137 // For every valid key, increment the valid bytes for that sector.
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800138 for (KeyDescriptor& key_descriptor : key_descriptors_) {
139 uint32_t sector_id = key_descriptor.address / sector_size_bytes;
Wyatt Heplere541e072020-02-14 09:10:53 -0800140 Entry entry;
141 TRY(Entry::Read(partition_, key_descriptor.address, &entry));
142 sectors_[sector_id].valid_bytes += entry.size();
Keir Mierle8c352dc2020-02-02 13:58:19 -0800143 }
Wyatt Hepler729f28c2020-02-05 09:46:00 -0800144 initialized_ = true;
David Rogers2e9e0c82020-02-13 15:06:06 -0800145
146 INF("KeyValueStore init complete: active keys %zu, deleted keys %zu, sectors "
147 "%zu, logical sector size %zu bytes",
148 size(),
149 (key_descriptors_.size() - size()),
150 sectors_.size(),
151 partition_.sector_size_bytes());
152
Keir Mierle8c352dc2020-02-02 13:58:19 -0800153 return Status::OK;
154}
155
156Status KeyValueStore::LoadEntry(Address entry_address,
157 Address* next_entry_address) {
Wyatt Heplere541e072020-02-14 09:10:53 -0800158 Entry entry;
159 TRY(Entry::Read(partition_, entry_address, &entry));
Keir Mierle8c352dc2020-02-02 13:58:19 -0800160
161 // TODO: Handle multiple magics for formats that have changed.
Wyatt Heplere541e072020-02-14 09:10:53 -0800162 if (entry.magic() != entry_header_format_.magic) {
Keir Mierle8c352dc2020-02-02 13:58:19 -0800163 // TODO: It may be cleaner to have some logging helpers for these cases.
Wyatt Heplere541e072020-02-14 09:10:53 -0800164 ERR("Found corrupt magic: %zx; expecting %zx; at address %zx",
165 size_t(entry.magic()),
Keir Mierle8c352dc2020-02-02 13:58:19 -0800166 size_t(entry_header_format_.magic),
167 size_t(entry_address));
168 return Status::DATA_LOSS;
169 }
170
171 // Read the key from flash & validate the entry (which reads the value).
Wyatt Heplera00d1ef2020-02-14 14:31:26 -0800172 Entry::KeyBuffer key_buffer;
Wyatt Heplere541e072020-02-14 09:10:53 -0800173 TRY_ASSIGN(size_t key_length, entry.ReadKey(key_buffer));
174 const string_view key(key_buffer.data(), key_length);
Wyatt Heplerbab0e202020-02-04 07:40:08 -0800175
Wyatt Heplere541e072020-02-14 09:10:53 -0800176 TRY(entry.VerifyChecksumInFlash(entry_header_format_.checksum));
Wyatt Hepler4d78cd62020-02-05 13:05:58 -0800177
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800178 KeyDescriptor key_descriptor(
179 key,
Wyatt Heplere541e072020-02-14 09:10:53 -0800180 entry.key_version(),
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800181 entry_address,
Wyatt Heplere541e072020-02-14 09:10:53 -0800182 entry.deleted() ? KeyDescriptor::kDeleted : KeyDescriptor::kValid);
Keir Mierle8c352dc2020-02-02 13:58:19 -0800183
184 DBG("Key hash: %zx (%zu)",
185 size_t(key_descriptor.key_hash),
186 size_t(key_descriptor.key_hash));
187
188 TRY(AppendNewOrOverwriteStaleExistingDescriptor(key_descriptor));
189
Wyatt Heplere541e072020-02-14 09:10:53 -0800190 *next_entry_address = entry.next_address();
Keir Mierle8c352dc2020-02-02 13:58:19 -0800191 return Status::OK;
192}
193
194// TODO: This method is the trigger of the O(valid_entries * all_entries) time
195// complexity for reading. At some cost to memory, this could be optimized by
196// using a hash table instead of scanning, but in practice this should be fine
197// for a small number of keys
198Status KeyValueStore::AppendNewOrOverwriteStaleExistingDescriptor(
199 const KeyDescriptor& key_descriptor) {
200 // With the new key descriptor, either add it to the descriptor table or
201 // overwrite an existing entry with an older version of the key.
202 KeyDescriptor* existing_descriptor = FindDescriptor(key_descriptor.key_hash);
Keir Mierle8c352dc2020-02-02 13:58:19 -0800203
Wyatt Hepler5406a672020-02-18 15:42:38 -0800204 // Write a new entry.
205 if (existing_descriptor == nullptr) {
206 if (key_descriptors_.full()) {
207 return Status::RESOURCE_EXHAUSTED;
208 }
209 key_descriptors_.push_back(key_descriptor);
210 } else if (existing_descriptor->key_version < key_descriptor.key_version) {
211 // Existing entry is old; replace the existing entry with the new one.
212 *existing_descriptor = key_descriptor;
213 } else {
214 // Otherwise, check for data integrity and leave the existing entry.
215 if (existing_descriptor->key_version == key_descriptor.key_version) {
216 ERR("Data loss: Duplicated old(=%zu) and new(=%zu) version",
217 size_t(existing_descriptor->key_version),
218 size_t(key_descriptor.key_version));
219 return Status::DATA_LOSS;
220 }
221 DBG("Found stale entry when appending; ignoring");
Keir Mierle8c352dc2020-02-02 13:58:19 -0800222 }
Keir Mierle8c352dc2020-02-02 13:58:19 -0800223 return Status::OK;
224}
225
Keir Mierle8c352dc2020-02-02 13:58:19 -0800226KeyValueStore::KeyDescriptor* KeyValueStore::FindDescriptor(uint32_t hash) {
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800227 for (KeyDescriptor& key_descriptor : key_descriptors_) {
228 if (key_descriptor.key_hash == hash) {
229 return &key_descriptor;
Keir Mierle8c352dc2020-02-02 13:58:19 -0800230 }
231 }
232 return nullptr;
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800233}
234
235StatusWithSize KeyValueStore::Get(string_view key,
Wyatt Hepler5f6efc02020-02-18 16:54:31 -0800236 span<byte> value_buffer,
237 size_t offset_bytes) const {
Wyatt Hepler50f70772020-02-13 11:25:10 -0800238 TRY_WITH_SIZE(CheckOperation(key));
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800239
David Rogers2761aeb2020-01-31 17:09:00 -0800240 const KeyDescriptor* key_descriptor;
Wyatt Hepler2d401692020-02-13 16:01:23 -0800241 TRY_WITH_SIZE(FindExistingKeyDescriptor(key, &key_descriptor));
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800242
Wyatt Heplere541e072020-02-14 09:10:53 -0800243 Entry entry;
244 TRY_WITH_SIZE(Entry::Read(partition_, key_descriptor->address, &entry));
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800245
Wyatt Hepler5f6efc02020-02-18 16:54:31 -0800246 StatusWithSize result = entry.ReadValue(value_buffer, offset_bytes);
247 if (result.ok() && options_.verify_on_read && offset_bytes == 0u) {
David Rogerscf680ab2020-02-12 23:28:32 -0800248 Status verify_result =
Wyatt Heplere541e072020-02-14 09:10:53 -0800249 entry.VerifyChecksum(entry_header_format_.checksum,
250 key,
251 value_buffer.subspan(0, result.size()));
David Rogerscf680ab2020-02-12 23:28:32 -0800252 if (!verify_result.ok()) {
Wyatt Hepler50f70772020-02-13 11:25:10 -0800253 std::memset(
254 value_buffer.subspan(0, result.size()).data(), 0, result.size());
255 return StatusWithSize(verify_result);
David Rogerscf680ab2020-02-12 23:28:32 -0800256 }
257
258 return StatusWithSize(verify_result, result.size());
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800259 }
260 return result;
261}
262
263Status KeyValueStore::Put(string_view key, span<const byte> value) {
Keir Mierle8c352dc2020-02-02 13:58:19 -0800264 DBG("Writing key/value; key length=%zu, value length=%zu",
265 key.size(),
266 value.size());
Wyatt Hepler729f28c2020-02-05 09:46:00 -0800267
268 TRY(CheckOperation(key));
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800269
Wyatt Hepler5406a672020-02-18 15:42:38 -0800270 if (Entry::size(partition_, key, value) > partition_.sector_size_bytes()) {
271 DBG("%zu B value with %zu B key cannot fit in one sector",
272 value.size(),
273 key.size());
274 return Status::INVALID_ARGUMENT;
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800275 }
276
David Rogers2761aeb2020-01-31 17:09:00 -0800277 KeyDescriptor* key_descriptor;
Wyatt Hepler2d401692020-02-13 16:01:23 -0800278 Status status = FindKeyDescriptor(key, &key_descriptor);
279
280 if (status.ok()) {
David Rogers3464d0a2020-02-07 11:45:46 -0800281 DBG("Writing over existing entry for key 0x%08" PRIx32 " in sector %zu",
282 key_descriptor->key_hash,
283 SectorIndex(SectorFromAddress(key_descriptor->address)));
Wyatt Hepler5a33d8c2020-02-06 09:32:58 -0800284 return WriteEntryForExistingKey(
285 key_descriptor, KeyDescriptor::kValid, key, value);
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800286 }
David Rogers2761aeb2020-01-31 17:09:00 -0800287
Wyatt Hepler2d401692020-02-13 16:01:23 -0800288 if (status == Status::NOT_FOUND) {
289 return WriteEntryForNewKey(key, value);
290 }
291
292 return status;
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800293}
294
295Status KeyValueStore::Delete(string_view key) {
Wyatt Hepler729f28c2020-02-05 09:46:00 -0800296 TRY(CheckOperation(key));
297
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800298 KeyDescriptor* key_descriptor;
Wyatt Hepler2d401692020-02-13 16:01:23 -0800299 TRY(FindExistingKeyDescriptor(key, &key_descriptor));
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800300
David Rogers3464d0a2020-02-07 11:45:46 -0800301 DBG("Writing tombstone for existing key 0x%08" PRIx32 " in sector %zu",
302 key_descriptor->key_hash,
303 SectorIndex(SectorFromAddress(key_descriptor->address)));
Wyatt Hepler5a33d8c2020-02-06 09:32:58 -0800304 return WriteEntryForExistingKey(
305 key_descriptor, KeyDescriptor::kDeleted, key, {});
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800306}
307
308KeyValueStore::iterator& KeyValueStore::iterator::operator++() {
309 // Skip to the next entry that is valid (not deleted).
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800310 while (++index_ < item_.kvs_.key_descriptors_.size() &&
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800311 descriptor().deleted()) {
312 }
313 return *this;
314}
315
316const KeyValueStore::Item& KeyValueStore::iterator::operator*() {
317 std::memset(item_.key_buffer_.data(), 0, item_.key_buffer_.size());
318
Wyatt Heplere541e072020-02-14 09:10:53 -0800319 Entry entry;
320 if (Entry::Read(item_.kvs_.partition_, descriptor().address, &entry).ok()) {
321 entry.ReadKey(item_.key_buffer_);
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800322 }
323
324 return item_;
325}
326
327KeyValueStore::iterator KeyValueStore::begin() const {
328 size_t i = 0;
329 // Skip over any deleted entries at the start of the descriptor list.
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800330 while (i < key_descriptors_.size() && key_descriptors_[i].deleted()) {
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800331 i += 1;
332 }
333 return iterator(*this, i);
334}
335
336// TODO(hepler): The valid entry count could be tracked in the KVS to avoid the
337// need for this for-loop.
338size_t KeyValueStore::size() const {
339 size_t valid_entries = 0;
340
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800341 for (const KeyDescriptor& key_descriptor : key_descriptors_) {
342 if (!key_descriptor.deleted()) {
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800343 valid_entries += 1;
344 }
345 }
346
347 return valid_entries;
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800348}
349
Wyatt Heplered163b02020-02-03 17:49:32 -0800350StatusWithSize KeyValueStore::ValueSize(std::string_view key) const {
Wyatt Hepler50f70772020-02-13 11:25:10 -0800351 TRY_WITH_SIZE(CheckOperation(key));
Wyatt Heplered163b02020-02-03 17:49:32 -0800352
353 const KeyDescriptor* key_descriptor;
Wyatt Hepler2d401692020-02-13 16:01:23 -0800354 TRY_WITH_SIZE(FindExistingKeyDescriptor(key, &key_descriptor));
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800355
Wyatt Heplere541e072020-02-14 09:10:53 -0800356 Entry entry;
357 TRY_WITH_SIZE(Entry::Read(partition_, key_descriptor->address, &entry));
Wyatt Heplered163b02020-02-03 17:49:32 -0800358
Wyatt Heplere541e072020-02-14 09:10:53 -0800359 return StatusWithSize(entry.value_size());
Wyatt Heplered163b02020-02-03 17:49:32 -0800360}
361
Wyatt Hepler4d78cd62020-02-05 13:05:58 -0800362uint32_t KeyValueStore::HashKey(string_view string) {
363 uint32_t hash = 0;
364 uint32_t coefficient = 65599u;
365
366 for (char ch : string) {
367 hash += coefficient * unsigned(ch);
368 coefficient *= 65599u;
369 }
370
371 return hash;
372}
373
Wyatt Hepler6e3a83b2020-02-04 07:36:45 -0800374Status KeyValueStore::FixedSizeGet(std::string_view key,
375 byte* value,
376 size_t size_bytes) const {
377 // Ensure that the size of the stored value matches the size of the type.
378 // Otherwise, report error. This check avoids potential memory corruption.
379 StatusWithSize result = ValueSize(key);
380 if (!result.ok()) {
381 return result.status();
Keir Mierle8c352dc2020-02-02 13:58:19 -0800382 }
Wyatt Hepler6e3a83b2020-02-04 07:36:45 -0800383 if (result.size() != size_bytes) {
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800384 DBG("Requested %zu B read, but value is %zu B", size_bytes, result.size());
Wyatt Hepler6e3a83b2020-02-04 07:36:45 -0800385 return Status::INVALID_ARGUMENT;
Wyatt Heplerbab0e202020-02-04 07:40:08 -0800386 }
Wyatt Hepler6e3a83b2020-02-04 07:36:45 -0800387 return Get(key, span(value, size_bytes)).status();
Keir Mierle8c352dc2020-02-02 13:58:19 -0800388}
389
Wyatt Hepler729f28c2020-02-05 09:46:00 -0800390Status KeyValueStore::CheckOperation(string_view key) const {
Wyatt Hepleracaacf92020-01-24 10:58:30 -0800391 if (InvalidKey(key)) {
Wyatt Heplerb7609542020-01-24 10:29:54 -0800392 return Status::INVALID_ARGUMENT;
393 }
Wyatt Hepler729f28c2020-02-05 09:46:00 -0800394 if (!initialized_) {
Wyatt Heplerb7609542020-01-24 10:29:54 -0800395 return Status::FAILED_PRECONDITION;
396 }
Wyatt Heplerb7609542020-01-24 10:29:54 -0800397 return Status::OK;
398}
399
Wyatt Hepler2d401692020-02-13 16:01:23 -0800400// Searches for a KeyDescriptor that matches this key and sets *result to point
401// to it if one is found.
402//
403// OK: there is a matching descriptor and *result is set
404// NOT_FOUND: there is no descriptor that matches this key, but this key
405// has a unique hash (and could potentially be added to the KVS)
406// ALREADY_EXISTS: there is no descriptor that matches this key, but the
407// key's hash collides with the hash for an existing descriptor
408//
David Rogers2761aeb2020-01-31 17:09:00 -0800409Status KeyValueStore::FindKeyDescriptor(string_view key,
410 const KeyDescriptor** result) const {
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800411 const uint32_t hash = HashKey(key);
Wyatt Heplera00d1ef2020-02-14 14:31:26 -0800412 Entry::KeyBuffer key_buffer;
Wyatt Heplerb7609542020-01-24 10:29:54 -0800413
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800414 for (auto& descriptor : key_descriptors_) {
David Rogers2761aeb2020-01-31 17:09:00 -0800415 if (descriptor.key_hash == hash) {
Wyatt Heplere541e072020-02-14 09:10:53 -0800416 TRY(Entry::ReadKey(
Wyatt Heplera00d1ef2020-02-14 14:31:26 -0800417 partition_, descriptor.address, key.size(), key_buffer.data()));
Wyatt Heplerb7609542020-01-24 10:29:54 -0800418
Wyatt Heplere541e072020-02-14 09:10:53 -0800419 if (key == string_view(key_buffer.data(), key.size())) {
Wyatt Hepler5a33d8c2020-02-06 09:32:58 -0800420 DBG("Found match for key hash 0x%08" PRIx32, hash);
David Rogers2761aeb2020-01-31 17:09:00 -0800421 *result = &descriptor;
Wyatt Heplerb7609542020-01-24 10:29:54 -0800422 return Status::OK;
Wyatt Hepler2d401692020-02-13 16:01:23 -0800423 } else {
424 WRN("Found key hash collision for 0x%08" PRIx32, hash);
425 return Status::ALREADY_EXISTS;
Wyatt Heplerb7609542020-01-24 10:29:54 -0800426 }
Wyatt Heplerb7609542020-01-24 10:29:54 -0800427 }
428 }
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800429 return Status::NOT_FOUND;
430}
431
Wyatt Hepler2d401692020-02-13 16:01:23 -0800432// Searches for a KeyDescriptor that matches this key and sets *result to point
433// to it if one is found.
434//
435// OK: there is a matching descriptor and *result is set
436// NOT_FOUND: there is no descriptor that matches this key
437//
438Status KeyValueStore::FindExistingKeyDescriptor(
439 string_view key, const KeyDescriptor** result) const {
440 Status status = FindKeyDescriptor(key, result);
441
442 // If the key's hash collides with an existing key or if the key is deleted,
443 // treat it as if it is not in the KVS.
444 if (status == Status::ALREADY_EXISTS ||
445 (status.ok() && (*result)->deleted())) {
446 return Status::NOT_FOUND;
447 }
448 return status;
449}
450
David Rogers2761aeb2020-01-31 17:09:00 -0800451Status KeyValueStore::WriteEntryForExistingKey(KeyDescriptor* key_descriptor,
Wyatt Hepler5a33d8c2020-02-06 09:32:58 -0800452 KeyDescriptor::State new_state,
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800453 string_view key,
454 span<const byte> value) {
Wyatt Hepler5a33d8c2020-02-06 09:32:58 -0800455 // Find the original entry and sector to update the sector's valid_bytes.
Wyatt Hepler30a52152020-02-12 11:26:05 -0800456 Entry original_entry;
Wyatt Heplere541e072020-02-14 09:10:53 -0800457 TRY(Entry::Read(partition_, key_descriptor->address, &original_entry));
David Rogers3464d0a2020-02-07 11:45:46 -0800458 SectorDescriptor* old_sector = SectorFromAddress(key_descriptor->address);
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800459
David Rogers2761aeb2020-01-31 17:09:00 -0800460 SectorDescriptor* sector;
Wyatt Hepler5406a672020-02-18 15:42:38 -0800461 TRY(FindOrRecoverSectorWithSpace(&sector,
462 Entry::size(partition_, key, value)));
David Rogers8ce55cd2020-02-04 19:41:48 -0800463 DBG("Writing existing entry; found sector: %zu", SectorIndex(sector));
David Rogers3464d0a2020-02-07 11:45:46 -0800464
465 if (old_sector != SectorFromAddress(key_descriptor->address)) {
466 DBG("Sector for old entry (size %zu) was garbage collected. Old entry "
467 "relocated to sector %zu",
468 original_entry.size(),
469 SectorIndex(SectorFromAddress(key_descriptor->address)));
470
471 old_sector = SectorFromAddress(key_descriptor->address);
472 }
473
Wyatt Hepler5a33d8c2020-02-06 09:32:58 -0800474 TRY(AppendEntry(sector, key_descriptor, key, value, new_state));
475
David Rogers3464d0a2020-02-07 11:45:46 -0800476 old_sector->RemoveValidBytes(original_entry.size());
Wyatt Hepler5a33d8c2020-02-06 09:32:58 -0800477 return Status::OK;
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800478}
479
480Status KeyValueStore::WriteEntryForNewKey(string_view key,
481 span<const byte> value) {
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800482 if (key_descriptors_.full()) {
Keir Mierle8c352dc2020-02-02 13:58:19 -0800483 WRN("KVS full: trying to store a new entry, but can't. Have %zu entries",
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800484 key_descriptors_.size());
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800485 return Status::RESOURCE_EXHAUSTED;
486 }
487
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800488 // Create the KeyDescriptor that will be added to the list. The version and
489 // address will be set by AppendEntry.
490 KeyDescriptor key_descriptor(key, 0, 0);
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800491
David Rogers2761aeb2020-01-31 17:09:00 -0800492 SectorDescriptor* sector;
Wyatt Hepler5406a672020-02-18 15:42:38 -0800493 TRY(FindOrRecoverSectorWithSpace(&sector,
494 Entry::size(partition_, key, value)));
David Rogers8ce55cd2020-02-04 19:41:48 -0800495 DBG("Writing new entry; found sector: %zu", SectorIndex(sector));
Wyatt Hepler0af6ad92020-02-13 15:54:46 -0800496 TRY(AppendEntry(sector, &key_descriptor, key, value, KeyDescriptor::kValid));
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800497
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800498 // Only add the entry when we are certain the write succeeded.
499 key_descriptors_.push_back(key_descriptor);
Wyatt Heplerb7609542020-01-24 10:29:54 -0800500 return Status::OK;
501}
502
David Rogers2761aeb2020-01-31 17:09:00 -0800503Status KeyValueStore::RelocateEntry(KeyDescriptor& key_descriptor) {
David Rogersf0a35442020-02-04 12:16:38 -0800504 struct TempEntry {
Wyatt Heplere541e072020-02-14 09:10:53 -0800505 Entry::KeyBuffer key;
David Rogersf0a35442020-02-04 12:16:38 -0800506 std::array<char, sizeof(working_buffer_) - sizeof(key)> value;
507 };
Wyatt Heplere541e072020-02-14 09:10:53 -0800508 TempEntry* temp_entry = reinterpret_cast<TempEntry*>(working_buffer_.data());
David Rogersf0a35442020-02-04 12:16:38 -0800509
David Rogersdf025cd2020-02-06 17:05:34 -0800510 DBG("Relocating entry"); // TODO: add entry info to the log statement.
511
Wyatt Heplere541e072020-02-14 09:10:53 -0800512 // Read the entry to be relocated. Store the entry in a local variable and
David Rogersf0a35442020-02-04 12:16:38 -0800513 // store the key and value in the TempEntry stored in the static allocated
514 // working_buffer_.
Wyatt Heplere541e072020-02-14 09:10:53 -0800515 Entry entry;
516 TRY(Entry::Read(partition_, key_descriptor.address, &entry));
517 TRY_ASSIGN(size_t key_length, entry.ReadKey(temp_entry->key));
518 string_view key = string_view(temp_entry->key.data(), key_length);
519 auto result = entry.ReadValue(as_writable_bytes(span(temp_entry->value)));
David Rogersf0a35442020-02-04 12:16:38 -0800520 if (!result.status().ok()) {
521 return Status::INTERNAL;
522 }
523
Wyatt Heplere541e072020-02-14 09:10:53 -0800524 auto value = span(temp_entry->value.data(), result.size());
525 TRY(entry.VerifyChecksum(
David Rogersf0a35442020-02-04 12:16:38 -0800526 entry_header_format_.checksum, key, as_bytes(value)));
527
David Rogers3464d0a2020-02-07 11:45:46 -0800528 SectorDescriptor* old_sector = SectorFromAddress(key_descriptor.address);
David Rogersf0a35442020-02-04 12:16:38 -0800529
530 // Find a new sector for the entry and write it to the new location.
David Rogers8ce55cd2020-02-04 19:41:48 -0800531 SectorDescriptor* new_sector;
Wyatt Heplere541e072020-02-14 09:10:53 -0800532 TRY(FindSectorWithSpace(&new_sector, entry.size(), old_sector, true));
Wyatt Hepler0af6ad92020-02-13 15:54:46 -0800533 TRY(AppendEntry(
534 new_sector, &key_descriptor, key, as_bytes(value), key_descriptor.state));
David Rogersdf025cd2020-02-06 17:05:34 -0800535
536 // Do the valid bytes accounting for the sector the entry was relocated out
537 // of.
Wyatt Heplere541e072020-02-14 09:10:53 -0800538 old_sector->RemoveValidBytes(entry.size());
David Rogersdf025cd2020-02-06 17:05:34 -0800539
540 return Status::OK;
David Rogersa12786b2020-01-31 16:02:33 -0800541}
542
David Rogers8db5a722020-02-03 18:28:34 -0800543// Find either an existing sector with enough space that is not the sector to
544// skip, or an empty sector. Maintains the invariant that there is always at
545// least 1 empty sector unless set to bypass the rule.
Wyatt Hepler5a33d8c2020-02-06 09:32:58 -0800546Status KeyValueStore::FindSectorWithSpace(
547 SectorDescriptor** found_sector,
548 size_t size,
549 const SectorDescriptor* sector_to_skip,
550 bool bypass_empty_sector_rule) {
David Rogers8ce55cd2020-02-04 19:41:48 -0800551 // The last_new_sector_ is the sector that was last selected as the "new empty
552 // sector" to write to. This last new sector is used as the starting point for
553 // the next "find a new empty sector to write to" operation. By using the last
554 // new sector as the start point we will cycle which empty sector is selected
555 // next, spreading the wear across all the empty sectors and get a wear
556 // leveling benefit, rather than putting more wear on the lower number
557 // sectors.
558 //
559 // Locally use the sector index for ease of iterating through the sectors. For
560 // the persistent storage use SectorDescriptor* rather than sector index
561 // because SectorDescriptor* is the standard way to identify a sector.
562 size_t last_new_sector_index_ = SectorIndex(last_new_sector_);
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800563 size_t start = (last_new_sector_index_ + 1) % sectors_.size();
David Rogers2761aeb2020-01-31 17:09:00 -0800564 SectorDescriptor* first_empty_sector = nullptr;
David Rogers8db5a722020-02-03 18:28:34 -0800565 bool at_least_two_empty_sectors = bypass_empty_sector_rule;
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800566
David Rogers2e9e0c82020-02-13 15:06:06 -0800567 DBG("Find sector with %zu bytes available, starting with sector %zu",
568 size,
569 start);
David Rogers67f4b6c2020-02-06 16:17:09 -0800570 if (sector_to_skip != nullptr) {
571 DBG(" Skip sector %zu", SectorIndex(sector_to_skip));
572 }
573 if (bypass_empty_sector_rule) {
574 DBG(" Bypassing empty sector rule");
575 }
576
David Rogers8ce55cd2020-02-04 19:41:48 -0800577 // Look for a partial sector to use with enough space. Immediately use the
578 // first one of those that is found. While scanning for a partial sector, keep
579 // track of the first empty sector and if a second sector was seen.
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800580 for (size_t j = 0; j < sectors_.size(); j++) {
581 size_t i = (j + start) % sectors_.size();
582 SectorDescriptor& sector = sectors_[i];
Keir Mierle8c352dc2020-02-02 13:58:19 -0800583
David Rogers8db5a722020-02-03 18:28:34 -0800584 if (sector_to_skip == &sector) {
David Rogers67f4b6c2020-02-06 16:17:09 -0800585 DBG(" Skipping the skip sector %zu", i);
David Rogers8db5a722020-02-03 18:28:34 -0800586 continue;
587 }
588
David Rogers67f4b6c2020-02-06 16:17:09 -0800589 DBG(" Examining sector %zu with %hu bytes available",
590 i,
591 sector.tail_free_bytes);
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800592 if (!SectorEmpty(sector) && sector.HasSpace(size)) {
David Rogers67f4b6c2020-02-06 16:17:09 -0800593 DBG(" Partially occupied sector %zu with enough space; done!", i);
David Rogers8ce55cd2020-02-04 19:41:48 -0800594 *found_sector = &sector;
595 return Status::OK;
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800596 }
597
598 if (SectorEmpty(sector)) {
599 if (first_empty_sector == nullptr) {
600 first_empty_sector = &sector;
601 } else {
602 at_least_two_empty_sectors = true;
Wyatt Hepler2ad60672020-01-21 08:00:16 -0800603 }
Wyatt Heplerb7609542020-01-24 10:29:54 -0800604 }
605 }
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800606
David Rogers8ce55cd2020-02-04 19:41:48 -0800607 // If the scan for a partial sector does not find a suitable sector, use the
608 // first empty sector that was found. Normally it is required to keep 1 empty
609 // sector after the sector found here, but that rule can be bypassed in
610 // special circumstances (such as during garbage collection).
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800611 if (at_least_two_empty_sectors) {
David Rogers67f4b6c2020-02-06 16:17:09 -0800612 DBG(" Found a usable empty sector; returning the first found (%zu)",
David Rogers8ce55cd2020-02-04 19:41:48 -0800613 SectorIndex(first_empty_sector));
614 last_new_sector_ = first_empty_sector;
615 *found_sector = first_empty_sector;
616 return Status::OK;
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800617 }
David Rogers8ce55cd2020-02-04 19:41:48 -0800618
619 // No sector was found.
David Rogers67f4b6c2020-02-06 16:17:09 -0800620 DBG(" Unable to find a usable sector");
David Rogers8ce55cd2020-02-04 19:41:48 -0800621 *found_sector = nullptr;
622 return Status::RESOURCE_EXHAUSTED;
Wyatt Heplerb7609542020-01-24 10:29:54 -0800623}
624
David Rogers2761aeb2020-01-31 17:09:00 -0800625Status KeyValueStore::FindOrRecoverSectorWithSpace(SectorDescriptor** sector,
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800626 size_t size) {
David Rogers8ce55cd2020-02-04 19:41:48 -0800627 Status result = FindSectorWithSpace(sector, size);
Wyatt Hepler2d401692020-02-13 16:01:23 -0800628 if (result == Status::RESOURCE_EXHAUSTED && options_.partial_gc_on_write) {
David Rogers1541d612020-02-06 23:47:02 -0800629 // Garbage collect and then try again to find the best sector.
630 TRY(GarbageCollectOneSector());
631 return FindSectorWithSpace(sector, size);
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800632 }
David Rogers8ce55cd2020-02-04 19:41:48 -0800633 return result;
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800634}
635
David Rogers2761aeb2020-01-31 17:09:00 -0800636KeyValueStore::SectorDescriptor* KeyValueStore::FindSectorToGarbageCollect() {
637 SectorDescriptor* sector_candidate = nullptr;
David Rogersa12786b2020-01-31 16:02:33 -0800638 size_t candidate_bytes = 0;
639
640 // Step 1: Try to find a sectors with stale keys and no valid keys (no
641 // relocation needed). If any such sectors are found, use the sector with the
642 // most reclaimable bytes.
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800643 for (auto& sector : sectors_) {
David Rogersa12786b2020-01-31 16:02:33 -0800644 if ((sector.valid_bytes == 0) &&
645 (RecoverableBytes(sector) > candidate_bytes)) {
646 sector_candidate = &sector;
647 candidate_bytes = RecoverableBytes(sector);
648 }
649 }
650
651 // Step 2: If step 1 yields no sectors, just find the sector with the most
652 // reclaimable bytes.
653 if (sector_candidate == nullptr) {
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800654 for (auto& sector : sectors_) {
David Rogersa12786b2020-01-31 16:02:33 -0800655 if (RecoverableBytes(sector) > candidate_bytes) {
656 sector_candidate = &sector;
657 candidate_bytes = RecoverableBytes(sector);
658 }
659 }
660 }
661
David Rogers5981f312020-02-13 13:33:56 -0800662 if (sector_candidate != nullptr) {
663 DBG("Found sector %zu to Garbage Collect, %zu recoverable bytes",
664 SectorIndex(sector_candidate),
665 RecoverableBytes(*sector_candidate));
666 } else {
667 DBG("Unable to find sector to garbage collect!");
668 }
David Rogersa12786b2020-01-31 16:02:33 -0800669 return sector_candidate;
670}
671
David Rogers1541d612020-02-06 23:47:02 -0800672Status KeyValueStore::GarbageCollectOneSector() {
David Rogers67f4b6c2020-02-06 16:17:09 -0800673 DBG("Garbage Collect a single sector");
674
David Rogersa12786b2020-01-31 16:02:33 -0800675 // Step 1: Find the sector to garbage collect
David Rogers2761aeb2020-01-31 17:09:00 -0800676 SectorDescriptor* sector_to_gc = FindSectorToGarbageCollect();
David Rogers3464d0a2020-02-07 11:45:46 -0800677 LogSectors();
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800678
David Rogersa12786b2020-01-31 16:02:33 -0800679 if (sector_to_gc == nullptr) {
680 return Status::RESOURCE_EXHAUSTED;
681 }
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800682
David Rogersa12786b2020-01-31 16:02:33 -0800683 // Step 2: Move any valid entries in the GC sector to other sectors
684 if (sector_to_gc->valid_bytes != 0) {
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800685 for (auto& descriptor : key_descriptors_) {
David Rogers2761aeb2020-01-31 17:09:00 -0800686 if (AddressInSector(*sector_to_gc, descriptor.address)) {
David Rogers67f4b6c2020-02-06 16:17:09 -0800687 DBG(" Relocate entry");
David Rogers2761aeb2020-01-31 17:09:00 -0800688 TRY(RelocateEntry(descriptor));
David Rogersa12786b2020-01-31 16:02:33 -0800689 }
Wyatt Heplerb7609542020-01-24 10:29:54 -0800690 }
691 }
Wyatt Heplerb7609542020-01-24 10:29:54 -0800692
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800693 if (sector_to_gc->valid_bytes != 0) {
David Rogers67f4b6c2020-02-06 16:17:09 -0800694 ERR(" Failed to relocate valid entries from sector being garbage "
695 "collected, %hu valid bytes remain",
696 sector_to_gc->valid_bytes);
Wyatt Heplerb7609542020-01-24 10:29:54 -0800697 return Status::INTERNAL;
698 }
699
David Rogersa12786b2020-01-31 16:02:33 -0800700 // Step 3: Reinitialize the sector
701 sector_to_gc->tail_free_bytes = 0;
702 TRY(partition_.Erase(SectorBaseAddress(sector_to_gc), 1));
703 sector_to_gc->tail_free_bytes = partition_.sector_size_bytes();
Wyatt Heplerb7609542020-01-24 10:29:54 -0800704
David Rogers67f4b6c2020-02-06 16:17:09 -0800705 DBG(" Garbage Collect complete");
David Rogers50185ad2020-02-07 00:02:46 -0800706 LogSectors();
David Rogersa12786b2020-01-31 16:02:33 -0800707 return Status::OK;
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800708}
709
David Rogers2761aeb2020-01-31 17:09:00 -0800710Status KeyValueStore::AppendEntry(SectorDescriptor* sector,
711 KeyDescriptor* key_descriptor,
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800712 const string_view key,
Wyatt Hepler5a33d8c2020-02-06 09:32:58 -0800713 span<const byte> value,
714 KeyDescriptor::State new_state) {
Wyatt Heplere541e072020-02-14 09:10:53 -0800715 const Address address = NextWritableAddress(sector);
716 DBG("Appending to address: %#zx", size_t(address));
717
718 Entry entry;
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800719
Wyatt Hepler5a33d8c2020-02-06 09:32:58 -0800720 if (new_state == KeyDescriptor::kDeleted) {
Wyatt Heplere541e072020-02-14 09:10:53 -0800721 entry = Entry::Tombstone(partition_,
722 address,
723 entry_header_format_.magic,
724 entry_header_format_.checksum,
725 key,
726 partition_.alignment_bytes(),
727 key_descriptor->key_version + 1);
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800728 } else {
Wyatt Heplere541e072020-02-14 09:10:53 -0800729 entry = Entry::Valid(partition_,
730 address,
731 entry_header_format_.magic,
732 entry_header_format_.checksum,
733 key,
734 value,
735 partition_.alignment_bytes(),
736 key_descriptor->key_version + 1);
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800737 }
738
Wyatt Hepler97fc7942020-02-06 15:55:45 -0800739 DBG("Appending %zu B entry with key version: %x",
Wyatt Heplere541e072020-02-14 09:10:53 -0800740 entry.size(),
741 unsigned(entry.key_version()));
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800742
Wyatt Heplere541e072020-02-14 09:10:53 -0800743 TRY_ASSIGN(const size_t written, entry.Write(key, value));
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800744
745 if (options_.verify_on_write) {
Wyatt Heplere541e072020-02-14 09:10:53 -0800746 TRY(entry.VerifyChecksumInFlash(entry_header_format_.checksum));
Wyatt Heplerb7609542020-01-24 10:29:54 -0800747 }
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800748
David Rogers2761aeb2020-01-31 17:09:00 -0800749 key_descriptor->address = address;
Wyatt Heplere541e072020-02-14 09:10:53 -0800750 key_descriptor->key_version = entry.key_version();
Wyatt Hepler5a33d8c2020-02-06 09:32:58 -0800751 key_descriptor->state = new_state;
752
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800753 sector->valid_bytes += written;
David Rogers2be76b02020-02-06 17:33:05 -0800754 sector->RemoveFreeBytes(written);
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800755 return Status::OK;
Wyatt Heplerb7609542020-01-24 10:29:54 -0800756}
757
Keir Mierle8c352dc2020-02-02 13:58:19 -0800758void KeyValueStore::LogDebugInfo() {
Keir Mierle8c352dc2020-02-02 13:58:19 -0800759 const size_t sector_size_bytes = partition_.sector_size_bytes();
760 DBG("====================== KEY VALUE STORE DUMP =========================");
761 DBG(" ");
762 DBG("Flash partition:");
Wyatt Heplerad0a7932020-02-06 08:20:38 -0800763 DBG(" Sector count = %zu", partition_.sector_count());
764 DBG(" Sector max count = %zu", kMaxUsableSectors);
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800765 DBG(" Sectors in use = %zu", sectors_.size());
Keir Mierle8c352dc2020-02-02 13:58:19 -0800766 DBG(" Sector size = %zu", sector_size_bytes);
767 DBG(" Total size = %zu", partition_.size_bytes());
768 DBG(" Alignment = %zu", partition_.alignment_bytes());
769 DBG(" ");
770 DBG("Key descriptors:");
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800771 DBG(" Entry count = %zu", key_descriptors_.size());
Keir Mierle8c352dc2020-02-02 13:58:19 -0800772 DBG(" Max entry count = %zu", kMaxEntries);
773 DBG(" ");
774 DBG(" # hash version address address (hex)");
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800775 for (size_t i = 0; i < key_descriptors_.size(); ++i) {
776 const KeyDescriptor& kd = key_descriptors_[i];
Keir Mierle8c352dc2020-02-02 13:58:19 -0800777 DBG(" |%3zu: | %8zx |%8zu | %8zu | %8zx",
778 i,
779 size_t(kd.key_hash),
780 size_t(kd.key_version),
781 size_t(kd.address),
782 size_t(kd.address));
783 }
784 DBG(" ");
785
786 DBG("Sector descriptors:");
787 DBG(" # tail free valid has_space");
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800788 for (size_t sector_id = 0; sector_id < sectors_.size(); ++sector_id) {
789 const SectorDescriptor& sd = sectors_[sector_id];
Keir Mierle8c352dc2020-02-02 13:58:19 -0800790 DBG(" |%3zu: | %8zu |%8zu | %s",
791 sector_id,
792 size_t(sd.tail_free_bytes),
793 size_t(sd.valid_bytes),
794 sd.tail_free_bytes ? "YES" : "");
795 }
796 DBG(" ");
797
798 // TODO: This should stop logging after some threshold.
799 // size_t dumped_bytes = 0;
800 DBG("Sector raw data:");
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800801 for (size_t sector_id = 0; sector_id < sectors_.size(); ++sector_id) {
Keir Mierle8c352dc2020-02-02 13:58:19 -0800802 // Read sector data. Yes, this will blow the stack on embedded.
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800803 std::array<byte, 500> raw_sector_data; // TODO!!!
Keir Mierle8c352dc2020-02-02 13:58:19 -0800804 StatusWithSize sws =
805 partition_.Read(sector_id * sector_size_bytes, raw_sector_data);
806 DBG("Read: %zu bytes", sws.size());
807
808 DBG(" base addr offs 0 1 2 3 4 5 6 7");
809 for (size_t i = 0; i < sector_size_bytes; i += 8) {
810 DBG(" %3zu %8zx %5zu | %02x %02x %02x %02x %02x %02x %02x %02x",
811 sector_id,
812 (sector_id * sector_size_bytes) + i,
813 i,
814 static_cast<unsigned int>(raw_sector_data[i + 0]),
815 static_cast<unsigned int>(raw_sector_data[i + 1]),
816 static_cast<unsigned int>(raw_sector_data[i + 2]),
817 static_cast<unsigned int>(raw_sector_data[i + 3]),
818 static_cast<unsigned int>(raw_sector_data[i + 4]),
819 static_cast<unsigned int>(raw_sector_data[i + 5]),
820 static_cast<unsigned int>(raw_sector_data[i + 6]),
821 static_cast<unsigned int>(raw_sector_data[i + 7]));
822
823 // TODO: Fix exit condition.
824 if (i > 128) {
825 break;
826 }
827 }
828 DBG(" ");
829 }
830
831 DBG("////////////////////// KEY VALUE STORE DUMP END /////////////////////");
832}
833
David Rogerscf680ab2020-02-12 23:28:32 -0800834void KeyValueStore::LogSectors() const {
835 DBG("Sector descriptors: count %zu", sectors_.size());
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800836 for (auto& sector : sectors_) {
David Rogers50185ad2020-02-07 00:02:46 -0800837 DBG(" - Sector %zu: valid %hu, recoverable %zu, free %hu",
838 SectorIndex(&sector),
839 sector.valid_bytes,
840 RecoverableBytes(sector),
841 sector.tail_free_bytes);
842 }
843}
844
David Rogerscf680ab2020-02-12 23:28:32 -0800845void KeyValueStore::LogKeyDescriptor() const {
846 DBG("Key descriptors: count %zu", key_descriptors_.size());
847 for (auto& key : key_descriptors_) {
848 DBG(" - Key: %s, hash %#zx, version %zu, address %#zx",
849 key.deleted() ? "Deleted" : "Valid",
850 static_cast<size_t>(key.key_hash),
851 static_cast<size_t>(key.key_version),
852 static_cast<size_t>(key.address));
853 }
854}
855
David Rogers3464d0a2020-02-07 11:45:46 -0800856void KeyValueStore::SectorDescriptor::RemoveValidBytes(size_t size) {
857 // TODO: add safety check for valid_bytes > size.
858 if (size > valid_bytes) {
David Rogers2e9e0c82020-02-13 15:06:06 -0800859 ERR("Trying to remove too many valid bytes, remove %zu, only have %hu",
David Rogers3464d0a2020-02-07 11:45:46 -0800860 size,
861 valid_bytes);
862 valid_bytes = size;
863 }
864 valid_bytes -= size;
865}
866
Wyatt Hepler2ad60672020-01-21 08:00:16 -0800867} // namespace pw::kvs