blob: d0ab51261cf7e0ad72dd913aa5a15896923f8e2b [file] [log] [blame]
Wyatt Heplerb7609542020-01-24 10:29:54 -08001// Copyright 2020 The Pigweed Authors
2//
3// Licensed under the Apache License, Version 2.0 (the "License"); you may not
4// use this file except in compliance with the License. You may obtain a copy of
5// the License at
6//
7// https://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
11// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12// License for the specific language governing permissions and limitations under
13// the License.
14
Wyatt Heplerb7609542020-01-24 10:29:54 -080015#include "pw_kvs/key_value_store.h"
16
Wyatt Heplerbab0e202020-02-04 07:40:08 -080017#include <algorithm>
Wyatt Hepler5a33d8c2020-02-06 09:32:58 -080018#include <cinttypes>
Wyatt Heplerb7609542020-01-24 10:29:54 -080019#include <cstring>
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -080020#include <type_traits>
Wyatt Heplerb7609542020-01-24 10:29:54 -080021
Keir Mierle8c352dc2020-02-02 13:58:19 -080022#define PW_LOG_USE_ULTRA_SHORT_NAMES 1
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -080023#include "pw_kvs_private/macros.h"
Keir Mierle8c352dc2020-02-02 13:58:19 -080024#include "pw_log/log.h"
Wyatt Heplerb7609542020-01-24 10:29:54 -080025
Wyatt Hepler2ad60672020-01-21 08:00:16 -080026namespace pw::kvs {
Wyatt Heplera00d1ef2020-02-14 14:31:26 -080027namespace {
Wyatt Heplerb7609542020-01-24 10:29:54 -080028
Wyatt Hepleracaacf92020-01-24 10:58:30 -080029using std::byte;
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -080030using std::string_view;
Wyatt Hepleracaacf92020-01-24 10:58:30 -080031
Wyatt Heplera00d1ef2020-02-14 14:31:26 -080032constexpr bool InvalidKey(std::string_view key) {
Wyatt Heplerbdd8e5a2020-02-20 19:27:26 -080033 return key.empty() || (key.size() > internal::Entry::kMaxKeyLength);
Wyatt Heplera00d1ef2020-02-14 14:31:26 -080034}
35
36} // namespace
37
Wyatt Heplerad0a7932020-02-06 08:20:38 -080038KeyValueStore::KeyValueStore(FlashPartition* partition,
Wyatt Hepler22d0d9f2020-03-05 14:57:11 -080039 span<const EntryFormat> formats,
Wyatt Hepler7ded6da2020-03-11 18:24:43 -070040 const Options& options,
41 size_t redundancy,
42 Vector<SectorDescriptor>& sector_descriptor_list,
43 const SectorDescriptor** temp_sectors_to_skip,
44 Vector<KeyDescriptor>& key_descriptor_list,
45 Address* addresses)
Wyatt Heplerad0a7932020-02-06 08:20:38 -080046 : partition_(*partition),
Wyatt Hepler22d0d9f2020-03-05 14:57:11 -080047 formats_(formats),
Wyatt Heplerc84393f2020-03-20 11:23:24 -070048 sectors_(sector_descriptor_list, *partition, temp_sectors_to_skip),
Wyatt Hepler7ded6da2020-03-11 18:24:43 -070049 entry_cache_(key_descriptor_list, addresses, redundancy),
David Rogers49766d92020-03-20 10:55:54 -070050 options_(options),
51 initialized_(false),
52 error_detected_(false),
David Rogers49766d92020-03-20 10:55:54 -070053 last_transaction_id_(0) {}
Wyatt Heplerad0a7932020-02-06 08:20:38 -080054
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -080055Status KeyValueStore::Init() {
Keir Mierlebf904812020-03-11 17:28:22 -070056 initialized_ = false;
David Rogers49766d92020-03-20 10:55:54 -070057 error_detected_ = false;
Keir Mierlebf904812020-03-11 17:28:22 -070058 last_transaction_id_ = 0;
Wyatt Heplerc84393f2020-03-20 11:23:24 -070059 sectors_.Reset();
Wyatt Hepler7ded6da2020-03-11 18:24:43 -070060 entry_cache_.Reset();
Wyatt Heplerd2298282020-02-20 17:12:45 -080061
David Rogers2e9e0c82020-02-13 15:06:06 -080062 INF("Initializing key value store");
Wyatt Hepler38ce30f2020-02-19 11:48:31 -080063 if (partition_.sector_count() > sectors_.max_size()) {
David Rogers2e9e0c82020-02-13 15:06:06 -080064 ERR("KVS init failed: kMaxUsableSectors (=%zu) must be at least as "
65 "large as the number of sectors in the flash partition (=%zu)",
Wyatt Hepler38ce30f2020-02-19 11:48:31 -080066 sectors_.max_size(),
David Rogers2e9e0c82020-02-13 15:06:06 -080067 partition_.sector_count());
Wyatt Heplerad0a7932020-02-06 08:20:38 -080068 return Status::FAILED_PRECONDITION;
69 }
70
Keir Mierle8c352dc2020-02-02 13:58:19 -080071 const size_t sector_size_bytes = partition_.sector_size_bytes();
Keir Mierle8c352dc2020-02-02 13:58:19 -080072
David Rogers49766d92020-03-20 10:55:54 -070073 // TODO: investigate doing this as a static assert/compile-time check.
74 if (sector_size_bytes > SectorDescriptor::max_sector_size()) {
75 ERR("KVS init failed: sector_size_bytes (=%zu) is greater than maximum "
76 "allowed sector size (=%zu)",
77 sector_size_bytes,
78 SectorDescriptor::max_sector_size());
79 return Status::FAILED_PRECONDITION;
80 }
81
Keir Mierle8c352dc2020-02-02 13:58:19 -080082 DBG("First pass: Read all entries from all sectors");
Wyatt Hepler2c7eca02020-02-18 16:01:42 -080083 Address sector_address = 0;
Keir Mierle8c352dc2020-02-02 13:58:19 -080084
Alexei Frolovd4adf912020-02-21 13:29:15 -080085 size_t total_corrupt_bytes = 0;
86 int corrupt_entries = 0;
David Rogers91627482020-02-27 17:38:12 -080087 bool empty_sector_found = false;
Alexei Frolovd4adf912020-02-21 13:29:15 -080088
Wyatt Hepler2c7eca02020-02-18 16:01:42 -080089 for (SectorDescriptor& sector : sectors_) {
Keir Mierle8c352dc2020-02-02 13:58:19 -080090 Address entry_address = sector_address;
91
Alexei Frolovd4adf912020-02-21 13:29:15 -080092 size_t sector_corrupt_bytes = 0;
93
Wyatt Hepler2c7eca02020-02-18 16:01:42 -080094 for (int num_entries_in_sector = 0; true; num_entries_in_sector++) {
95 DBG("Load entry: sector=%" PRIx32 ", entry#=%d, address=%" PRIx32,
96 sector_address,
Keir Mierle8c352dc2020-02-02 13:58:19 -080097 num_entries_in_sector,
Wyatt Hepler2c7eca02020-02-18 16:01:42 -080098 entry_address);
Keir Mierle8c352dc2020-02-02 13:58:19 -080099
Wyatt Heplerc84393f2020-03-20 11:23:24 -0700100 if (!sectors_.AddressInSector(sector, entry_address)) {
Keir Mierle8c352dc2020-02-02 13:58:19 -0800101 DBG("Fell off end of sector; moving to the next sector");
102 break;
103 }
104
105 Address next_entry_address;
106 Status status = LoadEntry(entry_address, &next_entry_address);
107 if (status == Status::NOT_FOUND) {
108 DBG("Hit un-written data in sector; moving to the next sector");
109 break;
110 }
111 if (status == Status::DATA_LOSS) {
Alexei Frolovd4adf912020-02-21 13:29:15 -0800112 // The entry could not be read, indicating data corruption within the
113 // sector. Try to scan the remainder of the sector for other entries.
David Rogersa2562b52020-03-05 15:30:05 -0800114 WRN("KVS init: data loss detected in sector %u at address %zu",
Wyatt Heplerc84393f2020-03-20 11:23:24 -0700115 sectors_.Index(sector),
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800116 size_t(entry_address));
Alexei Frolovd4adf912020-02-21 13:29:15 -0800117
David Rogers49766d92020-03-20 10:55:54 -0700118 error_detected_ = true;
Alexei Frolovd4adf912020-02-21 13:29:15 -0800119 corrupt_entries++;
120
121 status = ScanForEntry(sector,
122 entry_address + Entry::kMinAlignmentBytes,
123 &next_entry_address);
124 if (status == Status::NOT_FOUND) {
125 // No further entries in this sector. Mark the remaining bytes in the
126 // sector as corrupt (since we can't reliably know the size of the
127 // corrupt entry).
128 sector_corrupt_bytes +=
129 sector_size_bytes - (entry_address - sector_address);
130 break;
131 }
132
133 if (!status.ok()) {
134 ERR("Unexpected error in KVS initialization: %s", status.str());
135 return Status::UNKNOWN;
136 }
137
138 sector_corrupt_bytes += next_entry_address - entry_address;
139 } else if (!status.ok()) {
140 ERR("Unexpected error in KVS initialization: %s", status.str());
141 return Status::UNKNOWN;
Keir Mierle8c352dc2020-02-02 13:58:19 -0800142 }
Keir Mierle8c352dc2020-02-02 13:58:19 -0800143
144 // Entry loaded successfully; so get ready to load the next one.
145 entry_address = next_entry_address;
146
147 // Update of the number of writable bytes in this sector.
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800148 sector.set_writable_bytes(sector_size_bytes -
149 (entry_address - sector_address));
Keir Mierle8c352dc2020-02-02 13:58:19 -0800150 }
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800151
Alexei Frolovd4adf912020-02-21 13:29:15 -0800152 if (sector_corrupt_bytes > 0) {
153 // If the sector contains corrupt data, prevent any further entries from
154 // being written to it by indicating that it has no space. This should
155 // also make it a decent GC candidate. Valid keys in the sector are still
156 // readable as normal.
David Rogers49766d92020-03-20 10:55:54 -0700157 sector.mark_corrupt();
158 error_detected_ = true;
Alexei Frolovd4adf912020-02-21 13:29:15 -0800159
160 WRN("Sector %u contains %zuB of corrupt data",
Wyatt Heplerc84393f2020-03-20 11:23:24 -0700161 sectors_.Index(sector),
Alexei Frolovd4adf912020-02-21 13:29:15 -0800162 sector_corrupt_bytes);
163 }
164
David Rogers91627482020-02-27 17:38:12 -0800165 if (sector.Empty(sector_size_bytes)) {
166 empty_sector_found = true;
167 }
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800168 sector_address += sector_size_bytes;
Alexei Frolovd4adf912020-02-21 13:29:15 -0800169 total_corrupt_bytes += sector_corrupt_bytes;
Keir Mierle8c352dc2020-02-02 13:58:19 -0800170 }
171
172 DBG("Second pass: Count valid bytes in each sector");
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700173 Address newest_key = 0;
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800174
Wyatt Hepler02946272020-03-18 10:36:22 -0700175 // For every valid entry, count the valid bytes in that sector. Track which
176 // entry has the newest transaction ID for initializing last_new_sector_.
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700177 for (const EntryMetadata& metadata : entry_cache_) {
David Rogers49766d92020-03-20 10:55:54 -0700178 if (metadata.addresses().size() < redundancy()) {
179 error_detected_ = true;
180 }
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700181 for (Address address : metadata.addresses()) {
David Rogersf56131c2020-03-04 10:19:22 -0800182 Entry entry;
David Rogersa2562b52020-03-05 15:30:05 -0800183 TRY(Entry::Read(partition_, address, formats_, &entry));
Wyatt Heplerc84393f2020-03-20 11:23:24 -0700184 sectors_.FromAddress(address).AddValidBytes(entry.size());
David Rogersf56131c2020-03-04 10:19:22 -0800185 }
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700186 if (metadata.IsNewerThan(last_transaction_id_)) {
187 last_transaction_id_ = metadata.transaction_id();
188 newest_key = metadata.addresses().back();
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800189 }
Keir Mierle8c352dc2020-02-02 13:58:19 -0800190 }
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800191
Wyatt Heplerc84393f2020-03-20 11:23:24 -0700192 sectors_.set_last_new_sector(newest_key);
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800193
David Rogers49766d92020-03-20 10:55:54 -0700194 if (error_detected_) {
195 Status recovery_status = Repair();
196 if (recovery_status.ok()) {
197 INF("KVS init: Corruption detected and fully repaired");
198 } else {
199 ERR("KVS init: Corruption detected and unable repair");
200 }
201 }
202
David Rogers91627482020-02-27 17:38:12 -0800203 if (!empty_sector_found) {
204 // TODO: Record/report the error condition and recovery result.
205 Status gc_result = GarbageCollectPartial();
206
207 if (!gc_result.ok()) {
208 ERR("KVS init failed: Unable to maintain required free sector");
209 return Status::INTERNAL;
210 }
211 }
212
Wyatt Hepler729f28c2020-02-05 09:46:00 -0800213 initialized_ = true;
David Rogers2e9e0c82020-02-13 15:06:06 -0800214
Armando Montanez5464d5f2020-02-20 10:12:20 -0800215 INF("KeyValueStore init complete: active keys %zu, deleted keys %zu, sectors "
David Rogers2e9e0c82020-02-13 15:06:06 -0800216 "%zu, logical sector size %zu bytes",
217 size(),
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700218 (entry_cache_.total_entries() - size()),
David Rogers2e9e0c82020-02-13 15:06:06 -0800219 sectors_.size(),
220 partition_.sector_size_bytes());
221
Alexei Frolovd4adf912020-02-21 13:29:15 -0800222 if (total_corrupt_bytes > 0) {
223 WRN("Found %zu corrupt bytes and %d corrupt entries during init process; "
224 "some keys may be missing",
225 total_corrupt_bytes,
226 corrupt_entries);
227 return Status::DATA_LOSS;
228 }
229
Keir Mierle8c352dc2020-02-02 13:58:19 -0800230 return Status::OK;
231}
232
Alexei Frolov9e235832020-02-24 12:44:45 -0800233KeyValueStore::StorageStats KeyValueStore::GetStorageStats() const {
234 StorageStats stats{0, 0, 0};
235 const size_t sector_size = partition_.sector_size_bytes();
236 bool found_empty_sector = false;
237
238 for (const SectorDescriptor& sector : sectors_) {
239 stats.in_use_bytes += sector.valid_bytes();
240 stats.reclaimable_bytes += sector.RecoverableBytes(sector_size);
241
242 if (!found_empty_sector && sector.Empty(sector_size)) {
243 // The KVS tries to always keep an empty sector for GC, so don't count
244 // the first empty sector seen as writable space. However, a free sector
245 // cannot always be assumed to exist; if a GC operation fails, all sectors
246 // may be partially written, in which case the space reported might be
247 // inaccurate.
248 found_empty_sector = true;
249 continue;
250 }
251
252 stats.writable_bytes += sector.writable_bytes();
253 }
254
255 return stats;
256}
257
Keir Mierle8c352dc2020-02-02 13:58:19 -0800258Status KeyValueStore::LoadEntry(Address entry_address,
259 Address* next_entry_address) {
Wyatt Heplere541e072020-02-14 09:10:53 -0800260 Entry entry;
Wyatt Hepler22d0d9f2020-03-05 14:57:11 -0800261 TRY(Entry::Read(partition_, entry_address, formats_, &entry));
Keir Mierle8c352dc2020-02-02 13:58:19 -0800262
263 // Read the key from flash & validate the entry (which reads the value).
Wyatt Heplera00d1ef2020-02-14 14:31:26 -0800264 Entry::KeyBuffer key_buffer;
Wyatt Heplere541e072020-02-14 09:10:53 -0800265 TRY_ASSIGN(size_t key_length, entry.ReadKey(key_buffer));
266 const string_view key(key_buffer.data(), key_length);
Wyatt Heplerbab0e202020-02-04 07:40:08 -0800267
Wyatt Hepler22d0d9f2020-03-05 14:57:11 -0800268 TRY(entry.VerifyChecksumInFlash());
David Rogersf56131c2020-03-04 10:19:22 -0800269
270 // A valid entry was found, so update the next entry address before doing any
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700271 // of the checks that happen in AddNewOrUpdateExisting.
David Rogersf56131c2020-03-04 10:19:22 -0800272 *next_entry_address = entry.next_address();
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700273 return entry_cache_.AddNewOrUpdateExisting(
274 entry.descriptor(key), entry.address(), partition_.sector_size_bytes());
Keir Mierle8c352dc2020-02-02 13:58:19 -0800275}
276
Alexei Frolovd4adf912020-02-21 13:29:15 -0800277// Scans flash memory within a sector to find a KVS entry magic.
Alexei Frolovd4adf912020-02-21 13:29:15 -0800278Status KeyValueStore::ScanForEntry(const SectorDescriptor& sector,
279 Address start_address,
280 Address* next_entry_address) {
281 DBG("Scanning sector %u for entries starting from address %zx",
Wyatt Heplerc84393f2020-03-20 11:23:24 -0700282 sectors_.Index(sector),
Alexei Frolovd4adf912020-02-21 13:29:15 -0800283 size_t(start_address));
284
285 // Entries must start at addresses which are aligned on a multiple of
286 // Entry::kMinAlignmentBytes. However, that multiple can vary between entries.
287 // When scanning, we don't have an entry to tell us what the current alignment
288 // is, so the minimum alignment is used to be exhaustive.
289 for (Address address = AlignUp(start_address, Entry::kMinAlignmentBytes);
Wyatt Heplerc84393f2020-03-20 11:23:24 -0700290 sectors_.AddressInSector(sector, address);
Alexei Frolovd4adf912020-02-21 13:29:15 -0800291 address += Entry::kMinAlignmentBytes) {
Alexei Frolovd4adf912020-02-21 13:29:15 -0800292 uint32_t magic;
293 TRY(partition_.Read(address, as_writable_bytes(span(&magic, 1))));
Wyatt Hepler22d0d9f2020-03-05 14:57:11 -0800294 if (formats_.KnownMagic(magic)) {
Alexei Frolovd4adf912020-02-21 13:29:15 -0800295 DBG("Found entry magic at address %zx", size_t(address));
296 *next_entry_address = address;
297 return Status::OK;
298 }
299 }
300
301 return Status::NOT_FOUND;
302}
303
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800304StatusWithSize KeyValueStore::Get(string_view key,
Wyatt Hepler5f6efc02020-02-18 16:54:31 -0800305 span<byte> value_buffer,
306 size_t offset_bytes) const {
Wyatt Hepler50f70772020-02-13 11:25:10 -0800307 TRY_WITH_SIZE(CheckOperation(key));
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800308
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700309 EntryMetadata metadata;
310 TRY_WITH_SIZE(entry_cache_.FindExisting(partition_, key, &metadata));
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800311
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700312 return Get(key, metadata, value_buffer, offset_bytes);
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800313}
314
Wyatt Heplerfac81132020-02-27 17:26:33 -0800315Status KeyValueStore::PutBytes(string_view key, span<const byte> value) {
Keir Mierle8c352dc2020-02-02 13:58:19 -0800316 DBG("Writing key/value; key length=%zu, value length=%zu",
317 key.size(),
318 value.size());
Wyatt Hepler729f28c2020-02-05 09:46:00 -0800319
320 TRY(CheckOperation(key));
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800321
Wyatt Hepler5406a672020-02-18 15:42:38 -0800322 if (Entry::size(partition_, key, value) > partition_.sector_size_bytes()) {
323 DBG("%zu B value with %zu B key cannot fit in one sector",
324 value.size(),
325 key.size());
326 return Status::INVALID_ARGUMENT;
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800327 }
328
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700329 EntryMetadata metadata;
330 Status status = entry_cache_.Find(partition_, key, &metadata);
Wyatt Hepler2d401692020-02-13 16:01:23 -0800331
332 if (status.ok()) {
David Rogersf56131c2020-03-04 10:19:22 -0800333 // TODO: figure out logging how to support multiple addresses.
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700334 DBG("Overwriting entry for key 0x%08" PRIx32 " in %zu sectors including %u",
335 metadata.hash(),
336 metadata.addresses().size(),
Wyatt Heplerc84393f2020-03-20 11:23:24 -0700337 sectors_.Index(metadata.first_address()));
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700338 return WriteEntryForExistingKey(metadata, EntryState::kValid, key, value);
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800339 }
David Rogers2761aeb2020-01-31 17:09:00 -0800340
Wyatt Hepler2d401692020-02-13 16:01:23 -0800341 if (status == Status::NOT_FOUND) {
342 return WriteEntryForNewKey(key, value);
343 }
344
345 return status;
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800346}
347
348Status KeyValueStore::Delete(string_view key) {
Wyatt Hepler729f28c2020-02-05 09:46:00 -0800349 TRY(CheckOperation(key));
350
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700351 EntryMetadata metadata;
352 TRY(entry_cache_.FindExisting(partition_, key, &metadata));
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800353
David Rogersf56131c2020-03-04 10:19:22 -0800354 // TODO: figure out logging how to support multiple addresses.
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700355 DBG("Writing tombstone for key 0x%08" PRIx32 " in %zu sectors including %u",
356 metadata.hash(),
357 metadata.addresses().size(),
Wyatt Heplerc84393f2020-03-20 11:23:24 -0700358 sectors_.Index(metadata.first_address()));
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700359 return WriteEntryForExistingKey(metadata, EntryState::kDeleted, key, {});
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800360}
361
Wyatt Hepler08d37d82020-02-27 15:45:37 -0800362void KeyValueStore::Item::ReadKey() {
363 key_buffer_.fill('\0');
364
365 Entry entry;
David Rogersf3884eb2020-03-08 19:21:40 -0700366 // TODO: add support for using one of the redundant entries if reading the
367 // first copy fails.
Wyatt Hepler22d0d9f2020-03-05 14:57:11 -0800368 if (Entry::Read(
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700369 kvs_.partition_, iterator_->first_address(), kvs_.formats_, &entry)
Wyatt Hepler22d0d9f2020-03-05 14:57:11 -0800370 .ok()) {
Wyatt Hepler08d37d82020-02-27 15:45:37 -0800371 entry.ReadKey(key_buffer_);
372 }
373}
374
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800375KeyValueStore::iterator& KeyValueStore::iterator::operator++() {
376 // Skip to the next entry that is valid (not deleted).
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700377 while (++item_.iterator_ != item_.kvs_.entry_cache_.end() &&
Wyatt Hepler02946272020-03-18 10:36:22 -0700378 item_.iterator_->state() != EntryState::kValid) {
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800379 }
380 return *this;
381}
382
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800383KeyValueStore::iterator KeyValueStore::begin() const {
Wyatt Heplerbfc6a522020-04-01 16:30:24 -0700384 internal::EntryCache::const_iterator cache_iterator = entry_cache_.begin();
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800385 // Skip over any deleted entries at the start of the descriptor list.
Wyatt Hepler02946272020-03-18 10:36:22 -0700386 while (cache_iterator != entry_cache_.end() &&
387 cache_iterator->state() != EntryState::kValid) {
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700388 ++cache_iterator;
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800389 }
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700390 return iterator(*this, cache_iterator);
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800391}
392
Wyatt Heplerab3b2492020-03-11 16:15:16 -0700393StatusWithSize KeyValueStore::ValueSize(string_view key) const {
Wyatt Hepler50f70772020-02-13 11:25:10 -0800394 TRY_WITH_SIZE(CheckOperation(key));
Wyatt Heplered163b02020-02-03 17:49:32 -0800395
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700396 EntryMetadata metadata;
397 TRY_WITH_SIZE(entry_cache_.FindExisting(partition_, key, &metadata));
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800398
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700399 return ValueSize(metadata);
Wyatt Heplerfac81132020-02-27 17:26:33 -0800400}
Wyatt Heplered163b02020-02-03 17:49:32 -0800401
Wyatt Heplerfac81132020-02-27 17:26:33 -0800402StatusWithSize KeyValueStore::Get(string_view key,
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700403 const EntryMetadata& metadata,
Wyatt Heplerfac81132020-02-27 17:26:33 -0800404 span<std::byte> value_buffer,
405 size_t offset_bytes) const {
406 Entry entry;
David Rogersa2562b52020-03-05 15:30:05 -0800407 // TODO: add support for using one of the redundant entries if reading the
408 // first copy fails.
Wyatt Hepler22d0d9f2020-03-05 14:57:11 -0800409 TRY_WITH_SIZE(
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700410 Entry::Read(partition_, metadata.first_address(), formats_, &entry));
Wyatt Heplerfac81132020-02-27 17:26:33 -0800411
412 StatusWithSize result = entry.ReadValue(value_buffer, offset_bytes);
413 if (result.ok() && options_.verify_on_read && offset_bytes == 0u) {
Wyatt Hepler22d0d9f2020-03-05 14:57:11 -0800414 Status verify_result =
415 entry.VerifyChecksum(key, value_buffer.first(result.size()));
Wyatt Heplerfac81132020-02-27 17:26:33 -0800416 if (!verify_result.ok()) {
417 std::memset(value_buffer.data(), 0, result.size());
418 return StatusWithSize(verify_result, 0);
419 }
420
421 return StatusWithSize(verify_result, result.size());
422 }
423 return result;
Wyatt Heplered163b02020-02-03 17:49:32 -0800424}
425
Wyatt Hepler6e3a83b2020-02-04 07:36:45 -0800426Status KeyValueStore::FixedSizeGet(std::string_view key,
Wyatt Heplerfac81132020-02-27 17:26:33 -0800427 void* value,
428 size_t size_bytes) const {
429 TRY(CheckOperation(key));
430
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700431 EntryMetadata metadata;
432 TRY(entry_cache_.FindExisting(partition_, key, &metadata));
Wyatt Heplerfac81132020-02-27 17:26:33 -0800433
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700434 return FixedSizeGet(key, metadata, value, size_bytes);
Wyatt Heplerfac81132020-02-27 17:26:33 -0800435}
436
437Status KeyValueStore::FixedSizeGet(std::string_view key,
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700438 const EntryMetadata& metadata,
Wyatt Heplerfac81132020-02-27 17:26:33 -0800439 void* value,
Wyatt Hepler6e3a83b2020-02-04 07:36:45 -0800440 size_t size_bytes) const {
441 // Ensure that the size of the stored value matches the size of the type.
442 // Otherwise, report error. This check avoids potential memory corruption.
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700443 TRY_ASSIGN(const size_t actual_size, ValueSize(metadata));
Wyatt Heplerfac81132020-02-27 17:26:33 -0800444
445 if (actual_size != size_bytes) {
446 DBG("Requested %zu B read, but value is %zu B", size_bytes, actual_size);
Wyatt Hepler6e3a83b2020-02-04 07:36:45 -0800447 return Status::INVALID_ARGUMENT;
Wyatt Heplerbab0e202020-02-04 07:40:08 -0800448 }
Wyatt Heplerfac81132020-02-27 17:26:33 -0800449
450 StatusWithSize result =
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700451 Get(key, metadata, span(static_cast<byte*>(value), size_bytes), 0);
Wyatt Heplerfac81132020-02-27 17:26:33 -0800452
453 return result.status();
454}
455
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700456StatusWithSize KeyValueStore::ValueSize(const EntryMetadata& metadata) const {
Wyatt Heplerfac81132020-02-27 17:26:33 -0800457 Entry entry;
David Rogersf3884eb2020-03-08 19:21:40 -0700458 // TODO: add support for using one of the redundant entries if reading the
459 // first copy fails.
Wyatt Hepler22d0d9f2020-03-05 14:57:11 -0800460 TRY_WITH_SIZE(
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700461 Entry::Read(partition_, metadata.first_address(), formats_, &entry));
Wyatt Heplerfac81132020-02-27 17:26:33 -0800462
463 return StatusWithSize(entry.value_size());
Keir Mierle8c352dc2020-02-02 13:58:19 -0800464}
465
Wyatt Hepler729f28c2020-02-05 09:46:00 -0800466Status KeyValueStore::CheckOperation(string_view key) const {
Wyatt Hepleracaacf92020-01-24 10:58:30 -0800467 if (InvalidKey(key)) {
Wyatt Heplerb7609542020-01-24 10:29:54 -0800468 return Status::INVALID_ARGUMENT;
469 }
Wyatt Heplerd2298282020-02-20 17:12:45 -0800470 if (!initialized()) {
Wyatt Heplerb7609542020-01-24 10:29:54 -0800471 return Status::FAILED_PRECONDITION;
472 }
Wyatt Heplerb7609542020-01-24 10:29:54 -0800473 return Status::OK;
474}
475
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700476Status KeyValueStore::WriteEntryForExistingKey(EntryMetadata& metadata,
477 EntryState new_state,
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800478 string_view key,
479 span<const byte> value) {
Wyatt Heplerab3b2492020-03-11 16:15:16 -0700480 // Read the original entry to get the size for sector accounting purposes.
481 Entry entry;
David Rogersa2562b52020-03-05 15:30:05 -0800482 // TODO: add support for using one of the redundant entries if reading the
483 // first copy fails.
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700484 TRY(Entry::Read(partition_, metadata.first_address(), formats_, &entry));
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800485
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700486 return WriteEntry(key, value, new_state, &metadata, entry.size());
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800487}
488
489Status KeyValueStore::WriteEntryForNewKey(string_view key,
490 span<const byte> value) {
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700491 if (entry_cache_.full()) {
Keir Mierle8c352dc2020-02-02 13:58:19 -0800492 WRN("KVS full: trying to store a new entry, but can't. Have %zu entries",
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700493 entry_cache_.total_entries());
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800494 return Status::RESOURCE_EXHAUSTED;
495 }
496
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700497 return WriteEntry(key, value, EntryState::kValid);
Wyatt Heplerab3b2492020-03-11 16:15:16 -0700498}
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800499
Wyatt Heplerab3b2492020-03-11 16:15:16 -0700500Status KeyValueStore::WriteEntry(string_view key,
501 span<const byte> value,
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700502 EntryState new_state,
503 EntryMetadata* prior_metadata,
Wyatt Heplerab3b2492020-03-11 16:15:16 -0700504 size_t prior_size) {
505 const size_t entry_size = Entry::size(partition_, key, value);
506
507 // List of addresses for sectors with space for this entry.
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700508 Address* reserved_addresses = entry_cache_.TempReservedAddressesForWrite();
Wyatt Heplerab3b2492020-03-11 16:15:16 -0700509
510 // Find sectors to write the entry to. This may involve garbage collecting one
511 // or more sectors.
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700512 for (size_t i = 0; i < redundancy(); i++) {
Wyatt Heplerab3b2492020-03-11 16:15:16 -0700513 SectorDescriptor* sector;
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700514 TRY(GetSectorForWrite(&sector, entry_size, span(reserved_addresses, i)));
Wyatt Heplerab3b2492020-03-11 16:15:16 -0700515
Wyatt Heplerc84393f2020-03-20 11:23:24 -0700516 DBG("Found space for entry in sector %u", sectors_.Index(sector));
517 reserved_addresses[i] = sectors_.NextWritableAddress(*sector);
Wyatt Heplerab3b2492020-03-11 16:15:16 -0700518 }
519
520 // Write the entry at the first address that was found.
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700521 Entry entry = CreateEntry(reserved_addresses[0], key, value, new_state);
Wyatt Heplerab3b2492020-03-11 16:15:16 -0700522 TRY(AppendEntry(entry, key, value));
523
524 // After writing the first entry successfully, update the key descriptors.
525 // Once a single new the entry is written, the old entries are invalidated.
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700526 EntryMetadata new_metadata =
527 UpdateKeyDescriptor(entry, key, prior_metadata, prior_size);
Wyatt Heplerab3b2492020-03-11 16:15:16 -0700528
529 // Write the additional copies of the entry, if redundancy is greater than 1.
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700530 for (size_t i = 1; i < redundancy(); ++i) {
531 entry.set_address(reserved_addresses[i]);
Wyatt Heplerab3b2492020-03-11 16:15:16 -0700532 TRY(AppendEntry(entry, key, value));
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700533 new_metadata.AddNewAddress(reserved_addresses[i]);
Wyatt Heplerab3b2492020-03-11 16:15:16 -0700534 }
Wyatt Heplerb7609542020-01-24 10:29:54 -0800535 return Status::OK;
536}
537
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700538KeyValueStore::EntryMetadata KeyValueStore::UpdateKeyDescriptor(
Wyatt Heplerab3b2492020-03-11 16:15:16 -0700539 const Entry& entry,
540 string_view key,
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700541 EntryMetadata* prior_metadata,
Wyatt Heplerab3b2492020-03-11 16:15:16 -0700542 size_t prior_size) {
543 // If there is no prior descriptor, create a new one.
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700544 if (prior_metadata == nullptr) {
545 return entry_cache_.AddNew(entry.descriptor(key), entry.address());
David Rogersa2562b52020-03-05 15:30:05 -0800546 }
547
Wyatt Heplerab3b2492020-03-11 16:15:16 -0700548 // Remove valid bytes for the old entry and its copies, which are now stale.
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700549 for (Address address : prior_metadata->addresses()) {
Wyatt Heplerc84393f2020-03-20 11:23:24 -0700550 sectors_.FromAddress(address).RemoveValidBytes(prior_size);
David Rogersa2562b52020-03-05 15:30:05 -0800551 }
552
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700553 prior_metadata->Reset(entry.descriptor(key), entry.address());
554 return *prior_metadata;
David Rogersa2562b52020-03-05 15:30:05 -0800555}
556
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700557// Finds a sector to use for writing a new entry to. Does automatic garbage
David Rogersa2562b52020-03-05 15:30:05 -0800558// collection if needed and allowed.
559//
560// OK: Sector found with needed space.
561// RESOURCE_EXHAUSTED: No sector available with the needed space.
562Status KeyValueStore::GetSectorForWrite(SectorDescriptor** sector,
563 size_t entry_size,
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700564 span<const Address> reserved) {
Wyatt Heplerc84393f2020-03-20 11:23:24 -0700565 Status result = sectors_.FindSpace(sector, entry_size, reserved);
David Rogersa2562b52020-03-05 15:30:05 -0800566
David Rogersf3884eb2020-03-08 19:21:40 -0700567 size_t gc_sector_count = 0;
David Rogersa2562b52020-03-05 15:30:05 -0800568 bool do_auto_gc = options_.gc_on_write != GargbageCollectOnWrite::kDisabled;
569
570 // Do garbage collection as needed, so long as policy allows.
571 while (result == Status::RESOURCE_EXHAUSTED && do_auto_gc) {
572 if (options_.gc_on_write == GargbageCollectOnWrite::kOneSector) {
573 // If GC config option is kOneSector clear the flag to not do any more
574 // GC after this try.
575 do_auto_gc = false;
576 }
577 // Garbage collect and then try again to find the best sector.
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700578 Status gc_status = GarbageCollectPartial(reserved);
David Rogersa2562b52020-03-05 15:30:05 -0800579 if (!gc_status.ok()) {
580 if (gc_status == Status::NOT_FOUND) {
581 // Not enough space, and no reclaimable bytes, this KVS is full!
582 return Status::RESOURCE_EXHAUSTED;
583 }
584 return gc_status;
585 }
586
Wyatt Heplerc84393f2020-03-20 11:23:24 -0700587 result = sectors_.FindSpace(sector, entry_size, reserved);
David Rogersf3884eb2020-03-08 19:21:40 -0700588
589 gc_sector_count++;
590 // Allow total sectors + 2 number of GC cycles so that once reclaimable
591 // bytes in all the sectors have been reclaimed can try and free up space by
592 // moving entries for keys other than the one being worked on in to sectors
593 // that have copies of the key trying to be written.
594 if (gc_sector_count > (partition_.sector_count() + 2)) {
595 ERR("Did more GC sectors than total sectors!!!!");
596 return Status::RESOURCE_EXHAUSTED;
597 }
David Rogersa2562b52020-03-05 15:30:05 -0800598 }
599
600 if (!result.ok()) {
601 WRN("Unable to find sector to write %zu B", entry_size);
602 }
603 return result;
604}
605
Wyatt Heplerab3b2492020-03-11 16:15:16 -0700606Status KeyValueStore::AppendEntry(const Entry& entry,
David Rogersa2562b52020-03-05 15:30:05 -0800607 string_view key,
608 span<const byte> value) {
Wyatt Heplerab3b2492020-03-11 16:15:16 -0700609 const StatusWithSize result = entry.Write(key, value);
David Rogersa2562b52020-03-05 15:30:05 -0800610
David Rogersa2562b52020-03-05 15:30:05 -0800611 // Remove any bytes that were written, even if the write was not successful.
612 // This is important to retain the writable space invariant on the sectors.
Wyatt Heplerc84393f2020-03-20 11:23:24 -0700613 SectorDescriptor& sector = sectors_.FromAddress(entry.address());
614 sector.RemoveWritableBytes(result.size());
David Rogersa2562b52020-03-05 15:30:05 -0800615
616 if (!result.ok()) {
617 ERR("Failed to write %zu bytes at %#zx. %zu actually written",
618 entry.size(),
Wyatt Heplerab3b2492020-03-11 16:15:16 -0700619 size_t(entry.address()),
David Rogersa2562b52020-03-05 15:30:05 -0800620 result.size());
621 return result.status();
622 }
623
624 if (options_.verify_on_write) {
625 TRY(entry.VerifyChecksumInFlash());
626 }
627
Wyatt Heplerc84393f2020-03-20 11:23:24 -0700628 sector.AddValidBytes(result.size());
David Rogersa2562b52020-03-05 15:30:05 -0800629 return Status::OK;
630}
631
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700632Status KeyValueStore::RelocateEntry(const EntryMetadata& metadata,
Wyatt Heplerab3b2492020-03-11 16:15:16 -0700633 KeyValueStore::Address& address,
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700634 span<const Address> reserved_addresses) {
David Rogersa2562b52020-03-05 15:30:05 -0800635 Entry entry;
Wyatt Heplerab3b2492020-03-11 16:15:16 -0700636 TRY(Entry::Read(partition_, address, formats_, &entry));
David Rogersa2562b52020-03-05 15:30:05 -0800637
638 // Find a new sector for the entry and write it to the new location. For
639 // relocation the find should not not be a sector already containing the key
640 // but can be the always empty sector, since this is part of the GC process
641 // that will result in a new empty sector. Also find a sector that does not
642 // have reclaimable space (mostly for the full GC, where that would result in
643 // an immediate extra relocation).
644 SectorDescriptor* new_sector;
645
Wyatt Heplerc84393f2020-03-20 11:23:24 -0700646 TRY(sectors_.FindSpaceDuringGarbageCollection(
647 &new_sector, entry.size(), metadata.addresses(), reserved_addresses));
Wyatt Heplerab3b2492020-03-11 16:15:16 -0700648
Wyatt Heplerc84393f2020-03-20 11:23:24 -0700649 const Address new_address = sectors_.NextWritableAddress(*new_sector);
Wyatt Heplerab3b2492020-03-11 16:15:16 -0700650 const StatusWithSize result = entry.Copy(new_address);
651 new_sector->RemoveWritableBytes(result.size());
652 TRY(result);
David Rogersa2562b52020-03-05 15:30:05 -0800653
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700654 // Entry was written successfully; update descriptor's address and the sector
David Rogersa2562b52020-03-05 15:30:05 -0800655 // descriptors to reflect the new entry.
Wyatt Heplerc84393f2020-03-20 11:23:24 -0700656 sectors_.FromAddress(address).RemoveValidBytes(result.size());
Wyatt Heplerab3b2492020-03-11 16:15:16 -0700657 new_sector->AddValidBytes(result.size());
658 address = new_address;
David Rogersa2562b52020-03-05 15:30:05 -0800659
660 return Status::OK;
661}
662
David Rogerscd87c322020-02-27 14:04:08 -0800663Status KeyValueStore::GarbageCollectFull() {
664 DBG("Garbage Collect all sectors");
Wyatt Heplerc84393f2020-03-20 11:23:24 -0700665
666 SectorDescriptor* sector = sectors_.last_new();
David Rogerscd87c322020-02-27 14:04:08 -0800667
668 // TODO: look in to making an iterator method for cycling through sectors
669 // starting from last_new_sector_.
670 for (size_t j = 0; j < sectors_.size(); j++) {
671 sector += 1;
672 if (sector == sectors_.end()) {
673 sector = sectors_.begin();
674 }
675
676 if (sector->RecoverableBytes(partition_.sector_size_bytes()) > 0) {
Wyatt Heplerc84393f2020-03-20 11:23:24 -0700677 TRY(GarbageCollectSector(*sector, {}));
David Rogerscd87c322020-02-27 14:04:08 -0800678 }
679 }
680
681 DBG("Garbage Collect all complete");
David Rogerscd87c322020-02-27 14:04:08 -0800682 return Status::OK;
683}
684
David Rogersc9d545e2020-03-11 17:47:43 -0700685Status KeyValueStore::GarbageCollectPartial(
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700686 span<const Address> reserved_addresses) {
David Rogersc9d545e2020-03-11 17:47:43 -0700687 DBG("Garbage Collect a single sector");
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700688 for (Address address : reserved_addresses) {
David Rogersc9d545e2020-03-11 17:47:43 -0700689 DBG(" Avoid address %u", unsigned(address));
690 }
David Rogers67f4b6c2020-02-06 16:17:09 -0800691
David Rogersa12786b2020-01-31 16:02:33 -0800692 // Step 1: Find the sector to garbage collect
David Rogersc9d545e2020-03-11 17:47:43 -0700693 SectorDescriptor* sector_to_gc =
Wyatt Heplerc84393f2020-03-20 11:23:24 -0700694 sectors_.FindSectorToGarbageCollect(reserved_addresses);
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800695
David Rogersa12786b2020-01-31 16:02:33 -0800696 if (sector_to_gc == nullptr) {
David Rogersa2562b52020-03-05 15:30:05 -0800697 // Nothing to GC.
698 return Status::NOT_FOUND;
David Rogersa12786b2020-01-31 16:02:33 -0800699 }
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800700
David Rogersc9d545e2020-03-11 17:47:43 -0700701 // Step 2: Garbage collect the selected sector.
Wyatt Heplerc84393f2020-03-20 11:23:24 -0700702 return GarbageCollectSector(*sector_to_gc, reserved_addresses);
David Rogerscd87c322020-02-27 14:04:08 -0800703}
704
David Rogersf3884eb2020-03-08 19:21:40 -0700705Status KeyValueStore::RelocateKeyAddressesInSector(
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700706 SectorDescriptor& sector_to_gc,
707 const EntryMetadata& metadata,
708 span<const Address> reserved_addresses) {
709 for (FlashPartition::Address& address : metadata.addresses()) {
Wyatt Heplerc84393f2020-03-20 11:23:24 -0700710 if (sectors_.AddressInSector(sector_to_gc, address)) {
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700711 DBG(" Relocate entry for Key 0x%08" PRIx32 ", sector %u",
712 metadata.hash(),
Wyatt Heplerc84393f2020-03-20 11:23:24 -0700713 sectors_.Index(sectors_.FromAddress(address)));
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700714 TRY(RelocateEntry(metadata, address, reserved_addresses));
David Rogersf3884eb2020-03-08 19:21:40 -0700715 }
716 }
Wyatt Heplerab3b2492020-03-11 16:15:16 -0700717
David Rogersf3884eb2020-03-08 19:21:40 -0700718 return Status::OK;
719};
720
Wyatt Heplerab3b2492020-03-11 16:15:16 -0700721Status KeyValueStore::GarbageCollectSector(
Wyatt Heplerc84393f2020-03-20 11:23:24 -0700722 SectorDescriptor& sector_to_gc, span<const Address> reserved_addresses) {
David Rogersf3884eb2020-03-08 19:21:40 -0700723 // Step 1: Move any valid entries in the GC sector to other sectors
Wyatt Heplerc84393f2020-03-20 11:23:24 -0700724 if (sector_to_gc.valid_bytes() != 0) {
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700725 for (const EntryMetadata& metadata : entry_cache_) {
Wyatt Heplerab3b2492020-03-11 16:15:16 -0700726 TRY(RelocateKeyAddressesInSector(
Wyatt Heplerc84393f2020-03-20 11:23:24 -0700727 sector_to_gc, metadata, reserved_addresses));
David Rogersf3884eb2020-03-08 19:21:40 -0700728 }
729 }
730
Wyatt Heplerc84393f2020-03-20 11:23:24 -0700731 if (sector_to_gc.valid_bytes() != 0) {
David Rogers67f4b6c2020-02-06 16:17:09 -0800732 ERR(" Failed to relocate valid entries from sector being garbage "
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800733 "collected, %zu valid bytes remain",
Wyatt Heplerc84393f2020-03-20 11:23:24 -0700734 sector_to_gc.valid_bytes());
Wyatt Heplerb7609542020-01-24 10:29:54 -0800735 return Status::INTERNAL;
736 }
737
David Rogerscd87c322020-02-27 14:04:08 -0800738 // Step 2: Reinitialize the sector
Wyatt Heplerc84393f2020-03-20 11:23:24 -0700739 sector_to_gc.set_writable_bytes(0);
740 TRY(partition_.Erase(sectors_.BaseAddress(sector_to_gc), 1));
741 sector_to_gc.set_writable_bytes(partition_.sector_size_bytes());
Wyatt Heplerb7609542020-01-24 10:29:54 -0800742
Wyatt Heplerc84393f2020-03-20 11:23:24 -0700743 DBG(" Garbage Collect sector %u complete", sectors_.Index(sector_to_gc));
David Rogersa12786b2020-01-31 16:02:33 -0800744 return Status::OK;
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800745}
746
Wyatt Heplerbdd8e5a2020-02-20 19:27:26 -0800747KeyValueStore::Entry KeyValueStore::CreateEntry(Address address,
Wyatt Heplerab3b2492020-03-11 16:15:16 -0700748 string_view key,
Wyatt Heplerbdd8e5a2020-02-20 19:27:26 -0800749 span<const byte> value,
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700750 EntryState state) {
Keir Mierle9e38b402020-02-21 13:06:21 -0800751 // Always bump the transaction ID when creating a new entry.
752 //
753 // Burning transaction IDs prevents inconsistencies between flash and memory
754 // that which could happen if a write succeeds, but for some reason the read
755 // and verify step fails. Here's how this would happen:
756 //
757 // 1. The entry is written but for some reason the flash reports failure OR
758 // The write succeeds, but the read / verify operation fails.
759 // 2. The transaction ID is NOT incremented, because of the failure
760 // 3. (later) A new entry is written, re-using the transaction ID (oops)
761 //
762 // By always burning transaction IDs, the above problem can't happen.
763 last_transaction_id_ += 1;
764
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700765 if (state == EntryState::kDeleted) {
Wyatt Hepler7465be32020-02-21 15:30:53 -0800766 return Entry::Tombstone(
Wyatt Hepler22d0d9f2020-03-05 14:57:11 -0800767 partition_, address, formats_.primary(), key, last_transaction_id_);
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800768 }
769 return Entry::Valid(partition_,
770 address,
Wyatt Hepler22d0d9f2020-03-05 14:57:11 -0800771 formats_.primary(),
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800772 key,
773 value,
Keir Mierle9e38b402020-02-21 13:06:21 -0800774 last_transaction_id_);
Wyatt Heplerd2298282020-02-20 17:12:45 -0800775}
776
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700777void KeyValueStore::LogDebugInfo() const {
Keir Mierle8c352dc2020-02-02 13:58:19 -0800778 const size_t sector_size_bytes = partition_.sector_size_bytes();
779 DBG("====================== KEY VALUE STORE DUMP =========================");
780 DBG(" ");
781 DBG("Flash partition:");
Wyatt Heplerad0a7932020-02-06 08:20:38 -0800782 DBG(" Sector count = %zu", partition_.sector_count());
Wyatt Hepler38ce30f2020-02-19 11:48:31 -0800783 DBG(" Sector max count = %zu", sectors_.max_size());
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800784 DBG(" Sectors in use = %zu", sectors_.size());
Keir Mierle8c352dc2020-02-02 13:58:19 -0800785 DBG(" Sector size = %zu", sector_size_bytes);
786 DBG(" Total size = %zu", partition_.size_bytes());
787 DBG(" Alignment = %zu", partition_.alignment_bytes());
788 DBG(" ");
789 DBG("Key descriptors:");
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700790 DBG(" Entry count = %zu", entry_cache_.total_entries());
791 DBG(" Max entry count = %zu", entry_cache_.max_entries());
Keir Mierle8c352dc2020-02-02 13:58:19 -0800792 DBG(" ");
793 DBG(" # hash version address address (hex)");
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700794 size_t i = 0;
795 for (const EntryMetadata& metadata : entry_cache_) {
Keir Mierle8c352dc2020-02-02 13:58:19 -0800796 DBG(" |%3zu: | %8zx |%8zu | %8zu | %8zx",
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700797 i++,
798 size_t(metadata.hash()),
799 size_t(metadata.transaction_id()),
800 size_t(metadata.first_address()),
801 size_t(metadata.first_address()));
Keir Mierle8c352dc2020-02-02 13:58:19 -0800802 }
803 DBG(" ");
804
805 DBG("Sector descriptors:");
806 DBG(" # tail free valid has_space");
Wyatt Heplerc84393f2020-03-20 11:23:24 -0700807 for (const SectorDescriptor& sd : sectors_) {
808 DBG(" |%3u: | %8zu |%8zu | %s",
809 sectors_.Index(sd),
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800810 size_t(sd.writable_bytes()),
811 sd.valid_bytes(),
812 sd.writable_bytes() ? "YES" : "");
Keir Mierle8c352dc2020-02-02 13:58:19 -0800813 }
814 DBG(" ");
815
816 // TODO: This should stop logging after some threshold.
817 // size_t dumped_bytes = 0;
818 DBG("Sector raw data:");
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800819 for (size_t sector_id = 0; sector_id < sectors_.size(); ++sector_id) {
Keir Mierle8c352dc2020-02-02 13:58:19 -0800820 // Read sector data. Yes, this will blow the stack on embedded.
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800821 std::array<byte, 500> raw_sector_data; // TODO!!!
Keir Mierle8c352dc2020-02-02 13:58:19 -0800822 StatusWithSize sws =
823 partition_.Read(sector_id * sector_size_bytes, raw_sector_data);
824 DBG("Read: %zu bytes", sws.size());
825
826 DBG(" base addr offs 0 1 2 3 4 5 6 7");
827 for (size_t i = 0; i < sector_size_bytes; i += 8) {
828 DBG(" %3zu %8zx %5zu | %02x %02x %02x %02x %02x %02x %02x %02x",
829 sector_id,
830 (sector_id * sector_size_bytes) + i,
831 i,
832 static_cast<unsigned int>(raw_sector_data[i + 0]),
833 static_cast<unsigned int>(raw_sector_data[i + 1]),
834 static_cast<unsigned int>(raw_sector_data[i + 2]),
835 static_cast<unsigned int>(raw_sector_data[i + 3]),
836 static_cast<unsigned int>(raw_sector_data[i + 4]),
837 static_cast<unsigned int>(raw_sector_data[i + 5]),
838 static_cast<unsigned int>(raw_sector_data[i + 6]),
839 static_cast<unsigned int>(raw_sector_data[i + 7]));
840
841 // TODO: Fix exit condition.
842 if (i > 128) {
843 break;
844 }
845 }
846 DBG(" ");
847 }
848
849 DBG("////////////////////// KEY VALUE STORE DUMP END /////////////////////");
850}
851
David Rogerscf680ab2020-02-12 23:28:32 -0800852void KeyValueStore::LogSectors() const {
853 DBG("Sector descriptors: count %zu", sectors_.size());
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800854 for (auto& sector : sectors_) {
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800855 DBG(" - Sector %u: valid %zu, recoverable %zu, free %zu",
Wyatt Heplerc84393f2020-03-20 11:23:24 -0700856 sectors_.Index(sector),
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800857 sector.valid_bytes(),
858 sector.RecoverableBytes(partition_.sector_size_bytes()),
859 sector.writable_bytes());
David Rogers50185ad2020-02-07 00:02:46 -0800860 }
861}
862
David Rogerscf680ab2020-02-12 23:28:32 -0800863void KeyValueStore::LogKeyDescriptor() const {
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700864 DBG("Key descriptors: count %zu", entry_cache_.total_entries());
865 for (auto& metadata : entry_cache_) {
866 DBG(" - Key: %s, hash %#zx, transaction ID %zu, first address %#zx",
Wyatt Hepler02946272020-03-18 10:36:22 -0700867 metadata.state() == EntryState::kDeleted ? "Deleted" : "Valid",
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700868 static_cast<size_t>(metadata.hash()),
869 static_cast<size_t>(metadata.transaction_id()),
870 static_cast<size_t>(metadata.first_address()));
David Rogerscf680ab2020-02-12 23:28:32 -0800871 }
872}
873
Wyatt Hepler2ad60672020-01-21 08:00:16 -0800874} // namespace pw::kvs