1 // 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
15 #define PW_LOG_MODULE_NAME "KVS"
16 #define PW_LOG_LEVEL PW_KVS_LOG_LEVEL
17
18 #include "pw_kvs/internal/sectors.h"
19
20 #include "pw_kvs_private/config.h"
21 #include "pw_log/shorter.h"
22
23 namespace pw::kvs::internal {
24 namespace {
25
26 // Returns true if the container conatins the value.
27 // TODO: At some point move this to pw_containers, along with adding tests.
28 template <typename Container, typename T>
Contains(const Container & container,const T & value)29 bool Contains(const Container& container, const T& value) {
30 return std::find(std::begin(container), std::end(container), value) !=
31 std::end(container);
32 }
33
34 } // namespace
35
Find(FindMode find_mode,SectorDescriptor ** found_sector,size_t size,std::span<const Address> addresses_to_skip,std::span<const Address> reserved_addresses)36 Status Sectors::Find(FindMode find_mode,
37 SectorDescriptor** found_sector,
38 size_t size,
39 std::span<const Address> addresses_to_skip,
40 std::span<const Address> reserved_addresses) {
41 SectorDescriptor* first_empty_sector = nullptr;
42 bool at_least_two_empty_sectors = (find_mode == kGarbageCollect);
43
44 // Used for the GC reclaimable bytes check
45 SectorDescriptor* non_empty_least_reclaimable_sector = nullptr;
46 const size_t sector_size_bytes = partition_.sector_size_bytes();
47
48 // Build a list of sectors to avoid.
49 //
50 // This is overly strict. reserved_addresses is populated when there are
51 // sectors reserved for a new entry. It is safe to garbage collect into
52 // these sectors, as long as there remains room for the pending entry. These
53 // reserved sectors could also be garbage collected if they have recoverable
54 // space. For simplicitly, avoid both the relocating key's redundant entries
55 // (addresses_to_skip) and the sectors reserved for pending writes
56 // (reserved_addresses).
57 // TODO(hepler): Look into improving garbage collection.
58 size_t sectors_to_skip = 0;
59 for (Address address : addresses_to_skip) {
60 temp_sectors_to_skip_[sectors_to_skip++] = &FromAddress(address);
61 }
62 for (Address address : reserved_addresses) {
63 temp_sectors_to_skip_[sectors_to_skip++] = &FromAddress(address);
64 }
65
66 DBG("Find sector with %u bytes available, starting with sector %u, %s",
67 unsigned(size),
68 Index(last_new_),
69 (find_mode == kAppendEntry) ? "Append" : "GC");
70 for (size_t i = 0; i < sectors_to_skip; ++i) {
71 DBG(" Skip sector %u", Index(temp_sectors_to_skip_[i]));
72 }
73
74 // last_new_ is the sector that was last selected as the "new empty sector" to
75 // write to. This last new sector is used as the starting point for the next
76 // "find a new empty sector to write to" operation. By using the last new
77 // sector as the start point we will cycle which empty sector is selected
78 // next, spreading the wear across all the empty sectors and get a wear
79 // leveling benefit, rather than putting more wear on the lower number
80 // sectors.
81 SectorDescriptor* sector = last_new_;
82
83 // Look for a sector to use with enough space. The search uses a 3 priority
84 // tier process.
85 //
86 // Tier 1 is sector that already has valid data. During GC only select a
87 // sector that has no reclaimable bytes. Immediately use the first matching
88 // sector that is found.
89 //
90 // Tier 2 is find sectors that are empty/erased. While scanning for a partial
91 // sector, keep track of the first empty sector and if a second empty sector
92 // was seen. If during GC then count the second empty sector as always seen.
93 //
94 // Tier 3 is during garbage collection, find sectors with enough space that
95 // are not empty but have recoverable bytes. Pick the sector with the least
96 // recoverable bytes to minimize the likelyhood of this sector needing to be
97 // garbage collected soon.
98 for (size_t j = 0; j < descriptors_.size(); j++) {
99 sector += 1;
100 if (sector == descriptors_.end()) {
101 sector = descriptors_.begin();
102 }
103
104 // Skip sectors in the skip list.
105 if (Contains(std::span(temp_sectors_to_skip_, sectors_to_skip), sector)) {
106 continue;
107 }
108
109 if (!sector->Empty(sector_size_bytes) && sector->HasSpace(size)) {
110 if ((find_mode == kAppendEntry) ||
111 (sector->RecoverableBytes(sector_size_bytes) == 0)) {
112 *found_sector = sector;
113 return OkStatus();
114 } else {
115 if ((non_empty_least_reclaimable_sector == nullptr) ||
116 (non_empty_least_reclaimable_sector->RecoverableBytes(
117 sector_size_bytes) <
118 sector->RecoverableBytes(sector_size_bytes))) {
119 non_empty_least_reclaimable_sector = sector;
120 }
121 }
122 }
123
124 if (sector->Empty(sector_size_bytes)) {
125 if (first_empty_sector == nullptr) {
126 first_empty_sector = sector;
127 } else {
128 at_least_two_empty_sectors = true;
129 }
130 }
131 }
132
133 // Tier 2 check: If the scan for a partial sector does not find a suitable
134 // sector, use the first empty sector that was found. Normally it is required
135 // to keep 1 empty sector after the sector found here, but that rule does not
136 // apply during GC.
137 if (first_empty_sector != nullptr && at_least_two_empty_sectors) {
138 DBG(" Found a usable empty sector; returning the first found (%u)",
139 Index(first_empty_sector));
140 last_new_ = first_empty_sector;
141 *found_sector = first_empty_sector;
142 return OkStatus();
143 }
144
145 // Tier 3 check: If we got this far, use the sector with least recoverable
146 // bytes
147 if (non_empty_least_reclaimable_sector != nullptr) {
148 *found_sector = non_empty_least_reclaimable_sector;
149 DBG(" Found a usable sector %u, with %u B recoverable, in GC",
150 Index(*found_sector),
151 unsigned((*found_sector)->RecoverableBytes(sector_size_bytes)));
152 return OkStatus();
153 }
154
155 // No sector was found.
156 DBG(" Unable to find a usable sector");
157 *found_sector = nullptr;
158 return Status::ResourceExhausted();
159 }
160
WearLeveledSectorFromIndex(size_t idx) const161 SectorDescriptor& Sectors::WearLeveledSectorFromIndex(size_t idx) const {
162 return descriptors_[(Index(last_new_) + 1 + idx) % descriptors_.size()];
163 }
164
165 // TODO: Consider breaking this function into smaller sub-chunks.
FindSectorToGarbageCollect(std::span<const Address> reserved_addresses) const166 SectorDescriptor* Sectors::FindSectorToGarbageCollect(
167 std::span<const Address> reserved_addresses) const {
168 const size_t sector_size_bytes = partition_.sector_size_bytes();
169 SectorDescriptor* sector_candidate = nullptr;
170 size_t candidate_bytes = 0;
171
172 // Build a vector of sectors to avoid.
173 for (size_t i = 0; i < reserved_addresses.size(); ++i) {
174 temp_sectors_to_skip_[i] = &FromAddress(reserved_addresses[i]);
175 DBG(" Skip sector %u", Index(reserved_addresses[i]));
176 }
177 const std::span sectors_to_skip(temp_sectors_to_skip_,
178 reserved_addresses.size());
179
180 // Step 1: Try to find a sectors with stale keys and no valid keys (no
181 // relocation needed). Use the first such sector found, as that will help the
182 // KVS "rotate" around the partition. Initially this would select the sector
183 // with the most reclaimable space, but that can cause GC sector selection to
184 // "ping-pong" between two sectors when updating large keys.
185 for (size_t i = 0; i < descriptors_.size(); ++i) {
186 SectorDescriptor& sector = WearLeveledSectorFromIndex(i);
187 if ((sector.valid_bytes() == 0) &&
188 (sector.RecoverableBytes(sector_size_bytes) > 0) &&
189 !Contains(sectors_to_skip, §or)) {
190 sector_candidate = §or;
191 break;
192 }
193 }
194
195 // Step 2: If step 1 yields no sectors, just find the sector with the most
196 // reclaimable bytes but no addresses to avoid.
197 if (sector_candidate == nullptr) {
198 for (size_t i = 0; i < descriptors_.size(); ++i) {
199 SectorDescriptor& sector = WearLeveledSectorFromIndex(i);
200 if ((sector.RecoverableBytes(sector_size_bytes) > candidate_bytes) &&
201 !Contains(sectors_to_skip, §or)) {
202 sector_candidate = §or;
203 candidate_bytes = sector.RecoverableBytes(sector_size_bytes);
204 }
205 }
206 }
207
208 // Step 3: If no sectors with reclaimable bytes, select the sector with the
209 // most free bytes. This at least will allow entries of existing keys to get
210 // spread to other sectors, including sectors that already have copies of the
211 // current key being written.
212 if (sector_candidate == nullptr) {
213 for (size_t i = 0; i < descriptors_.size(); ++i) {
214 SectorDescriptor& sector = WearLeveledSectorFromIndex(i);
215 if ((sector.valid_bytes() > candidate_bytes) &&
216 !Contains(sectors_to_skip, §or)) {
217 sector_candidate = §or;
218 candidate_bytes = sector.valid_bytes();
219 DBG(" Doing GC on sector with no reclaimable bytes!");
220 }
221 }
222 }
223
224 if (sector_candidate != nullptr) {
225 DBG("Found sector %u to Garbage Collect, %u recoverable bytes",
226 Index(sector_candidate),
227 unsigned(sector_candidate->RecoverableBytes(sector_size_bytes)));
228 } else {
229 DBG("Unable to find sector to garbage collect!");
230 }
231 return sector_candidate;
232 }
233
234 } // namespace pw::kvs::internal
235