blob: 5ae647b58cab29137bd8e900a51003df006c374e [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 Hepler2c7eca02020-02-18 16:01:42 -080081 Address sector_address = 0;
Keir Mierle8c352dc2020-02-02 13:58:19 -080082
Wyatt Hepler2c7eca02020-02-18 16:01:42 -080083 for (SectorDescriptor& sector : sectors_) {
84 // Reset the sector's valid and writable byte counts. These will be updated
85 // after reading each entry.
86 sector.Reset(sector_size_bytes);
Keir Mierle8c352dc2020-02-02 13:58:19 -080087 Address entry_address = sector_address;
88
Wyatt Hepler2c7eca02020-02-18 16:01:42 -080089 for (int num_entries_in_sector = 0; true; num_entries_in_sector++) {
90 DBG("Load entry: sector=%" PRIx32 ", entry#=%d, address=%" PRIx32,
91 sector_address,
Keir Mierle8c352dc2020-02-02 13:58:19 -080092 num_entries_in_sector,
Wyatt Hepler2c7eca02020-02-18 16:01:42 -080093 entry_address);
Keir Mierle8c352dc2020-02-02 13:58:19 -080094
Wyatt Hepler2c7eca02020-02-18 16:01:42 -080095 if (!AddressInSector(sector, entry_address)) {
Keir Mierle8c352dc2020-02-02 13:58:19 -080096 DBG("Fell off end of sector; moving to the next sector");
97 break;
98 }
99
100 Address next_entry_address;
101 Status status = LoadEntry(entry_address, &next_entry_address);
102 if (status == Status::NOT_FOUND) {
103 DBG("Hit un-written data in sector; moving to the next sector");
104 break;
105 }
106 if (status == Status::DATA_LOSS) {
107 // It's not clear KVS can make a unilateral decision about what to do
108 // in corruption cases. It's an application decision, for which we
109 // should offer some configurability. For now, entirely bail out of
110 // loading and give up.
111 //
112 // Later, scan for remaining valid keys; since it's entirely possible
113 // that there is a duplicate of the key elsewhere and everything is
114 // fine. Later, we can wipe and maybe recover the sector.
115 //
116 // TODO: Implement rest-of-sector scanning for valid entries.
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800117 ERR("KVS init failed: data loss detected in sector %u at address %zu",
118 SectorIndex(&sector),
119 size_t(entry_address));
Keir Mierle8c352dc2020-02-02 13:58:19 -0800120 return Status::DATA_LOSS;
121 }
122 TRY(status);
123
124 // Entry loaded successfully; so get ready to load the next one.
125 entry_address = next_entry_address;
126
127 // Update of the number of writable bytes in this sector.
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800128 sector.set_writable_bytes(sector_size_bytes -
129 (entry_address - sector_address));
Keir Mierle8c352dc2020-02-02 13:58:19 -0800130 }
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800131
132 sector_address += sector_size_bytes;
Keir Mierle8c352dc2020-02-02 13:58:19 -0800133 }
134
135 DBG("Second pass: Count valid bytes in each sector");
Keir Mierle8c352dc2020-02-02 13:58:19 -0800136 // For every valid key, increment the valid bytes for that sector.
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800137 for (KeyDescriptor& key_descriptor : key_descriptors_) {
Wyatt Heplere541e072020-02-14 09:10:53 -0800138 Entry entry;
139 TRY(Entry::Read(partition_, key_descriptor.address, &entry));
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800140 SectorFromAddress(key_descriptor.address)->AddValidBytes(entry.size());
Keir Mierle8c352dc2020-02-02 13:58:19 -0800141 }
Wyatt Hepler729f28c2020-02-05 09:46:00 -0800142 initialized_ = true;
David Rogers2e9e0c82020-02-13 15:06:06 -0800143
Armando Montanez5464d5f2020-02-20 10:12:20 -0800144 INF("KeyValueStore init complete: active keys %zu, deleted keys %zu, sectors "
David Rogers2e9e0c82020-02-13 15:06:06 -0800145 "%zu, logical sector size %zu bytes",
146 size(),
147 (key_descriptors_.size() - size()),
148 sectors_.size(),
149 partition_.sector_size_bytes());
150
Keir Mierle8c352dc2020-02-02 13:58:19 -0800151 return Status::OK;
152}
153
154Status KeyValueStore::LoadEntry(Address entry_address,
155 Address* next_entry_address) {
Wyatt Heplere541e072020-02-14 09:10:53 -0800156 Entry entry;
157 TRY(Entry::Read(partition_, entry_address, &entry));
Keir Mierle8c352dc2020-02-02 13:58:19 -0800158
159 // TODO: Handle multiple magics for formats that have changed.
Wyatt Heplere541e072020-02-14 09:10:53 -0800160 if (entry.magic() != entry_header_format_.magic) {
Keir Mierle8c352dc2020-02-02 13:58:19 -0800161 // TODO: It may be cleaner to have some logging helpers for these cases.
Wyatt Heplere541e072020-02-14 09:10:53 -0800162 ERR("Found corrupt magic: %zx; expecting %zx; at address %zx",
163 size_t(entry.magic()),
Keir Mierle8c352dc2020-02-02 13:58:19 -0800164 size_t(entry_header_format_.magic),
165 size_t(entry_address));
166 return Status::DATA_LOSS;
167 }
168
169 // Read the key from flash & validate the entry (which reads the value).
Wyatt Heplera00d1ef2020-02-14 14:31:26 -0800170 Entry::KeyBuffer key_buffer;
Wyatt Heplere541e072020-02-14 09:10:53 -0800171 TRY_ASSIGN(size_t key_length, entry.ReadKey(key_buffer));
172 const string_view key(key_buffer.data(), key_length);
Wyatt Heplerbab0e202020-02-04 07:40:08 -0800173
Wyatt Heplere541e072020-02-14 09:10:53 -0800174 TRY(entry.VerifyChecksumInFlash(entry_header_format_.checksum));
Wyatt Hepler4d78cd62020-02-05 13:05:58 -0800175
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800176 KeyDescriptor key_descriptor(
177 key,
Wyatt Heplere541e072020-02-14 09:10:53 -0800178 entry.key_version(),
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800179 entry_address,
Wyatt Heplere541e072020-02-14 09:10:53 -0800180 entry.deleted() ? KeyDescriptor::kDeleted : KeyDescriptor::kValid);
Keir Mierle8c352dc2020-02-02 13:58:19 -0800181
182 DBG("Key hash: %zx (%zu)",
183 size_t(key_descriptor.key_hash),
184 size_t(key_descriptor.key_hash));
185
186 TRY(AppendNewOrOverwriteStaleExistingDescriptor(key_descriptor));
187
Wyatt Heplere541e072020-02-14 09:10:53 -0800188 *next_entry_address = entry.next_address();
Keir Mierle8c352dc2020-02-02 13:58:19 -0800189 return Status::OK;
190}
191
192// TODO: This method is the trigger of the O(valid_entries * all_entries) time
193// complexity for reading. At some cost to memory, this could be optimized by
194// using a hash table instead of scanning, but in practice this should be fine
195// for a small number of keys
196Status KeyValueStore::AppendNewOrOverwriteStaleExistingDescriptor(
197 const KeyDescriptor& key_descriptor) {
198 // With the new key descriptor, either add it to the descriptor table or
199 // overwrite an existing entry with an older version of the key.
200 KeyDescriptor* existing_descriptor = FindDescriptor(key_descriptor.key_hash);
Keir Mierle8c352dc2020-02-02 13:58:19 -0800201
Wyatt Hepler5406a672020-02-18 15:42:38 -0800202 // Write a new entry.
203 if (existing_descriptor == nullptr) {
204 if (key_descriptors_.full()) {
205 return Status::RESOURCE_EXHAUSTED;
206 }
207 key_descriptors_.push_back(key_descriptor);
208 } else if (existing_descriptor->key_version < key_descriptor.key_version) {
209 // Existing entry is old; replace the existing entry with the new one.
210 *existing_descriptor = key_descriptor;
211 } else {
212 // Otherwise, check for data integrity and leave the existing entry.
213 if (existing_descriptor->key_version == key_descriptor.key_version) {
214 ERR("Data loss: Duplicated old(=%zu) and new(=%zu) version",
215 size_t(existing_descriptor->key_version),
216 size_t(key_descriptor.key_version));
217 return Status::DATA_LOSS;
218 }
219 DBG("Found stale entry when appending; ignoring");
Keir Mierle8c352dc2020-02-02 13:58:19 -0800220 }
Keir Mierle8c352dc2020-02-02 13:58:19 -0800221 return Status::OK;
222}
223
Keir Mierle8c352dc2020-02-02 13:58:19 -0800224KeyValueStore::KeyDescriptor* KeyValueStore::FindDescriptor(uint32_t hash) {
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800225 for (KeyDescriptor& key_descriptor : key_descriptors_) {
226 if (key_descriptor.key_hash == hash) {
227 return &key_descriptor;
Keir Mierle8c352dc2020-02-02 13:58:19 -0800228 }
229 }
230 return nullptr;
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800231}
232
233StatusWithSize KeyValueStore::Get(string_view key,
Wyatt Hepler5f6efc02020-02-18 16:54:31 -0800234 span<byte> value_buffer,
235 size_t offset_bytes) const {
Wyatt Hepler50f70772020-02-13 11:25:10 -0800236 TRY_WITH_SIZE(CheckOperation(key));
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800237
David Rogers2761aeb2020-01-31 17:09:00 -0800238 const KeyDescriptor* key_descriptor;
Wyatt Hepler2d401692020-02-13 16:01:23 -0800239 TRY_WITH_SIZE(FindExistingKeyDescriptor(key, &key_descriptor));
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800240
Wyatt Heplere541e072020-02-14 09:10:53 -0800241 Entry entry;
242 TRY_WITH_SIZE(Entry::Read(partition_, key_descriptor->address, &entry));
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800243
Wyatt Hepler5f6efc02020-02-18 16:54:31 -0800244 StatusWithSize result = entry.ReadValue(value_buffer, offset_bytes);
245 if (result.ok() && options_.verify_on_read && offset_bytes == 0u) {
David Rogerscf680ab2020-02-12 23:28:32 -0800246 Status verify_result =
Wyatt Heplere541e072020-02-14 09:10:53 -0800247 entry.VerifyChecksum(entry_header_format_.checksum,
248 key,
249 value_buffer.subspan(0, result.size()));
David Rogerscf680ab2020-02-12 23:28:32 -0800250 if (!verify_result.ok()) {
Wyatt Hepler50f70772020-02-13 11:25:10 -0800251 std::memset(
252 value_buffer.subspan(0, result.size()).data(), 0, result.size());
253 return StatusWithSize(verify_result);
David Rogerscf680ab2020-02-12 23:28:32 -0800254 }
255
256 return StatusWithSize(verify_result, result.size());
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800257 }
258 return result;
259}
260
261Status KeyValueStore::Put(string_view key, span<const byte> value) {
Keir Mierle8c352dc2020-02-02 13:58:19 -0800262 DBG("Writing key/value; key length=%zu, value length=%zu",
263 key.size(),
264 value.size());
Wyatt Hepler729f28c2020-02-05 09:46:00 -0800265
266 TRY(CheckOperation(key));
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800267
Wyatt Hepler5406a672020-02-18 15:42:38 -0800268 if (Entry::size(partition_, key, value) > partition_.sector_size_bytes()) {
269 DBG("%zu B value with %zu B key cannot fit in one sector",
270 value.size(),
271 key.size());
272 return Status::INVALID_ARGUMENT;
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800273 }
274
David Rogers2761aeb2020-01-31 17:09:00 -0800275 KeyDescriptor* key_descriptor;
Wyatt Hepler2d401692020-02-13 16:01:23 -0800276 Status status = FindKeyDescriptor(key, &key_descriptor);
277
278 if (status.ok()) {
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800279 DBG("Overwriting entry for key %#08" PRIx32 " in sector %u",
David Rogers3464d0a2020-02-07 11:45:46 -0800280 key_descriptor->key_hash,
281 SectorIndex(SectorFromAddress(key_descriptor->address)));
Wyatt Hepler5a33d8c2020-02-06 09:32:58 -0800282 return WriteEntryForExistingKey(
283 key_descriptor, KeyDescriptor::kValid, key, value);
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800284 }
David Rogers2761aeb2020-01-31 17:09:00 -0800285
Wyatt Hepler2d401692020-02-13 16:01:23 -0800286 if (status == Status::NOT_FOUND) {
287 return WriteEntryForNewKey(key, value);
288 }
289
290 return status;
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800291}
292
293Status KeyValueStore::Delete(string_view key) {
Wyatt Hepler729f28c2020-02-05 09:46:00 -0800294 TRY(CheckOperation(key));
295
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800296 KeyDescriptor* key_descriptor;
Wyatt Hepler2d401692020-02-13 16:01:23 -0800297 TRY(FindExistingKeyDescriptor(key, &key_descriptor));
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800298
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800299 DBG("Writing tombstone for key %#08" PRIx32 " in sector %u",
David Rogers3464d0a2020-02-07 11:45:46 -0800300 key_descriptor->key_hash,
301 SectorIndex(SectorFromAddress(key_descriptor->address)));
Wyatt Hepler5a33d8c2020-02-06 09:32:58 -0800302 return WriteEntryForExistingKey(
303 key_descriptor, KeyDescriptor::kDeleted, key, {});
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800304}
305
306KeyValueStore::iterator& KeyValueStore::iterator::operator++() {
307 // Skip to the next entry that is valid (not deleted).
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800308 while (++index_ < item_.kvs_.key_descriptors_.size() &&
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800309 descriptor().deleted()) {
310 }
311 return *this;
312}
313
314const KeyValueStore::Item& KeyValueStore::iterator::operator*() {
315 std::memset(item_.key_buffer_.data(), 0, item_.key_buffer_.size());
316
Wyatt Heplere541e072020-02-14 09:10:53 -0800317 Entry entry;
318 if (Entry::Read(item_.kvs_.partition_, descriptor().address, &entry).ok()) {
319 entry.ReadKey(item_.key_buffer_);
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800320 }
321
322 return item_;
323}
324
325KeyValueStore::iterator KeyValueStore::begin() const {
326 size_t i = 0;
327 // Skip over any deleted entries at the start of the descriptor list.
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800328 while (i < key_descriptors_.size() && key_descriptors_[i].deleted()) {
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800329 i += 1;
330 }
331 return iterator(*this, i);
332}
333
334// TODO(hepler): The valid entry count could be tracked in the KVS to avoid the
335// need for this for-loop.
336size_t KeyValueStore::size() const {
337 size_t valid_entries = 0;
338
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800339 for (const KeyDescriptor& key_descriptor : key_descriptors_) {
340 if (!key_descriptor.deleted()) {
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800341 valid_entries += 1;
342 }
343 }
344
345 return valid_entries;
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800346}
347
Wyatt Heplered163b02020-02-03 17:49:32 -0800348StatusWithSize KeyValueStore::ValueSize(std::string_view key) const {
Wyatt Hepler50f70772020-02-13 11:25:10 -0800349 TRY_WITH_SIZE(CheckOperation(key));
Wyatt Heplered163b02020-02-03 17:49:32 -0800350
351 const KeyDescriptor* key_descriptor;
Wyatt Hepler2d401692020-02-13 16:01:23 -0800352 TRY_WITH_SIZE(FindExistingKeyDescriptor(key, &key_descriptor));
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800353
Wyatt Heplere541e072020-02-14 09:10:53 -0800354 Entry entry;
355 TRY_WITH_SIZE(Entry::Read(partition_, key_descriptor->address, &entry));
Wyatt Heplered163b02020-02-03 17:49:32 -0800356
Wyatt Heplere541e072020-02-14 09:10:53 -0800357 return StatusWithSize(entry.value_size());
Wyatt Heplered163b02020-02-03 17:49:32 -0800358}
359
Wyatt Hepler4d78cd62020-02-05 13:05:58 -0800360uint32_t KeyValueStore::HashKey(string_view string) {
361 uint32_t hash = 0;
362 uint32_t coefficient = 65599u;
363
364 for (char ch : string) {
365 hash += coefficient * unsigned(ch);
366 coefficient *= 65599u;
367 }
368
369 return hash;
370}
371
Wyatt Hepler6e3a83b2020-02-04 07:36:45 -0800372Status KeyValueStore::FixedSizeGet(std::string_view key,
373 byte* value,
374 size_t size_bytes) const {
375 // Ensure that the size of the stored value matches the size of the type.
376 // Otherwise, report error. This check avoids potential memory corruption.
377 StatusWithSize result = ValueSize(key);
378 if (!result.ok()) {
379 return result.status();
Keir Mierle8c352dc2020-02-02 13:58:19 -0800380 }
Wyatt Hepler6e3a83b2020-02-04 07:36:45 -0800381 if (result.size() != size_bytes) {
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800382 DBG("Requested %zu B read, but value is %zu B", size_bytes, result.size());
Wyatt Hepler6e3a83b2020-02-04 07:36:45 -0800383 return Status::INVALID_ARGUMENT;
Wyatt Heplerbab0e202020-02-04 07:40:08 -0800384 }
Wyatt Hepler6e3a83b2020-02-04 07:36:45 -0800385 return Get(key, span(value, size_bytes)).status();
Keir Mierle8c352dc2020-02-02 13:58:19 -0800386}
387
Wyatt Hepler729f28c2020-02-05 09:46:00 -0800388Status KeyValueStore::CheckOperation(string_view key) const {
Wyatt Hepleracaacf92020-01-24 10:58:30 -0800389 if (InvalidKey(key)) {
Wyatt Heplerb7609542020-01-24 10:29:54 -0800390 return Status::INVALID_ARGUMENT;
391 }
Wyatt Hepler729f28c2020-02-05 09:46:00 -0800392 if (!initialized_) {
Wyatt Heplerb7609542020-01-24 10:29:54 -0800393 return Status::FAILED_PRECONDITION;
394 }
Wyatt Heplerb7609542020-01-24 10:29:54 -0800395 return Status::OK;
396}
397
Wyatt Hepler2d401692020-02-13 16:01:23 -0800398// Searches for a KeyDescriptor that matches this key and sets *result to point
399// to it if one is found.
400//
401// OK: there is a matching descriptor and *result is set
402// NOT_FOUND: there is no descriptor that matches this key, but this key
403// has a unique hash (and could potentially be added to the KVS)
404// ALREADY_EXISTS: there is no descriptor that matches this key, but the
405// key's hash collides with the hash for an existing descriptor
406//
David Rogers2761aeb2020-01-31 17:09:00 -0800407Status KeyValueStore::FindKeyDescriptor(string_view key,
408 const KeyDescriptor** result) const {
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800409 const uint32_t hash = HashKey(key);
Wyatt Heplera00d1ef2020-02-14 14:31:26 -0800410 Entry::KeyBuffer key_buffer;
Wyatt Heplerb7609542020-01-24 10:29:54 -0800411
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800412 for (auto& descriptor : key_descriptors_) {
David Rogers2761aeb2020-01-31 17:09:00 -0800413 if (descriptor.key_hash == hash) {
Wyatt Heplere541e072020-02-14 09:10:53 -0800414 TRY(Entry::ReadKey(
Wyatt Heplera00d1ef2020-02-14 14:31:26 -0800415 partition_, descriptor.address, key.size(), key_buffer.data()));
Wyatt Heplerb7609542020-01-24 10:29:54 -0800416
Wyatt Heplere541e072020-02-14 09:10:53 -0800417 if (key == string_view(key_buffer.data(), key.size())) {
Wyatt Hepler5a33d8c2020-02-06 09:32:58 -0800418 DBG("Found match for key hash 0x%08" PRIx32, hash);
David Rogers2761aeb2020-01-31 17:09:00 -0800419 *result = &descriptor;
Wyatt Heplerb7609542020-01-24 10:29:54 -0800420 return Status::OK;
Wyatt Hepler2d401692020-02-13 16:01:23 -0800421 } else {
422 WRN("Found key hash collision for 0x%08" PRIx32, hash);
423 return Status::ALREADY_EXISTS;
Wyatt Heplerb7609542020-01-24 10:29:54 -0800424 }
Wyatt Heplerb7609542020-01-24 10:29:54 -0800425 }
426 }
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800427 return Status::NOT_FOUND;
428}
429
Wyatt Hepler2d401692020-02-13 16:01:23 -0800430// Searches for a KeyDescriptor that matches this key and sets *result to point
431// to it if one is found.
432//
433// OK: there is a matching descriptor and *result is set
434// NOT_FOUND: there is no descriptor that matches this key
435//
436Status KeyValueStore::FindExistingKeyDescriptor(
437 string_view key, const KeyDescriptor** result) const {
438 Status status = FindKeyDescriptor(key, result);
439
440 // If the key's hash collides with an existing key or if the key is deleted,
441 // treat it as if it is not in the KVS.
442 if (status == Status::ALREADY_EXISTS ||
443 (status.ok() && (*result)->deleted())) {
444 return Status::NOT_FOUND;
445 }
446 return status;
447}
448
David Rogers2761aeb2020-01-31 17:09:00 -0800449Status KeyValueStore::WriteEntryForExistingKey(KeyDescriptor* key_descriptor,
Wyatt Hepler5a33d8c2020-02-06 09:32:58 -0800450 KeyDescriptor::State new_state,
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800451 string_view key,
452 span<const byte> value) {
Wyatt Hepler5a33d8c2020-02-06 09:32:58 -0800453 // Find the original entry and sector to update the sector's valid_bytes.
Wyatt Hepler30a52152020-02-12 11:26:05 -0800454 Entry original_entry;
Wyatt Heplere541e072020-02-14 09:10:53 -0800455 TRY(Entry::Read(partition_, key_descriptor->address, &original_entry));
David Rogers3464d0a2020-02-07 11:45:46 -0800456 SectorDescriptor* old_sector = SectorFromAddress(key_descriptor->address);
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800457
David Rogers2761aeb2020-01-31 17:09:00 -0800458 SectorDescriptor* sector;
Wyatt Hepler5406a672020-02-18 15:42:38 -0800459 TRY(FindOrRecoverSectorWithSpace(&sector,
460 Entry::size(partition_, key, value)));
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800461 DBG("Writing existing entry; found sector %u (%#" PRIx32 ")",
462 SectorIndex(sector),
463 SectorBaseAddress(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 "
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800467 "relocated to sector %u",
David Rogers3464d0a2020-02-07 11:45:46 -0800468 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)));
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800495 DBG("Writing new entry; found sector: %u", 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) {
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800551 SectorDescriptor* first_empty_sector = nullptr;
552 bool at_least_two_empty_sectors = bypass_empty_sector_rule;
553
554 DBG("Find sector with %zu bytes available, starting with sector %u",
555 size,
556 SectorIndex(last_new_sector_));
557 if (sector_to_skip != nullptr) {
558 DBG(" Skip sector %u", SectorIndex(sector_to_skip));
559 }
560 if (bypass_empty_sector_rule) {
561 DBG(" Bypassing empty sector rule");
562 }
563
David Rogers8ce55cd2020-02-04 19:41:48 -0800564 // The last_new_sector_ is the sector that was last selected as the "new empty
565 // sector" to write to. This last new sector is used as the starting point for
566 // the next "find a new empty sector to write to" operation. By using the last
567 // new sector as the start point we will cycle which empty sector is selected
568 // next, spreading the wear across all the empty sectors and get a wear
569 // leveling benefit, rather than putting more wear on the lower number
570 // sectors.
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800571 SectorDescriptor* sector = last_new_sector_;
David Rogers67f4b6c2020-02-06 16:17:09 -0800572
David Rogers8ce55cd2020-02-04 19:41:48 -0800573 // Look for a partial sector to use with enough space. Immediately use the
574 // first one of those that is found. While scanning for a partial sector, keep
575 // track of the first empty sector and if a second sector was seen.
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800576 for (size_t j = 0; j < sectors_.size(); j++) {
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800577 sector += 1;
578 if (sector == sectors_.end()) {
579 sector = sectors_.begin();
580 }
Keir Mierle8c352dc2020-02-02 13:58:19 -0800581
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800582 if (sector_to_skip == sector) {
David Rogers8db5a722020-02-03 18:28:34 -0800583 continue;
584 }
585
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800586 const size_t sector_size_bytes = partition_.sector_size_bytes();
587 if (!sector->Empty(sector_size_bytes) && sector->HasSpace(size)) {
588 *found_sector = sector;
David Rogers8ce55cd2020-02-04 19:41:48 -0800589 return Status::OK;
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800590 }
591
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800592 if (sector->Empty(sector_size_bytes)) {
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800593 if (first_empty_sector == nullptr) {
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800594 first_empty_sector = sector;
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800595 } else {
596 at_least_two_empty_sectors = true;
Wyatt Hepler2ad60672020-01-21 08:00:16 -0800597 }
Wyatt Heplerb7609542020-01-24 10:29:54 -0800598 }
599 }
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800600
David Rogers8ce55cd2020-02-04 19:41:48 -0800601 // If the scan for a partial sector does not find a suitable sector, use the
602 // first empty sector that was found. Normally it is required to keep 1 empty
603 // sector after the sector found here, but that rule can be bypassed in
604 // special circumstances (such as during garbage collection).
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800605 if (at_least_two_empty_sectors) {
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800606 DBG(" Found a usable empty sector; returning the first found (%u)",
David Rogers8ce55cd2020-02-04 19:41:48 -0800607 SectorIndex(first_empty_sector));
608 last_new_sector_ = first_empty_sector;
609 *found_sector = first_empty_sector;
610 return Status::OK;
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800611 }
David Rogers8ce55cd2020-02-04 19:41:48 -0800612
613 // No sector was found.
David Rogers67f4b6c2020-02-06 16:17:09 -0800614 DBG(" Unable to find a usable sector");
David Rogers8ce55cd2020-02-04 19:41:48 -0800615 *found_sector = nullptr;
616 return Status::RESOURCE_EXHAUSTED;
Wyatt Heplerb7609542020-01-24 10:29:54 -0800617}
618
David Rogers2761aeb2020-01-31 17:09:00 -0800619Status KeyValueStore::FindOrRecoverSectorWithSpace(SectorDescriptor** sector,
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800620 size_t size) {
David Rogers8ce55cd2020-02-04 19:41:48 -0800621 Status result = FindSectorWithSpace(sector, size);
Wyatt Hepler2d401692020-02-13 16:01:23 -0800622 if (result == Status::RESOURCE_EXHAUSTED && options_.partial_gc_on_write) {
David Rogers1541d612020-02-06 23:47:02 -0800623 // Garbage collect and then try again to find the best sector.
624 TRY(GarbageCollectOneSector());
625 return FindSectorWithSpace(sector, size);
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800626 }
David Rogers8ce55cd2020-02-04 19:41:48 -0800627 return result;
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800628}
629
David Rogers2761aeb2020-01-31 17:09:00 -0800630KeyValueStore::SectorDescriptor* KeyValueStore::FindSectorToGarbageCollect() {
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800631 const size_t sector_size_bytes = partition_.sector_size_bytes();
David Rogers2761aeb2020-01-31 17:09:00 -0800632 SectorDescriptor* sector_candidate = nullptr;
David Rogersa12786b2020-01-31 16:02:33 -0800633 size_t candidate_bytes = 0;
634
635 // Step 1: Try to find a sectors with stale keys and no valid keys (no
636 // relocation needed). If any such sectors are found, use the sector with the
637 // most reclaimable bytes.
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800638 for (auto& sector : sectors_) {
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800639 if ((sector.valid_bytes() == 0) &&
640 (sector.RecoverableBytes(sector_size_bytes) > candidate_bytes)) {
David Rogersa12786b2020-01-31 16:02:33 -0800641 sector_candidate = &sector;
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800642 candidate_bytes = sector.RecoverableBytes(sector_size_bytes);
David Rogersa12786b2020-01-31 16:02:33 -0800643 }
644 }
645
646 // Step 2: If step 1 yields no sectors, just find the sector with the most
647 // reclaimable bytes.
648 if (sector_candidate == nullptr) {
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800649 for (auto& sector : sectors_) {
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800650 if (sector.RecoverableBytes(sector_size_bytes) > candidate_bytes) {
David Rogersa12786b2020-01-31 16:02:33 -0800651 sector_candidate = &sector;
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800652 candidate_bytes = sector.RecoverableBytes(sector_size_bytes);
David Rogersa12786b2020-01-31 16:02:33 -0800653 }
654 }
655 }
656
David Rogers5981f312020-02-13 13:33:56 -0800657 if (sector_candidate != nullptr) {
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800658 DBG("Found sector %u to Garbage Collect, %zu recoverable bytes",
David Rogers5981f312020-02-13 13:33:56 -0800659 SectorIndex(sector_candidate),
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800660 sector_candidate->RecoverableBytes(sector_size_bytes));
David Rogers5981f312020-02-13 13:33:56 -0800661 } else {
662 DBG("Unable to find sector to garbage collect!");
663 }
David Rogersa12786b2020-01-31 16:02:33 -0800664 return sector_candidate;
665}
666
David Rogers1541d612020-02-06 23:47:02 -0800667Status KeyValueStore::GarbageCollectOneSector() {
David Rogers67f4b6c2020-02-06 16:17:09 -0800668 DBG("Garbage Collect a single sector");
669
David Rogersa12786b2020-01-31 16:02:33 -0800670 // Step 1: Find the sector to garbage collect
David Rogers2761aeb2020-01-31 17:09:00 -0800671 SectorDescriptor* sector_to_gc = FindSectorToGarbageCollect();
David Rogers3464d0a2020-02-07 11:45:46 -0800672 LogSectors();
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800673
David Rogersa12786b2020-01-31 16:02:33 -0800674 if (sector_to_gc == nullptr) {
675 return Status::RESOURCE_EXHAUSTED;
676 }
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800677
David Rogersa12786b2020-01-31 16:02:33 -0800678 // Step 2: Move any valid entries in the GC sector to other sectors
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800679 if (sector_to_gc->valid_bytes() != 0) {
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800680 for (auto& descriptor : key_descriptors_) {
David Rogers2761aeb2020-01-31 17:09:00 -0800681 if (AddressInSector(*sector_to_gc, descriptor.address)) {
David Rogers67f4b6c2020-02-06 16:17:09 -0800682 DBG(" Relocate entry");
David Rogers2761aeb2020-01-31 17:09:00 -0800683 TRY(RelocateEntry(descriptor));
David Rogersa12786b2020-01-31 16:02:33 -0800684 }
Wyatt Heplerb7609542020-01-24 10:29:54 -0800685 }
686 }
Wyatt Heplerb7609542020-01-24 10:29:54 -0800687
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800688 if (sector_to_gc->valid_bytes() != 0) {
David Rogers67f4b6c2020-02-06 16:17:09 -0800689 ERR(" Failed to relocate valid entries from sector being garbage "
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800690 "collected, %zu valid bytes remain",
691 sector_to_gc->valid_bytes());
Wyatt Heplerb7609542020-01-24 10:29:54 -0800692 return Status::INTERNAL;
693 }
694
David Rogersa12786b2020-01-31 16:02:33 -0800695 // Step 3: Reinitialize the sector
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800696 sector_to_gc->set_writable_bytes(0);
David Rogersa12786b2020-01-31 16:02:33 -0800697 TRY(partition_.Erase(SectorBaseAddress(sector_to_gc), 1));
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800698 sector_to_gc->set_writable_bytes(partition_.sector_size_bytes());
Wyatt Heplerb7609542020-01-24 10:29:54 -0800699
David Rogers67f4b6c2020-02-06 16:17:09 -0800700 DBG(" Garbage Collect complete");
David Rogers50185ad2020-02-07 00:02:46 -0800701 LogSectors();
David Rogersa12786b2020-01-31 16:02:33 -0800702 return Status::OK;
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800703}
704
David Rogers2761aeb2020-01-31 17:09:00 -0800705Status KeyValueStore::AppendEntry(SectorDescriptor* sector,
706 KeyDescriptor* key_descriptor,
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800707 const string_view key,
Wyatt Hepler5a33d8c2020-02-06 09:32:58 -0800708 span<const byte> value,
709 KeyDescriptor::State new_state) {
Wyatt Heplere541e072020-02-14 09:10:53 -0800710 const Address address = NextWritableAddress(sector);
711 DBG("Appending to address: %#zx", size_t(address));
712
713 Entry entry;
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800714
Wyatt Hepler5a33d8c2020-02-06 09:32:58 -0800715 if (new_state == KeyDescriptor::kDeleted) {
Wyatt Heplere541e072020-02-14 09:10:53 -0800716 entry = Entry::Tombstone(partition_,
717 address,
718 entry_header_format_.magic,
719 entry_header_format_.checksum,
720 key,
721 partition_.alignment_bytes(),
722 key_descriptor->key_version + 1);
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800723 } else {
Wyatt Heplere541e072020-02-14 09:10:53 -0800724 entry = Entry::Valid(partition_,
725 address,
726 entry_header_format_.magic,
727 entry_header_format_.checksum,
728 key,
729 value,
730 partition_.alignment_bytes(),
731 key_descriptor->key_version + 1);
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800732 }
733
Wyatt Hepler97fc7942020-02-06 15:55:45 -0800734 DBG("Appending %zu B entry with key version: %x",
Wyatt Heplere541e072020-02-14 09:10:53 -0800735 entry.size(),
736 unsigned(entry.key_version()));
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800737
Wyatt Heplere541e072020-02-14 09:10:53 -0800738 TRY_ASSIGN(const size_t written, entry.Write(key, value));
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800739
740 if (options_.verify_on_write) {
Wyatt Heplere541e072020-02-14 09:10:53 -0800741 TRY(entry.VerifyChecksumInFlash(entry_header_format_.checksum));
Wyatt Heplerb7609542020-01-24 10:29:54 -0800742 }
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800743
David Rogers2761aeb2020-01-31 17:09:00 -0800744 key_descriptor->address = address;
Wyatt Heplere541e072020-02-14 09:10:53 -0800745 key_descriptor->key_version = entry.key_version();
Wyatt Hepler5a33d8c2020-02-06 09:32:58 -0800746 key_descriptor->state = new_state;
747
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800748 sector->MarkValidBytesWritten(written);
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800749 return Status::OK;
Wyatt Heplerb7609542020-01-24 10:29:54 -0800750}
751
Keir Mierle8c352dc2020-02-02 13:58:19 -0800752void KeyValueStore::LogDebugInfo() {
Keir Mierle8c352dc2020-02-02 13:58:19 -0800753 const size_t sector_size_bytes = partition_.sector_size_bytes();
754 DBG("====================== KEY VALUE STORE DUMP =========================");
755 DBG(" ");
756 DBG("Flash partition:");
Wyatt Heplerad0a7932020-02-06 08:20:38 -0800757 DBG(" Sector count = %zu", partition_.sector_count());
758 DBG(" Sector max count = %zu", kMaxUsableSectors);
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800759 DBG(" Sectors in use = %zu", sectors_.size());
Keir Mierle8c352dc2020-02-02 13:58:19 -0800760 DBG(" Sector size = %zu", sector_size_bytes);
761 DBG(" Total size = %zu", partition_.size_bytes());
762 DBG(" Alignment = %zu", partition_.alignment_bytes());
763 DBG(" ");
764 DBG("Key descriptors:");
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800765 DBG(" Entry count = %zu", key_descriptors_.size());
Keir Mierle8c352dc2020-02-02 13:58:19 -0800766 DBG(" Max entry count = %zu", kMaxEntries);
767 DBG(" ");
768 DBG(" # hash version address address (hex)");
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800769 for (size_t i = 0; i < key_descriptors_.size(); ++i) {
770 const KeyDescriptor& kd = key_descriptors_[i];
Keir Mierle8c352dc2020-02-02 13:58:19 -0800771 DBG(" |%3zu: | %8zx |%8zu | %8zu | %8zx",
772 i,
773 size_t(kd.key_hash),
774 size_t(kd.key_version),
775 size_t(kd.address),
776 size_t(kd.address));
777 }
778 DBG(" ");
779
780 DBG("Sector descriptors:");
781 DBG(" # tail free valid has_space");
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800782 for (size_t sector_id = 0; sector_id < sectors_.size(); ++sector_id) {
783 const SectorDescriptor& sd = sectors_[sector_id];
Keir Mierle8c352dc2020-02-02 13:58:19 -0800784 DBG(" |%3zu: | %8zu |%8zu | %s",
785 sector_id,
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800786 size_t(sd.writable_bytes()),
787 sd.valid_bytes(),
788 sd.writable_bytes() ? "YES" : "");
Keir Mierle8c352dc2020-02-02 13:58:19 -0800789 }
790 DBG(" ");
791
792 // TODO: This should stop logging after some threshold.
793 // size_t dumped_bytes = 0;
794 DBG("Sector raw data:");
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800795 for (size_t sector_id = 0; sector_id < sectors_.size(); ++sector_id) {
Keir Mierle8c352dc2020-02-02 13:58:19 -0800796 // Read sector data. Yes, this will blow the stack on embedded.
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800797 std::array<byte, 500> raw_sector_data; // TODO!!!
Keir Mierle8c352dc2020-02-02 13:58:19 -0800798 StatusWithSize sws =
799 partition_.Read(sector_id * sector_size_bytes, raw_sector_data);
800 DBG("Read: %zu bytes", sws.size());
801
802 DBG(" base addr offs 0 1 2 3 4 5 6 7");
803 for (size_t i = 0; i < sector_size_bytes; i += 8) {
804 DBG(" %3zu %8zx %5zu | %02x %02x %02x %02x %02x %02x %02x %02x",
805 sector_id,
806 (sector_id * sector_size_bytes) + i,
807 i,
808 static_cast<unsigned int>(raw_sector_data[i + 0]),
809 static_cast<unsigned int>(raw_sector_data[i + 1]),
810 static_cast<unsigned int>(raw_sector_data[i + 2]),
811 static_cast<unsigned int>(raw_sector_data[i + 3]),
812 static_cast<unsigned int>(raw_sector_data[i + 4]),
813 static_cast<unsigned int>(raw_sector_data[i + 5]),
814 static_cast<unsigned int>(raw_sector_data[i + 6]),
815 static_cast<unsigned int>(raw_sector_data[i + 7]));
816
817 // TODO: Fix exit condition.
818 if (i > 128) {
819 break;
820 }
821 }
822 DBG(" ");
823 }
824
825 DBG("////////////////////// KEY VALUE STORE DUMP END /////////////////////");
826}
827
David Rogerscf680ab2020-02-12 23:28:32 -0800828void KeyValueStore::LogSectors() const {
829 DBG("Sector descriptors: count %zu", sectors_.size());
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800830 for (auto& sector : sectors_) {
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800831 DBG(" - Sector %u: valid %zu, recoverable %zu, free %zu",
David Rogers50185ad2020-02-07 00:02:46 -0800832 SectorIndex(&sector),
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800833 sector.valid_bytes(),
834 sector.RecoverableBytes(partition_.sector_size_bytes()),
835 sector.writable_bytes());
David Rogers50185ad2020-02-07 00:02:46 -0800836 }
837}
838
David Rogerscf680ab2020-02-12 23:28:32 -0800839void KeyValueStore::LogKeyDescriptor() const {
840 DBG("Key descriptors: count %zu", key_descriptors_.size());
841 for (auto& key : key_descriptors_) {
842 DBG(" - Key: %s, hash %#zx, version %zu, address %#zx",
843 key.deleted() ? "Deleted" : "Valid",
844 static_cast<size_t>(key.key_hash),
845 static_cast<size_t>(key.key_version),
846 static_cast<size_t>(key.address));
847 }
848}
849
Wyatt Hepler2ad60672020-01-21 08:00:16 -0800850} // namespace pw::kvs