blob: 2ad68fa4a96b6b0650f12c628c68fd2f738e6bf3 [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
Wyatt Heplerab3b2492020-03-11 16:15:16 -070036// Returns true if the container conatins the value.
37// TODO: At some point move this to pw_containers, along with adding tests.
38template <typename Container, typename T>
39bool Contains(const Container& container, const T& value) {
40 return std::find(std::begin(container), std::end(container), value) !=
41 std::end(container);
42}
43
Wyatt Heplera00d1ef2020-02-14 14:31:26 -080044} // namespace
45
Wyatt Heplerad0a7932020-02-06 08:20:38 -080046KeyValueStore::KeyValueStore(FlashPartition* partition,
Wyatt Hepler22d0d9f2020-03-05 14:57:11 -080047 span<const EntryFormat> formats,
Wyatt Hepler7ded6da2020-03-11 18:24:43 -070048 const Options& options,
49 size_t redundancy,
50 Vector<SectorDescriptor>& sector_descriptor_list,
51 const SectorDescriptor** temp_sectors_to_skip,
52 Vector<KeyDescriptor>& key_descriptor_list,
53 Address* addresses)
Wyatt Heplerad0a7932020-02-06 08:20:38 -080054 : partition_(*partition),
Wyatt Hepler22d0d9f2020-03-05 14:57:11 -080055 formats_(formats),
Wyatt Hepler7ded6da2020-03-11 18:24:43 -070056 entry_cache_(key_descriptor_list, addresses, redundancy),
Wyatt Heplerd2298282020-02-20 17:12:45 -080057 sectors_(sector_descriptor_list),
Wyatt Hepler7ded6da2020-03-11 18:24:43 -070058 temp_sectors_to_skip_(temp_sectors_to_skip),
Wyatt Heplerd2298282020-02-20 17:12:45 -080059 options_(options) {
Keir Mierlebf904812020-03-11 17:28:22 -070060 initialized_ = false;
61 last_new_sector_ = nullptr;
62 last_transaction_id_ = 0;
Wyatt Heplerd2298282020-02-20 17:12:45 -080063}
Wyatt Heplerad0a7932020-02-06 08:20:38 -080064
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -080065Status KeyValueStore::Init() {
Keir Mierlebf904812020-03-11 17:28:22 -070066 initialized_ = false;
67 last_new_sector_ = nullptr;
68 last_transaction_id_ = 0;
Wyatt Hepler7ded6da2020-03-11 18:24:43 -070069 entry_cache_.Reset();
Wyatt Heplerd2298282020-02-20 17:12:45 -080070
David Rogers2e9e0c82020-02-13 15:06:06 -080071 INF("Initializing key value store");
Wyatt Hepler38ce30f2020-02-19 11:48:31 -080072 if (partition_.sector_count() > sectors_.max_size()) {
David Rogers2e9e0c82020-02-13 15:06:06 -080073 ERR("KVS init failed: kMaxUsableSectors (=%zu) must be at least as "
74 "large as the number of sectors in the flash partition (=%zu)",
Wyatt Hepler38ce30f2020-02-19 11:48:31 -080075 sectors_.max_size(),
David Rogers2e9e0c82020-02-13 15:06:06 -080076 partition_.sector_count());
Wyatt Heplerad0a7932020-02-06 08:20:38 -080077 return Status::FAILED_PRECONDITION;
78 }
79
Keir Mierle8c352dc2020-02-02 13:58:19 -080080 const size_t sector_size_bytes = partition_.sector_size_bytes();
Keir Mierle8c352dc2020-02-02 13:58:19 -080081
82 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
Wyatt Heplerd2298282020-02-20 17:12:45 -080085 sectors_.assign(partition_.sector_count(),
86 SectorDescriptor(sector_size_bytes));
87
Alexei Frolovd4adf912020-02-21 13:29:15 -080088 size_t total_corrupt_bytes = 0;
89 int corrupt_entries = 0;
David Rogers91627482020-02-27 17:38:12 -080090 bool empty_sector_found = false;
Alexei Frolovd4adf912020-02-21 13:29:15 -080091
Wyatt Hepler2c7eca02020-02-18 16:01:42 -080092 for (SectorDescriptor& sector : sectors_) {
Keir Mierle8c352dc2020-02-02 13:58:19 -080093 Address entry_address = sector_address;
94
Alexei Frolovd4adf912020-02-21 13:29:15 -080095 size_t sector_corrupt_bytes = 0;
96
Wyatt Hepler2c7eca02020-02-18 16:01:42 -080097 for (int num_entries_in_sector = 0; true; num_entries_in_sector++) {
98 DBG("Load entry: sector=%" PRIx32 ", entry#=%d, address=%" PRIx32,
99 sector_address,
Keir Mierle8c352dc2020-02-02 13:58:19 -0800100 num_entries_in_sector,
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800101 entry_address);
Keir Mierle8c352dc2020-02-02 13:58:19 -0800102
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800103 if (!AddressInSector(sector, entry_address)) {
Keir Mierle8c352dc2020-02-02 13:58:19 -0800104 DBG("Fell off end of sector; moving to the next sector");
105 break;
106 }
107
108 Address next_entry_address;
109 Status status = LoadEntry(entry_address, &next_entry_address);
110 if (status == Status::NOT_FOUND) {
111 DBG("Hit un-written data in sector; moving to the next sector");
112 break;
113 }
114 if (status == Status::DATA_LOSS) {
Alexei Frolovd4adf912020-02-21 13:29:15 -0800115 // The entry could not be read, indicating data corruption within the
116 // sector. Try to scan the remainder of the sector for other entries.
David Rogersa2562b52020-03-05 15:30:05 -0800117 WRN("KVS init: data loss detected in sector %u at address %zu",
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800118 SectorIndex(&sector),
119 size_t(entry_address));
Alexei Frolovd4adf912020-02-21 13:29:15 -0800120
121 corrupt_entries++;
122
123 status = ScanForEntry(sector,
124 entry_address + Entry::kMinAlignmentBytes,
125 &next_entry_address);
126 if (status == Status::NOT_FOUND) {
127 // No further entries in this sector. Mark the remaining bytes in the
128 // sector as corrupt (since we can't reliably know the size of the
129 // corrupt entry).
130 sector_corrupt_bytes +=
131 sector_size_bytes - (entry_address - sector_address);
132 break;
133 }
134
135 if (!status.ok()) {
136 ERR("Unexpected error in KVS initialization: %s", status.str());
137 return Status::UNKNOWN;
138 }
139
140 sector_corrupt_bytes += next_entry_address - entry_address;
141 } else if (!status.ok()) {
142 ERR("Unexpected error in KVS initialization: %s", status.str());
143 return Status::UNKNOWN;
Keir Mierle8c352dc2020-02-02 13:58:19 -0800144 }
Keir Mierle8c352dc2020-02-02 13:58:19 -0800145
146 // Entry loaded successfully; so get ready to load the next one.
147 entry_address = next_entry_address;
148
149 // Update of the number of writable bytes in this sector.
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800150 sector.set_writable_bytes(sector_size_bytes -
151 (entry_address - sector_address));
Keir Mierle8c352dc2020-02-02 13:58:19 -0800152 }
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800153
Alexei Frolovd4adf912020-02-21 13:29:15 -0800154 if (sector_corrupt_bytes > 0) {
155 // If the sector contains corrupt data, prevent any further entries from
156 // being written to it by indicating that it has no space. This should
157 // also make it a decent GC candidate. Valid keys in the sector are still
158 // readable as normal.
159 sector.set_writable_bytes(0);
160
161 WRN("Sector %u contains %zuB of corrupt data",
162 SectorIndex(&sector),
163 sector_corrupt_bytes);
164 }
165
David Rogers91627482020-02-27 17:38:12 -0800166 if (sector.Empty(sector_size_bytes)) {
167 empty_sector_found = true;
168 }
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800169 sector_address += sector_size_bytes;
Alexei Frolovd4adf912020-02-21 13:29:15 -0800170 total_corrupt_bytes += sector_corrupt_bytes;
Keir Mierle8c352dc2020-02-02 13:58:19 -0800171 }
172
173 DBG("Second pass: Count valid bytes in each sector");
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700174 Address newest_key = 0;
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800175
Keir Mierle8c352dc2020-02-02 13:58:19 -0800176 // For every valid key, increment the valid bytes for that sector.
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700177
178 for (const EntryMetadata& metadata : entry_cache_) {
179 for (Address address : metadata.addresses()) {
David Rogersf56131c2020-03-04 10:19:22 -0800180 Entry entry;
David Rogersa2562b52020-03-05 15:30:05 -0800181 TRY(Entry::Read(partition_, address, formats_, &entry));
David Rogersf56131c2020-03-04 10:19:22 -0800182 SectorFromAddress(address)->AddValidBytes(entry.size());
183 }
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700184 if (metadata.IsNewerThan(last_transaction_id_)) {
185 last_transaction_id_ = metadata.transaction_id();
186 newest_key = metadata.addresses().back();
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800187 }
Keir Mierle8c352dc2020-02-02 13:58:19 -0800188 }
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800189
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700190 last_new_sector_ = SectorFromAddress(newest_key);
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800191
David Rogers91627482020-02-27 17:38:12 -0800192 if (!empty_sector_found) {
193 // TODO: Record/report the error condition and recovery result.
194 Status gc_result = GarbageCollectPartial();
195
196 if (!gc_result.ok()) {
197 ERR("KVS init failed: Unable to maintain required free sector");
198 return Status::INTERNAL;
199 }
200 }
201
Wyatt Hepler729f28c2020-02-05 09:46:00 -0800202 initialized_ = true;
David Rogers2e9e0c82020-02-13 15:06:06 -0800203
Armando Montanez5464d5f2020-02-20 10:12:20 -0800204 INF("KeyValueStore init complete: active keys %zu, deleted keys %zu, sectors "
David Rogers2e9e0c82020-02-13 15:06:06 -0800205 "%zu, logical sector size %zu bytes",
206 size(),
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700207 (entry_cache_.total_entries() - size()),
David Rogers2e9e0c82020-02-13 15:06:06 -0800208 sectors_.size(),
209 partition_.sector_size_bytes());
210
Alexei Frolovd4adf912020-02-21 13:29:15 -0800211 if (total_corrupt_bytes > 0) {
212 WRN("Found %zu corrupt bytes and %d corrupt entries during init process; "
213 "some keys may be missing",
214 total_corrupt_bytes,
215 corrupt_entries);
216 return Status::DATA_LOSS;
217 }
218
Keir Mierle8c352dc2020-02-02 13:58:19 -0800219 return Status::OK;
220}
221
Alexei Frolov9e235832020-02-24 12:44:45 -0800222KeyValueStore::StorageStats KeyValueStore::GetStorageStats() const {
223 StorageStats stats{0, 0, 0};
224 const size_t sector_size = partition_.sector_size_bytes();
225 bool found_empty_sector = false;
226
227 for (const SectorDescriptor& sector : sectors_) {
228 stats.in_use_bytes += sector.valid_bytes();
229 stats.reclaimable_bytes += sector.RecoverableBytes(sector_size);
230
231 if (!found_empty_sector && sector.Empty(sector_size)) {
232 // The KVS tries to always keep an empty sector for GC, so don't count
233 // the first empty sector seen as writable space. However, a free sector
234 // cannot always be assumed to exist; if a GC operation fails, all sectors
235 // may be partially written, in which case the space reported might be
236 // inaccurate.
237 found_empty_sector = true;
238 continue;
239 }
240
241 stats.writable_bytes += sector.writable_bytes();
242 }
243
244 return stats;
245}
246
Keir Mierle8c352dc2020-02-02 13:58:19 -0800247Status KeyValueStore::LoadEntry(Address entry_address,
248 Address* next_entry_address) {
Wyatt Heplere541e072020-02-14 09:10:53 -0800249 Entry entry;
Wyatt Hepler22d0d9f2020-03-05 14:57:11 -0800250 TRY(Entry::Read(partition_, entry_address, formats_, &entry));
Keir Mierle8c352dc2020-02-02 13:58:19 -0800251
252 // Read the key from flash & validate the entry (which reads the value).
Wyatt Heplera00d1ef2020-02-14 14:31:26 -0800253 Entry::KeyBuffer key_buffer;
Wyatt Heplere541e072020-02-14 09:10:53 -0800254 TRY_ASSIGN(size_t key_length, entry.ReadKey(key_buffer));
255 const string_view key(key_buffer.data(), key_length);
Wyatt Heplerbab0e202020-02-04 07:40:08 -0800256
Wyatt Hepler22d0d9f2020-03-05 14:57:11 -0800257 TRY(entry.VerifyChecksumInFlash());
David Rogersf56131c2020-03-04 10:19:22 -0800258
259 // A valid entry was found, so update the next entry address before doing any
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700260 // of the checks that happen in AddNewOrUpdateExisting.
David Rogersf56131c2020-03-04 10:19:22 -0800261 *next_entry_address = entry.next_address();
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700262 return entry_cache_.AddNewOrUpdateExisting(
263 entry.descriptor(key), entry.address(), partition_.sector_size_bytes());
Keir Mierle8c352dc2020-02-02 13:58:19 -0800264}
265
Alexei Frolovd4adf912020-02-21 13:29:15 -0800266// Scans flash memory within a sector to find a KVS entry magic.
Alexei Frolovd4adf912020-02-21 13:29:15 -0800267Status KeyValueStore::ScanForEntry(const SectorDescriptor& sector,
268 Address start_address,
269 Address* next_entry_address) {
270 DBG("Scanning sector %u for entries starting from address %zx",
271 SectorIndex(&sector),
272 size_t(start_address));
273
274 // Entries must start at addresses which are aligned on a multiple of
275 // Entry::kMinAlignmentBytes. However, that multiple can vary between entries.
276 // When scanning, we don't have an entry to tell us what the current alignment
277 // is, so the minimum alignment is used to be exhaustive.
278 for (Address address = AlignUp(start_address, Entry::kMinAlignmentBytes);
279 AddressInSector(sector, address);
280 address += Entry::kMinAlignmentBytes) {
Alexei Frolovd4adf912020-02-21 13:29:15 -0800281 uint32_t magic;
282 TRY(partition_.Read(address, as_writable_bytes(span(&magic, 1))));
Wyatt Hepler22d0d9f2020-03-05 14:57:11 -0800283 if (formats_.KnownMagic(magic)) {
Alexei Frolovd4adf912020-02-21 13:29:15 -0800284 DBG("Found entry magic at address %zx", size_t(address));
285 *next_entry_address = address;
286 return Status::OK;
287 }
288 }
289
290 return Status::NOT_FOUND;
291}
292
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800293StatusWithSize KeyValueStore::Get(string_view key,
Wyatt Hepler5f6efc02020-02-18 16:54:31 -0800294 span<byte> value_buffer,
295 size_t offset_bytes) const {
Wyatt Hepler50f70772020-02-13 11:25:10 -0800296 TRY_WITH_SIZE(CheckOperation(key));
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800297
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700298 EntryMetadata metadata;
299 TRY_WITH_SIZE(entry_cache_.FindExisting(partition_, key, &metadata));
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800300
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700301 return Get(key, metadata, value_buffer, offset_bytes);
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800302}
303
Wyatt Heplerfac81132020-02-27 17:26:33 -0800304Status KeyValueStore::PutBytes(string_view key, span<const byte> value) {
Keir Mierle8c352dc2020-02-02 13:58:19 -0800305 DBG("Writing key/value; key length=%zu, value length=%zu",
306 key.size(),
307 value.size());
Wyatt Hepler729f28c2020-02-05 09:46:00 -0800308
309 TRY(CheckOperation(key));
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800310
Wyatt Hepler5406a672020-02-18 15:42:38 -0800311 if (Entry::size(partition_, key, value) > partition_.sector_size_bytes()) {
312 DBG("%zu B value with %zu B key cannot fit in one sector",
313 value.size(),
314 key.size());
315 return Status::INVALID_ARGUMENT;
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800316 }
317
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700318 EntryMetadata metadata;
319 Status status = entry_cache_.Find(partition_, key, &metadata);
Wyatt Hepler2d401692020-02-13 16:01:23 -0800320
321 if (status.ok()) {
David Rogersf56131c2020-03-04 10:19:22 -0800322 // TODO: figure out logging how to support multiple addresses.
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700323 DBG("Overwriting entry for key 0x%08" PRIx32 " in %zu sectors including %u",
324 metadata.hash(),
325 metadata.addresses().size(),
326 SectorIndex(SectorFromAddress(metadata.first_address())));
327 return WriteEntryForExistingKey(metadata, EntryState::kValid, key, value);
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800328 }
David Rogers2761aeb2020-01-31 17:09:00 -0800329
Wyatt Hepler2d401692020-02-13 16:01:23 -0800330 if (status == Status::NOT_FOUND) {
331 return WriteEntryForNewKey(key, value);
332 }
333
334 return status;
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800335}
336
337Status KeyValueStore::Delete(string_view key) {
Wyatt Hepler729f28c2020-02-05 09:46:00 -0800338 TRY(CheckOperation(key));
339
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700340 EntryMetadata metadata;
341 TRY(entry_cache_.FindExisting(partition_, key, &metadata));
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800342
David Rogersf56131c2020-03-04 10:19:22 -0800343 // TODO: figure out logging how to support multiple addresses.
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700344 DBG("Writing tombstone for key 0x%08" PRIx32 " in %zu sectors including %u",
345 metadata.hash(),
346 metadata.addresses().size(),
347 SectorIndex(SectorFromAddress(metadata.first_address())));
348 return WriteEntryForExistingKey(metadata, EntryState::kDeleted, key, {});
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800349}
350
Wyatt Hepler08d37d82020-02-27 15:45:37 -0800351void KeyValueStore::Item::ReadKey() {
352 key_buffer_.fill('\0');
353
354 Entry entry;
David Rogersf3884eb2020-03-08 19:21:40 -0700355 // TODO: add support for using one of the redundant entries if reading the
356 // first copy fails.
Wyatt Hepler22d0d9f2020-03-05 14:57:11 -0800357 if (Entry::Read(
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700358 kvs_.partition_, iterator_->first_address(), kvs_.formats_, &entry)
Wyatt Hepler22d0d9f2020-03-05 14:57:11 -0800359 .ok()) {
Wyatt Hepler08d37d82020-02-27 15:45:37 -0800360 entry.ReadKey(key_buffer_);
361 }
362}
363
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800364KeyValueStore::iterator& KeyValueStore::iterator::operator++() {
365 // Skip to the next entry that is valid (not deleted).
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700366 while (++item_.iterator_ != item_.kvs_.entry_cache_.end() &&
367 item_.iterator_->deleted()) {
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800368 }
369 return *this;
370}
371
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800372KeyValueStore::iterator KeyValueStore::begin() const {
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700373 internal::EntryCache::iterator cache_iterator = entry_cache_.begin();
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800374 // Skip over any deleted entries at the start of the descriptor list.
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700375 while (cache_iterator != entry_cache_.end() && cache_iterator->deleted()) {
376 ++cache_iterator;
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800377 }
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700378 return iterator(*this, cache_iterator);
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800379}
380
Wyatt Heplerab3b2492020-03-11 16:15:16 -0700381StatusWithSize KeyValueStore::ValueSize(string_view key) const {
Wyatt Hepler50f70772020-02-13 11:25:10 -0800382 TRY_WITH_SIZE(CheckOperation(key));
Wyatt Heplered163b02020-02-03 17:49:32 -0800383
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700384 EntryMetadata metadata;
385 TRY_WITH_SIZE(entry_cache_.FindExisting(partition_, key, &metadata));
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800386
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700387 return ValueSize(metadata);
Wyatt Heplerfac81132020-02-27 17:26:33 -0800388}
Wyatt Heplered163b02020-02-03 17:49:32 -0800389
Wyatt Heplerfac81132020-02-27 17:26:33 -0800390StatusWithSize KeyValueStore::Get(string_view key,
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700391 const EntryMetadata& metadata,
Wyatt Heplerfac81132020-02-27 17:26:33 -0800392 span<std::byte> value_buffer,
393 size_t offset_bytes) const {
394 Entry entry;
David Rogersa2562b52020-03-05 15:30:05 -0800395 // TODO: add support for using one of the redundant entries if reading the
396 // first copy fails.
Wyatt Hepler22d0d9f2020-03-05 14:57:11 -0800397 TRY_WITH_SIZE(
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700398 Entry::Read(partition_, metadata.first_address(), formats_, &entry));
Wyatt Heplerfac81132020-02-27 17:26:33 -0800399
400 StatusWithSize result = entry.ReadValue(value_buffer, offset_bytes);
401 if (result.ok() && options_.verify_on_read && offset_bytes == 0u) {
Wyatt Hepler22d0d9f2020-03-05 14:57:11 -0800402 Status verify_result =
403 entry.VerifyChecksum(key, value_buffer.first(result.size()));
Wyatt Heplerfac81132020-02-27 17:26:33 -0800404 if (!verify_result.ok()) {
405 std::memset(value_buffer.data(), 0, result.size());
406 return StatusWithSize(verify_result, 0);
407 }
408
409 return StatusWithSize(verify_result, result.size());
410 }
411 return result;
Wyatt Heplered163b02020-02-03 17:49:32 -0800412}
413
Wyatt Hepler6e3a83b2020-02-04 07:36:45 -0800414Status KeyValueStore::FixedSizeGet(std::string_view key,
Wyatt Heplerfac81132020-02-27 17:26:33 -0800415 void* value,
416 size_t size_bytes) const {
417 TRY(CheckOperation(key));
418
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700419 EntryMetadata metadata;
420 TRY(entry_cache_.FindExisting(partition_, key, &metadata));
Wyatt Heplerfac81132020-02-27 17:26:33 -0800421
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700422 return FixedSizeGet(key, metadata, value, size_bytes);
Wyatt Heplerfac81132020-02-27 17:26:33 -0800423}
424
425Status KeyValueStore::FixedSizeGet(std::string_view key,
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700426 const EntryMetadata& metadata,
Wyatt Heplerfac81132020-02-27 17:26:33 -0800427 void* value,
Wyatt Hepler6e3a83b2020-02-04 07:36:45 -0800428 size_t size_bytes) const {
429 // Ensure that the size of the stored value matches the size of the type.
430 // Otherwise, report error. This check avoids potential memory corruption.
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700431 TRY_ASSIGN(const size_t actual_size, ValueSize(metadata));
Wyatt Heplerfac81132020-02-27 17:26:33 -0800432
433 if (actual_size != size_bytes) {
434 DBG("Requested %zu B read, but value is %zu B", size_bytes, actual_size);
Wyatt Hepler6e3a83b2020-02-04 07:36:45 -0800435 return Status::INVALID_ARGUMENT;
Wyatt Heplerbab0e202020-02-04 07:40:08 -0800436 }
Wyatt Heplerfac81132020-02-27 17:26:33 -0800437
438 StatusWithSize result =
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700439 Get(key, metadata, span(static_cast<byte*>(value), size_bytes), 0);
Wyatt Heplerfac81132020-02-27 17:26:33 -0800440
441 return result.status();
442}
443
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700444StatusWithSize KeyValueStore::ValueSize(const EntryMetadata& metadata) const {
Wyatt Heplerfac81132020-02-27 17:26:33 -0800445 Entry entry;
David Rogersf3884eb2020-03-08 19:21:40 -0700446 // TODO: add support for using one of the redundant entries if reading the
447 // first copy fails.
Wyatt Hepler22d0d9f2020-03-05 14:57:11 -0800448 TRY_WITH_SIZE(
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700449 Entry::Read(partition_, metadata.first_address(), formats_, &entry));
Wyatt Heplerfac81132020-02-27 17:26:33 -0800450
451 return StatusWithSize(entry.value_size());
Keir Mierle8c352dc2020-02-02 13:58:19 -0800452}
453
Wyatt Hepler729f28c2020-02-05 09:46:00 -0800454Status KeyValueStore::CheckOperation(string_view key) const {
Wyatt Hepleracaacf92020-01-24 10:58:30 -0800455 if (InvalidKey(key)) {
Wyatt Heplerb7609542020-01-24 10:29:54 -0800456 return Status::INVALID_ARGUMENT;
457 }
Wyatt Heplerd2298282020-02-20 17:12:45 -0800458 if (!initialized()) {
Wyatt Heplerb7609542020-01-24 10:29:54 -0800459 return Status::FAILED_PRECONDITION;
460 }
Wyatt Heplerb7609542020-01-24 10:29:54 -0800461 return Status::OK;
462}
463
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700464Status KeyValueStore::WriteEntryForExistingKey(EntryMetadata& metadata,
465 EntryState new_state,
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800466 string_view key,
467 span<const byte> value) {
Wyatt Heplerab3b2492020-03-11 16:15:16 -0700468 // Read the original entry to get the size for sector accounting purposes.
469 Entry entry;
David Rogersa2562b52020-03-05 15:30:05 -0800470 // TODO: add support for using one of the redundant entries if reading the
471 // first copy fails.
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700472 TRY(Entry::Read(partition_, metadata.first_address(), formats_, &entry));
Wyatt Hepler6c24c062020-02-05 15:30:49 -0800473
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700474 return WriteEntry(key, value, new_state, &metadata, entry.size());
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800475}
476
477Status KeyValueStore::WriteEntryForNewKey(string_view key,
478 span<const byte> value) {
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700479 if (entry_cache_.full()) {
Keir Mierle8c352dc2020-02-02 13:58:19 -0800480 WRN("KVS full: trying to store a new entry, but can't. Have %zu entries",
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700481 entry_cache_.total_entries());
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800482 return Status::RESOURCE_EXHAUSTED;
483 }
484
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700485 return WriteEntry(key, value, EntryState::kValid);
Wyatt Heplerab3b2492020-03-11 16:15:16 -0700486}
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800487
Wyatt Heplerab3b2492020-03-11 16:15:16 -0700488Status KeyValueStore::WriteEntry(string_view key,
489 span<const byte> value,
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700490 EntryState new_state,
491 EntryMetadata* prior_metadata,
Wyatt Heplerab3b2492020-03-11 16:15:16 -0700492 size_t prior_size) {
493 const size_t entry_size = Entry::size(partition_, key, value);
494
495 // List of addresses for sectors with space for this entry.
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700496 Address* reserved_addresses = entry_cache_.TempReservedAddressesForWrite();
Wyatt Heplerab3b2492020-03-11 16:15:16 -0700497
498 // Find sectors to write the entry to. This may involve garbage collecting one
499 // or more sectors.
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700500 for (size_t i = 0; i < redundancy(); i++) {
Wyatt Heplerab3b2492020-03-11 16:15:16 -0700501 SectorDescriptor* sector;
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700502 TRY(GetSectorForWrite(&sector, entry_size, span(reserved_addresses, i)));
Wyatt Heplerab3b2492020-03-11 16:15:16 -0700503
504 DBG("Found space for entry in sector %u", SectorIndex(sector));
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700505 reserved_addresses[i] = NextWritableAddress(sector);
Wyatt Heplerab3b2492020-03-11 16:15:16 -0700506 }
507
508 // Write the entry at the first address that was found.
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700509 Entry entry = CreateEntry(reserved_addresses[0], key, value, new_state);
Wyatt Heplerab3b2492020-03-11 16:15:16 -0700510 TRY(AppendEntry(entry, key, value));
511
512 // After writing the first entry successfully, update the key descriptors.
513 // Once a single new the entry is written, the old entries are invalidated.
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700514 EntryMetadata new_metadata =
515 UpdateKeyDescriptor(entry, key, prior_metadata, prior_size);
Wyatt Heplerab3b2492020-03-11 16:15:16 -0700516
517 // Write the additional copies of the entry, if redundancy is greater than 1.
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700518 for (size_t i = 1; i < redundancy(); ++i) {
519 entry.set_address(reserved_addresses[i]);
Wyatt Heplerab3b2492020-03-11 16:15:16 -0700520 TRY(AppendEntry(entry, key, value));
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700521 new_metadata.AddNewAddress(reserved_addresses[i]);
Wyatt Heplerab3b2492020-03-11 16:15:16 -0700522 }
Wyatt Heplerb7609542020-01-24 10:29:54 -0800523 return Status::OK;
524}
525
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700526KeyValueStore::EntryMetadata KeyValueStore::UpdateKeyDescriptor(
Wyatt Heplerab3b2492020-03-11 16:15:16 -0700527 const Entry& entry,
528 string_view key,
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700529 EntryMetadata* prior_metadata,
Wyatt Heplerab3b2492020-03-11 16:15:16 -0700530 size_t prior_size) {
531 // If there is no prior descriptor, create a new one.
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700532 if (prior_metadata == nullptr) {
533 return entry_cache_.AddNew(entry.descriptor(key), entry.address());
David Rogersa2562b52020-03-05 15:30:05 -0800534 }
535
Wyatt Heplerab3b2492020-03-11 16:15:16 -0700536 // Remove valid bytes for the old entry and its copies, which are now stale.
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700537 for (Address address : prior_metadata->addresses()) {
Wyatt Heplerab3b2492020-03-11 16:15:16 -0700538 SectorFromAddress(address)->RemoveValidBytes(prior_size);
David Rogersa2562b52020-03-05 15:30:05 -0800539 }
540
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700541 prior_metadata->Reset(entry.descriptor(key), entry.address());
542 return *prior_metadata;
David Rogersa2562b52020-03-05 15:30:05 -0800543}
544
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700545// Finds a sector to use for writing a new entry to. Does automatic garbage
David Rogersa2562b52020-03-05 15:30:05 -0800546// collection if needed and allowed.
547//
548// OK: Sector found with needed space.
549// RESOURCE_EXHAUSTED: No sector available with the needed space.
550Status KeyValueStore::GetSectorForWrite(SectorDescriptor** sector,
551 size_t entry_size,
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700552 span<const Address> reserved) {
David Rogersc9d545e2020-03-11 17:47:43 -0700553 Status result =
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700554 FindSectorWithSpace(sector, entry_size, kAppendEntry, {}, reserved);
David Rogersa2562b52020-03-05 15:30:05 -0800555
David Rogersf3884eb2020-03-08 19:21:40 -0700556 size_t gc_sector_count = 0;
David Rogersa2562b52020-03-05 15:30:05 -0800557 bool do_auto_gc = options_.gc_on_write != GargbageCollectOnWrite::kDisabled;
558
559 // Do garbage collection as needed, so long as policy allows.
560 while (result == Status::RESOURCE_EXHAUSTED && do_auto_gc) {
561 if (options_.gc_on_write == GargbageCollectOnWrite::kOneSector) {
562 // If GC config option is kOneSector clear the flag to not do any more
563 // GC after this try.
564 do_auto_gc = false;
565 }
566 // Garbage collect and then try again to find the best sector.
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700567 Status gc_status = GarbageCollectPartial(reserved);
David Rogersa2562b52020-03-05 15:30:05 -0800568 if (!gc_status.ok()) {
569 if (gc_status == Status::NOT_FOUND) {
570 // Not enough space, and no reclaimable bytes, this KVS is full!
571 return Status::RESOURCE_EXHAUSTED;
572 }
573 return gc_status;
574 }
575
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700576 result =
577 FindSectorWithSpace(sector, entry_size, kAppendEntry, {}, reserved);
David Rogersf3884eb2020-03-08 19:21:40 -0700578
579 gc_sector_count++;
580 // Allow total sectors + 2 number of GC cycles so that once reclaimable
581 // bytes in all the sectors have been reclaimed can try and free up space by
582 // moving entries for keys other than the one being worked on in to sectors
583 // that have copies of the key trying to be written.
584 if (gc_sector_count > (partition_.sector_count() + 2)) {
585 ERR("Did more GC sectors than total sectors!!!!");
586 return Status::RESOURCE_EXHAUSTED;
587 }
David Rogersa2562b52020-03-05 15:30:05 -0800588 }
589
590 if (!result.ok()) {
591 WRN("Unable to find sector to write %zu B", entry_size);
592 }
593 return result;
594}
595
Wyatt Heplerab3b2492020-03-11 16:15:16 -0700596Status KeyValueStore::AppendEntry(const Entry& entry,
David Rogersa2562b52020-03-05 15:30:05 -0800597 string_view key,
598 span<const byte> value) {
Wyatt Heplerab3b2492020-03-11 16:15:16 -0700599 const StatusWithSize result = entry.Write(key, value);
David Rogersa2562b52020-03-05 15:30:05 -0800600
David Rogersa2562b52020-03-05 15:30:05 -0800601 // Remove any bytes that were written, even if the write was not successful.
602 // This is important to retain the writable space invariant on the sectors.
Wyatt Heplerab3b2492020-03-11 16:15:16 -0700603 SectorDescriptor* const sector = SectorFromAddress(entry.address());
604 sector->RemoveWritableBytes(result.size());
David Rogersa2562b52020-03-05 15:30:05 -0800605
606 if (!result.ok()) {
607 ERR("Failed to write %zu bytes at %#zx. %zu actually written",
608 entry.size(),
Wyatt Heplerab3b2492020-03-11 16:15:16 -0700609 size_t(entry.address()),
David Rogersa2562b52020-03-05 15:30:05 -0800610 result.size());
611 return result.status();
612 }
613
614 if (options_.verify_on_write) {
615 TRY(entry.VerifyChecksumInFlash());
616 }
617
Wyatt Heplerab3b2492020-03-11 16:15:16 -0700618 sector->AddValidBytes(result.size());
David Rogersa2562b52020-03-05 15:30:05 -0800619 return Status::OK;
620}
621
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700622Status KeyValueStore::RelocateEntry(const EntryMetadata& metadata,
Wyatt Heplerab3b2492020-03-11 16:15:16 -0700623 KeyValueStore::Address& address,
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700624 span<const Address> reserved_addresses) {
David Rogersa2562b52020-03-05 15:30:05 -0800625 Entry entry;
Wyatt Heplerab3b2492020-03-11 16:15:16 -0700626 TRY(Entry::Read(partition_, address, formats_, &entry));
David Rogersa2562b52020-03-05 15:30:05 -0800627
628 // Find a new sector for the entry and write it to the new location. For
629 // relocation the find should not not be a sector already containing the key
630 // but can be the always empty sector, since this is part of the GC process
631 // that will result in a new empty sector. Also find a sector that does not
632 // have reclaimable space (mostly for the full GC, where that would result in
633 // an immediate extra relocation).
634 SectorDescriptor* new_sector;
635
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700636 TRY(FindSectorWithSpace(&new_sector,
637 entry.size(),
638 kGarbageCollect,
639 metadata.addresses(),
640 reserved_addresses));
Wyatt Heplerab3b2492020-03-11 16:15:16 -0700641
642 const Address new_address = NextWritableAddress(new_sector);
643 const StatusWithSize result = entry.Copy(new_address);
644 new_sector->RemoveWritableBytes(result.size());
645 TRY(result);
David Rogersa2562b52020-03-05 15:30:05 -0800646
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700647 // Entry was written successfully; update descriptor's address and the sector
David Rogersa2562b52020-03-05 15:30:05 -0800648 // descriptors to reflect the new entry.
Wyatt Heplerab3b2492020-03-11 16:15:16 -0700649 SectorFromAddress(address)->RemoveValidBytes(result.size());
650 new_sector->AddValidBytes(result.size());
651 address = new_address;
David Rogersa2562b52020-03-05 15:30:05 -0800652
653 return Status::OK;
654}
655
David Rogers8db5a722020-02-03 18:28:34 -0800656// Find either an existing sector with enough space that is not the sector to
657// skip, or an empty sector. Maintains the invariant that there is always at
David Rogersc8fe1f52020-02-27 14:04:08 -0800658// least 1 empty sector except during GC. On GC, skip sectors that have
659// reclaimable bytes.
Wyatt Hepler5a33d8c2020-02-06 09:32:58 -0800660Status KeyValueStore::FindSectorWithSpace(
661 SectorDescriptor** found_sector,
662 size_t size,
David Rogersc8fe1f52020-02-27 14:04:08 -0800663 FindSectorMode find_mode,
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700664 span<const Address> addresses_to_skip,
665 span<const Address> reserved_addresses) {
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800666 SectorDescriptor* first_empty_sector = nullptr;
David Rogersc8fe1f52020-02-27 14:04:08 -0800667 bool at_least_two_empty_sectors = (find_mode == kGarbageCollect);
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800668
David Rogersf3884eb2020-03-08 19:21:40 -0700669 // Used for the GC reclaimable bytes check
670 SectorDescriptor* non_empty_least_reclaimable_sector = nullptr;
671 const size_t sector_size_bytes = partition_.sector_size_bytes();
672
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700673 // Build a list of sectors to avoid.
674 //
675 // This is overly strict. reserved_addresses is populated when there are
676 // sectors reserved for a new entry. It is safe to garbage collect into
677 // these sectors, as long as there remains room for the pending entry. These
678 // reserved sectors could also be garbage collected if they have recoverable
679 // space. For simplicitly, avoid both the relocating key's redundant entries
680 // (addresses_to_skip) and the sectors reserved for pending writes
681 // (reserved_addresses).
682 // TODO(hepler): Look into improving garbage collection.
683 size_t sectors_to_skip = 0;
Wyatt Heplerab3b2492020-03-11 16:15:16 -0700684 for (Address address : addresses_to_skip) {
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700685 temp_sectors_to_skip_[sectors_to_skip++] = SectorFromAddress(address);
686 }
687 for (Address address : reserved_addresses) {
688 temp_sectors_to_skip_[sectors_to_skip++] = SectorFromAddress(address);
David Rogersa2562b52020-03-05 15:30:05 -0800689 }
690
David Rogersf3884eb2020-03-08 19:21:40 -0700691 DBG("Find sector with %zu bytes available, starting with sector %u, %s",
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800692 size,
David Rogersf3884eb2020-03-08 19:21:40 -0700693 SectorIndex(last_new_sector_),
694 (find_mode == kAppendEntry) ? "Append" : "GC");
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700695 for (size_t i = 0; i < sectors_to_skip; ++i) {
696 DBG(" Skip sector %u", SectorIndex(temp_sectors_to_skip_[i]));
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800697 }
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800698
David Rogers8ce55cd2020-02-04 19:41:48 -0800699 // The last_new_sector_ is the sector that was last selected as the "new empty
700 // sector" to write to. This last new sector is used as the starting point for
701 // the next "find a new empty sector to write to" operation. By using the last
702 // new sector as the start point we will cycle which empty sector is selected
703 // next, spreading the wear across all the empty sectors and get a wear
704 // leveling benefit, rather than putting more wear on the lower number
705 // sectors.
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800706 SectorDescriptor* sector = last_new_sector_;
David Rogers67f4b6c2020-02-06 16:17:09 -0800707
David Rogersf3884eb2020-03-08 19:21:40 -0700708 // Look for a sector to use with enough space. The search uses a 3 priority
David Rogerscd87c322020-02-27 14:04:08 -0800709 // tier process.
710 //
David Rogersc8fe1f52020-02-27 14:04:08 -0800711 // Tier 1 is sector that already has valid data. During GC only select a
712 // sector that has no reclaimable bytes. Immediately use the first matching
713 // sector that is found.
David Rogerscd87c322020-02-27 14:04:08 -0800714 //
David Rogersc8fe1f52020-02-27 14:04:08 -0800715 // Tier 2 is find sectors that are empty/erased. While scanning for a partial
716 // sector, keep track of the first empty sector and if a second empty sector
717 // was seen. If during GC then count the second empty sector as always seen.
David Rogersf3884eb2020-03-08 19:21:40 -0700718 //
719 // Tier 3 is during garbage collection, find sectors with enough space that
720 // are not empty but have recoverable bytes. Pick the sector with the least
721 // recoverable bytes to minimize the likelyhood of this sector needing to be
722 // garbage collected soon.
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800723 for (size_t j = 0; j < sectors_.size(); j++) {
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800724 sector += 1;
725 if (sector == sectors_.end()) {
726 sector = sectors_.begin();
727 }
Keir Mierle8c352dc2020-02-02 13:58:19 -0800728
David Rogersf3884eb2020-03-08 19:21:40 -0700729 // Skip sectors in the skip list.
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700730 if (Contains(span(temp_sectors_to_skip_, sectors_to_skip), sector)) {
David Rogers8db5a722020-02-03 18:28:34 -0800731 continue;
732 }
733
David Rogersf3884eb2020-03-08 19:21:40 -0700734 if (!sector->Empty(sector_size_bytes) && sector->HasSpace(size)) {
735 if ((find_mode == kAppendEntry) ||
736 (sector->RecoverableBytes(sector_size_bytes) == 0)) {
737 *found_sector = sector;
738 return Status::OK;
739 } else {
740 if ((non_empty_least_reclaimable_sector == nullptr) ||
741 (non_empty_least_reclaimable_sector->RecoverableBytes(
742 sector_size_bytes) <
743 sector->RecoverableBytes(sector_size_bytes))) {
744 non_empty_least_reclaimable_sector = sector;
745 }
746 }
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800747 }
748
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800749 if (sector->Empty(sector_size_bytes)) {
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800750 if (first_empty_sector == nullptr) {
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800751 first_empty_sector = sector;
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800752 } else {
753 at_least_two_empty_sectors = true;
Wyatt Hepler2ad60672020-01-21 08:00:16 -0800754 }
Wyatt Heplerb7609542020-01-24 10:29:54 -0800755 }
756 }
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800757
David Rogersf3884eb2020-03-08 19:21:40 -0700758 // Tier 2 check: If the scan for a partial sector does not find a suitable
759 // sector, use the first empty sector that was found. Normally it is required
760 // to keep 1 empty sector after the sector found here, but that rule does not
761 // apply during GC.
762 if (first_empty_sector != nullptr && at_least_two_empty_sectors) {
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800763 DBG(" Found a usable empty sector; returning the first found (%u)",
David Rogers8ce55cd2020-02-04 19:41:48 -0800764 SectorIndex(first_empty_sector));
765 last_new_sector_ = first_empty_sector;
766 *found_sector = first_empty_sector;
767 return Status::OK;
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800768 }
David Rogers8ce55cd2020-02-04 19:41:48 -0800769
David Rogersf3884eb2020-03-08 19:21:40 -0700770 // Tier 3 check: If we got this far, use the sector with least recoverable
771 // bytes
772 if (non_empty_least_reclaimable_sector != nullptr) {
773 *found_sector = non_empty_least_reclaimable_sector;
774 DBG(" Found a usable sector %u, with %zu B recoverable, in GC",
775 SectorIndex(*found_sector),
776 (*found_sector)->RecoverableBytes(sector_size_bytes));
777 return Status::OK;
778 }
779
David Rogers8ce55cd2020-02-04 19:41:48 -0800780 // No sector was found.
David Rogers67f4b6c2020-02-06 16:17:09 -0800781 DBG(" Unable to find a usable sector");
David Rogers8ce55cd2020-02-04 19:41:48 -0800782 *found_sector = nullptr;
783 return Status::RESOURCE_EXHAUSTED;
Wyatt Heplerb7609542020-01-24 10:29:54 -0800784}
785
David Rogersf3884eb2020-03-08 19:21:40 -0700786// TODO: Break up this function in to smaller sub-chunks including create an
787// abstraction for the sector list. Look in to being able to unit test this as
788// its own thing
789KeyValueStore::SectorDescriptor* KeyValueStore::FindSectorToGarbageCollect(
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700790 span<const Address> reserved_addresses) {
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800791 const size_t sector_size_bytes = partition_.sector_size_bytes();
David Rogers2761aeb2020-01-31 17:09:00 -0800792 SectorDescriptor* sector_candidate = nullptr;
David Rogersa12786b2020-01-31 16:02:33 -0800793 size_t candidate_bytes = 0;
794
David Rogersf3884eb2020-03-08 19:21:40 -0700795 // Build a vector of sectors to avoid.
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700796 for (size_t i = 0; i < reserved_addresses.size(); ++i) {
797 temp_sectors_to_skip_[i] = SectorFromAddress(reserved_addresses[i]);
798 DBG(" Skip sector %u",
799 SectorIndex(SectorFromAddress(reserved_addresses[i])));
David Rogersf3884eb2020-03-08 19:21:40 -0700800 }
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700801 const span sectors_to_skip(temp_sectors_to_skip_, reserved_addresses.size());
David Rogersf3884eb2020-03-08 19:21:40 -0700802
David Rogersa12786b2020-01-31 16:02:33 -0800803 // Step 1: Try to find a sectors with stale keys and no valid keys (no
804 // relocation needed). If any such sectors are found, use the sector with the
805 // most reclaimable bytes.
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800806 for (auto& sector : sectors_) {
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800807 if ((sector.valid_bytes() == 0) &&
David Rogersf3884eb2020-03-08 19:21:40 -0700808 (sector.RecoverableBytes(sector_size_bytes) > candidate_bytes) &&
809 !Contains(sectors_to_skip, &sector)) {
David Rogersa12786b2020-01-31 16:02:33 -0800810 sector_candidate = &sector;
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800811 candidate_bytes = sector.RecoverableBytes(sector_size_bytes);
David Rogersa12786b2020-01-31 16:02:33 -0800812 }
813 }
814
David Rogersc9d545e2020-03-11 17:47:43 -0700815 // Step 2: If step 1 yields no sectors, just find the sector with the most
David Rogersf3884eb2020-03-08 19:21:40 -0700816 // reclaimable bytes but no addresses to avoid.
817 if (sector_candidate == nullptr) {
818 for (auto& sector : sectors_) {
819 if ((sector.RecoverableBytes(sector_size_bytes) > candidate_bytes) &&
820 !Contains(sectors_to_skip, &sector)) {
821 sector_candidate = &sector;
822 candidate_bytes = sector.RecoverableBytes(sector_size_bytes);
823 }
824 }
825 }
826
David Rogersf3884eb2020-03-08 19:21:40 -0700827 // Step 3: If no sectors with reclaimable bytes, select the sector with the
828 // most free bytes. This at least will allow entries of existing keys to get
829 // spread to other sectors, including sectors that already have copies of the
830 // current key being written.
831 if (sector_candidate == nullptr) {
832 for (auto& sector : sectors_) {
833 if ((sector.valid_bytes() > candidate_bytes) &&
834 !Contains(sectors_to_skip, &sector)) {
835 sector_candidate = &sector;
836 candidate_bytes = sector.valid_bytes();
837 DBG(" Doing GC on sector with no reclaimable bytes!");
838 }
839 }
840 }
841
David Rogers5981f312020-02-13 13:33:56 -0800842 if (sector_candidate != nullptr) {
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800843 DBG("Found sector %u to Garbage Collect, %zu recoverable bytes",
David Rogers5981f312020-02-13 13:33:56 -0800844 SectorIndex(sector_candidate),
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800845 sector_candidate->RecoverableBytes(sector_size_bytes));
David Rogers5981f312020-02-13 13:33:56 -0800846 } else {
847 DBG("Unable to find sector to garbage collect!");
848 }
David Rogersa12786b2020-01-31 16:02:33 -0800849 return sector_candidate;
850}
851
David Rogerscd87c322020-02-27 14:04:08 -0800852Status KeyValueStore::GarbageCollectFull() {
853 DBG("Garbage Collect all sectors");
David Rogerscd87c322020-02-27 14:04:08 -0800854 SectorDescriptor* sector = last_new_sector_;
855
856 // TODO: look in to making an iterator method for cycling through sectors
857 // starting from last_new_sector_.
858 for (size_t j = 0; j < sectors_.size(); j++) {
859 sector += 1;
860 if (sector == sectors_.end()) {
861 sector = sectors_.begin();
862 }
863
864 if (sector->RecoverableBytes(partition_.sector_size_bytes()) > 0) {
Wyatt Heplerab3b2492020-03-11 16:15:16 -0700865 TRY(GarbageCollectSector(sector, {}));
David Rogerscd87c322020-02-27 14:04:08 -0800866 }
867 }
868
869 DBG("Garbage Collect all complete");
David Rogerscd87c322020-02-27 14:04:08 -0800870 return Status::OK;
871}
872
David Rogersc9d545e2020-03-11 17:47:43 -0700873Status KeyValueStore::GarbageCollectPartial(
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700874 span<const Address> reserved_addresses) {
David Rogersc9d545e2020-03-11 17:47:43 -0700875 DBG("Garbage Collect a single sector");
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700876 for (Address address : reserved_addresses) {
David Rogersc9d545e2020-03-11 17:47:43 -0700877 DBG(" Avoid address %u", unsigned(address));
878 }
David Rogers67f4b6c2020-02-06 16:17:09 -0800879
David Rogersa12786b2020-01-31 16:02:33 -0800880 // Step 1: Find the sector to garbage collect
David Rogersc9d545e2020-03-11 17:47:43 -0700881 SectorDescriptor* sector_to_gc =
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700882 FindSectorToGarbageCollect(reserved_addresses);
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800883
David Rogersa12786b2020-01-31 16:02:33 -0800884 if (sector_to_gc == nullptr) {
David Rogersa2562b52020-03-05 15:30:05 -0800885 // Nothing to GC.
886 return Status::NOT_FOUND;
David Rogersa12786b2020-01-31 16:02:33 -0800887 }
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800888
David Rogersc9d545e2020-03-11 17:47:43 -0700889 // Step 2: Garbage collect the selected sector.
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700890 return GarbageCollectSector(sector_to_gc, reserved_addresses);
David Rogerscd87c322020-02-27 14:04:08 -0800891}
892
David Rogersf3884eb2020-03-08 19:21:40 -0700893Status KeyValueStore::RelocateKeyAddressesInSector(
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700894 SectorDescriptor& sector_to_gc,
895 const EntryMetadata& metadata,
896 span<const Address> reserved_addresses) {
897 for (FlashPartition::Address& address : metadata.addresses()) {
Wyatt Heplerab3b2492020-03-11 16:15:16 -0700898 if (AddressInSector(sector_to_gc, address)) {
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700899 DBG(" Relocate entry for Key 0x%08" PRIx32 ", sector %u",
900 metadata.hash(),
Wyatt Heplerab3b2492020-03-11 16:15:16 -0700901 SectorIndex(SectorFromAddress(address)));
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700902 TRY(RelocateEntry(metadata, address, reserved_addresses));
David Rogersf3884eb2020-03-08 19:21:40 -0700903 }
904 }
Wyatt Heplerab3b2492020-03-11 16:15:16 -0700905
David Rogersf3884eb2020-03-08 19:21:40 -0700906 return Status::OK;
907};
908
Wyatt Heplerab3b2492020-03-11 16:15:16 -0700909Status KeyValueStore::GarbageCollectSector(
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700910 SectorDescriptor* sector_to_gc, span<const Address> reserved_addresses) {
David Rogersf3884eb2020-03-08 19:21:40 -0700911 // Step 1: Move any valid entries in the GC sector to other sectors
Wyatt Heplerab3b2492020-03-11 16:15:16 -0700912 if (sector_to_gc->valid_bytes() != 0) {
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700913 for (const EntryMetadata& metadata : entry_cache_) {
Wyatt Heplerab3b2492020-03-11 16:15:16 -0700914 TRY(RelocateKeyAddressesInSector(
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700915 *sector_to_gc, metadata, reserved_addresses));
David Rogersf3884eb2020-03-08 19:21:40 -0700916 }
917 }
918
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800919 if (sector_to_gc->valid_bytes() != 0) {
David Rogers67f4b6c2020-02-06 16:17:09 -0800920 ERR(" Failed to relocate valid entries from sector being garbage "
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800921 "collected, %zu valid bytes remain",
922 sector_to_gc->valid_bytes());
Wyatt Heplerb7609542020-01-24 10:29:54 -0800923 return Status::INTERNAL;
924 }
925
David Rogerscd87c322020-02-27 14:04:08 -0800926 // Step 2: Reinitialize the sector
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800927 sector_to_gc->set_writable_bytes(0);
David Rogersa12786b2020-01-31 16:02:33 -0800928 TRY(partition_.Erase(SectorBaseAddress(sector_to_gc), 1));
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800929 sector_to_gc->set_writable_bytes(partition_.sector_size_bytes());
Wyatt Heplerb7609542020-01-24 10:29:54 -0800930
David Rogerscd87c322020-02-27 14:04:08 -0800931 DBG(" Garbage Collect sector %u complete", SectorIndex(sector_to_gc));
David Rogersa12786b2020-01-31 16:02:33 -0800932 return Status::OK;
Wyatt Hepler4da1fcb2020-01-30 17:32:18 -0800933}
934
Wyatt Heplerbdd8e5a2020-02-20 19:27:26 -0800935KeyValueStore::Entry KeyValueStore::CreateEntry(Address address,
Wyatt Heplerab3b2492020-03-11 16:15:16 -0700936 string_view key,
Wyatt Heplerbdd8e5a2020-02-20 19:27:26 -0800937 span<const byte> value,
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700938 EntryState state) {
Keir Mierle9e38b402020-02-21 13:06:21 -0800939 // Always bump the transaction ID when creating a new entry.
940 //
941 // Burning transaction IDs prevents inconsistencies between flash and memory
942 // that which could happen if a write succeeds, but for some reason the read
943 // and verify step fails. Here's how this would happen:
944 //
945 // 1. The entry is written but for some reason the flash reports failure OR
946 // The write succeeds, but the read / verify operation fails.
947 // 2. The transaction ID is NOT incremented, because of the failure
948 // 3. (later) A new entry is written, re-using the transaction ID (oops)
949 //
950 // By always burning transaction IDs, the above problem can't happen.
951 last_transaction_id_ += 1;
952
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700953 if (state == EntryState::kDeleted) {
Wyatt Hepler7465be32020-02-21 15:30:53 -0800954 return Entry::Tombstone(
Wyatt Hepler22d0d9f2020-03-05 14:57:11 -0800955 partition_, address, formats_.primary(), key, last_transaction_id_);
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800956 }
957 return Entry::Valid(partition_,
958 address,
Wyatt Hepler22d0d9f2020-03-05 14:57:11 -0800959 formats_.primary(),
Wyatt Hepler1fc11042020-02-19 17:17:51 -0800960 key,
961 value,
Keir Mierle9e38b402020-02-21 13:06:21 -0800962 last_transaction_id_);
Wyatt Heplerd2298282020-02-20 17:12:45 -0800963}
964
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700965void KeyValueStore::LogDebugInfo() const {
Keir Mierle8c352dc2020-02-02 13:58:19 -0800966 const size_t sector_size_bytes = partition_.sector_size_bytes();
967 DBG("====================== KEY VALUE STORE DUMP =========================");
968 DBG(" ");
969 DBG("Flash partition:");
Wyatt Heplerad0a7932020-02-06 08:20:38 -0800970 DBG(" Sector count = %zu", partition_.sector_count());
Wyatt Hepler38ce30f2020-02-19 11:48:31 -0800971 DBG(" Sector max count = %zu", sectors_.max_size());
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800972 DBG(" Sectors in use = %zu", sectors_.size());
Keir Mierle8c352dc2020-02-02 13:58:19 -0800973 DBG(" Sector size = %zu", sector_size_bytes);
974 DBG(" Total size = %zu", partition_.size_bytes());
975 DBG(" Alignment = %zu", partition_.alignment_bytes());
976 DBG(" ");
977 DBG("Key descriptors:");
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700978 DBG(" Entry count = %zu", entry_cache_.total_entries());
979 DBG(" Max entry count = %zu", entry_cache_.max_entries());
Keir Mierle8c352dc2020-02-02 13:58:19 -0800980 DBG(" ");
981 DBG(" # hash version address address (hex)");
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700982 size_t i = 0;
983 for (const EntryMetadata& metadata : entry_cache_) {
Keir Mierle8c352dc2020-02-02 13:58:19 -0800984 DBG(" |%3zu: | %8zx |%8zu | %8zu | %8zx",
Wyatt Hepler7ded6da2020-03-11 18:24:43 -0700985 i++,
986 size_t(metadata.hash()),
987 size_t(metadata.transaction_id()),
988 size_t(metadata.first_address()),
989 size_t(metadata.first_address()));
Keir Mierle8c352dc2020-02-02 13:58:19 -0800990 }
991 DBG(" ");
992
993 DBG("Sector descriptors:");
994 DBG(" # tail free valid has_space");
Wyatt Hepler1c329ca2020-02-07 18:07:23 -0800995 for (size_t sector_id = 0; sector_id < sectors_.size(); ++sector_id) {
996 const SectorDescriptor& sd = sectors_[sector_id];
Keir Mierle8c352dc2020-02-02 13:58:19 -0800997 DBG(" |%3zu: | %8zu |%8zu | %s",
998 sector_id,
Wyatt Hepler2c7eca02020-02-18 16:01:42 -0800999 size_t(sd.writable_bytes()),
1000 sd.valid_bytes(),
1001 sd.writable_bytes() ? "YES" : "");
Keir Mierle8c352dc2020-02-02 13:58:19 -08001002 }
1003 DBG(" ");
1004
1005 // TODO: This should stop logging after some threshold.
1006 // size_t dumped_bytes = 0;
1007 DBG("Sector raw data:");
Wyatt Hepler1c329ca2020-02-07 18:07:23 -08001008 for (size_t sector_id = 0; sector_id < sectors_.size(); ++sector_id) {
Keir Mierle8c352dc2020-02-02 13:58:19 -08001009 // Read sector data. Yes, this will blow the stack on embedded.
Wyatt Hepler1c329ca2020-02-07 18:07:23 -08001010 std::array<byte, 500> raw_sector_data; // TODO!!!
Keir Mierle8c352dc2020-02-02 13:58:19 -08001011 StatusWithSize sws =
1012 partition_.Read(sector_id * sector_size_bytes, raw_sector_data);
1013 DBG("Read: %zu bytes", sws.size());
1014
1015 DBG(" base addr offs 0 1 2 3 4 5 6 7");
1016 for (size_t i = 0; i < sector_size_bytes; i += 8) {
1017 DBG(" %3zu %8zx %5zu | %02x %02x %02x %02x %02x %02x %02x %02x",
1018 sector_id,
1019 (sector_id * sector_size_bytes) + i,
1020 i,
1021 static_cast<unsigned int>(raw_sector_data[i + 0]),
1022 static_cast<unsigned int>(raw_sector_data[i + 1]),
1023 static_cast<unsigned int>(raw_sector_data[i + 2]),
1024 static_cast<unsigned int>(raw_sector_data[i + 3]),
1025 static_cast<unsigned int>(raw_sector_data[i + 4]),
1026 static_cast<unsigned int>(raw_sector_data[i + 5]),
1027 static_cast<unsigned int>(raw_sector_data[i + 6]),
1028 static_cast<unsigned int>(raw_sector_data[i + 7]));
1029
1030 // TODO: Fix exit condition.
1031 if (i > 128) {
1032 break;
1033 }
1034 }
1035 DBG(" ");
1036 }
1037
1038 DBG("////////////////////// KEY VALUE STORE DUMP END /////////////////////");
1039}
1040
David Rogerscf680ab2020-02-12 23:28:32 -08001041void KeyValueStore::LogSectors() const {
1042 DBG("Sector descriptors: count %zu", sectors_.size());
Wyatt Hepler1c329ca2020-02-07 18:07:23 -08001043 for (auto& sector : sectors_) {
Wyatt Hepler2c7eca02020-02-18 16:01:42 -08001044 DBG(" - Sector %u: valid %zu, recoverable %zu, free %zu",
David Rogers50185ad2020-02-07 00:02:46 -08001045 SectorIndex(&sector),
Wyatt Hepler2c7eca02020-02-18 16:01:42 -08001046 sector.valid_bytes(),
1047 sector.RecoverableBytes(partition_.sector_size_bytes()),
1048 sector.writable_bytes());
David Rogers50185ad2020-02-07 00:02:46 -08001049 }
1050}
1051
David Rogerscf680ab2020-02-12 23:28:32 -08001052void KeyValueStore::LogKeyDescriptor() const {
Wyatt Hepler7ded6da2020-03-11 18:24:43 -07001053 DBG("Key descriptors: count %zu", entry_cache_.total_entries());
1054 for (auto& metadata : entry_cache_) {
1055 DBG(" - Key: %s, hash %#zx, transaction ID %zu, first address %#zx",
1056 metadata.deleted() ? "Deleted" : "Valid",
1057 static_cast<size_t>(metadata.hash()),
1058 static_cast<size_t>(metadata.transaction_id()),
1059 static_cast<size_t>(metadata.first_address()));
David Rogerscf680ab2020-02-12 23:28:32 -08001060 }
1061}
1062
Wyatt Hepler2ad60672020-01-21 08:00:16 -08001063} // namespace pw::kvs