1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
//! Garbage collection: reclaims a sector by moving its live pages, then erasing it. It also
//! levels the wear of sectors whose data never changes (static wear leveling).
use alloc::vec::Vec;
use core::cmp::Reverse;
use embedded_storage::nor_flash::NorFlash;
use super::layout::{MARKER_OFFSET, PageHeader};
use super::space::Purpose;
use super::{NorBackend, NorError, WEAR_GAP};
use crate::ObjectId;
impl<F: NorFlash> NorBackend<F> {
/// Reclaims the sector with the most garbage, the least worn one on a tie. Returns `false` if
/// no sector can be reclaimed.
pub(super) fn collect(&mut self) -> Result<bool, NorError<F::Error>> {
let Some(victim) = (0..self.sectors.len())
.filter(|&s| self.sectors[s].formatted && self.garbage(s) > 0)
.max_by_key(|&s| (self.garbage(s), Reverse(self.sectors[s].erase_count)))
else {
return Ok(false);
};
let active_free = if self.active == Some(victim) {
0
} else {
self.active_free_pages()
};
if self.sectors[victim].live > active_free + self.free_sectors() * Self::DATA_PAGES {
return Ok(false);
}
if self.active == Some(victim) {
self.active = None;
}
self.reclaim(victim)?;
Ok(true)
}
/// Static wear leveling. A sector whose data never changes has no garbage, so the garbage
/// collection never picks it: it stops wearing, and the other sectors take every erase. When
/// the least worn sector holding data is `WEAR_GAP` erases behind the most worn sector, its
/// data moves to the most worn free sector, where it can stay, and it is erased: as the least
/// worn free sector, it is the next one opened. Moves at most one sector.
///
/// Free space doesn't change: the data takes one free sector and frees another. Only sectors
/// with a header count: one without may have worn out, its header failing to write.
///
/// The move is optional: if it runs out of pages, or they keep reading back wrong, it stops
/// without an error. The pages moved so far stay where they went, and the sector left half
/// moved, with garbage now, is collected later.
pub(super) fn level_wear(&mut self) -> Result<(), NorError<F::Error>> {
let most_worn = (self.sectors.iter())
.filter(|s| s.formatted)
.map(|s| s.erase_count)
.max();
let Some(cold) = (0..self.sectors.len())
.filter(|&s| self.sectors[s].live > 0 && self.active != Some(s))
.min_by_key(|&s| self.sectors[s].erase_count)
else {
return Ok(());
};
let Some(target) = (0..self.sectors.len())
.filter(|&s| self.is_free(s) && self.sectors[s].formatted)
.max_by_key(|&s| self.sectors[s].erase_count)
else {
return Ok(());
};
let cold_count = self.sectors[cold].erase_count;
if most_worn.is_none_or(|most| most - cold_count < WEAR_GAP)
|| self.sectors[target].erase_count <= cold_count
{
return Ok(());
}
// The pages are allocated from the active sector: the target is, during the move.
let previous = self.active;
if !self.activate(target)? {
return Ok(());
}
let moved = self.reclaim(cold);
// Back to the previous active sector, if it has room. The sector the data went to is then
// closed, as pages are only allocated from the active sector.
if let (Some(previous), Some(current)) = (previous, self.active)
&& previous != current
&& self.sectors[previous].next_page < Self::PAGES_PER_SECTOR
{
if self.sectors[current].next_page > 1 {
self.sectors[current].next_page = Self::PAGES_PER_SECTOR;
}
self.active = Some(previous);
}
match moved {
// The first copies of the moved pages, in `unmarked`, are marked before any erase.
Err(NorError::NoSpace | NorError::VerifyFailed) => self.mark_unmarked(),
moved => moved,
}
}
/// Moves the live pages of `sector` to the active sector, then erases it.
fn reclaim(&mut self, sector: usize) -> Result<(), NorError<F::Error>> {
let mut moved = Vec::new();
let result = self.relocate(sector, &mut moved).and_then(|()| {
// Retire the sector before erasing it, so a cut erase is detected at mount.
self.program_marker(self.sector_addr(sector) + MARKER_OFFSET as u32)
});
if let Err(error) = result {
// Not retired, the sector still counts at mount: the first copies of the moved pages
// would bring their version back once the new copies are marked, by a removal.
self.unmarked.extend(moved);
return Err(error);
}
// Reclaimed even if its header reads back wrong: it is then erased again before use.
self.erase_sector(sector)?;
Ok(())
}
/// Moves the live pages of `sector` to the active sector, adding the pages moved to `moved`.
fn relocate(&mut self, sector: usize, moved: &mut Vec<u16>) -> Result<(), NorError<F::Error>> {
for index in 1..self.sectors[sector].next_page {
let page = sector * Self::PAGES_PER_SECTOR + index;
let bytes = self.read_page(page)?;
let Some(header) = PageHeader::decode(&bytes) else {
continue;
};
let id = ObjectId(header.object_id);
let slot = usize::from(header.index);
// RAM decides, not the marker: a removal whose mark was written although the flash
// reported an error still has its object, until it is retried.
let live = self.objects.get(&id).is_some_and(|object| {
object.version == header.version && object.pages.get(slot) == Some(&(page as u16))
});
if !live {
continue;
}
// Same bytes, header and commit included, in one program: until the sector is
// erased, mount sees two copies and keeps one, the committed one for a last page.
// The old copy no longer counts as live, so the RAM state stays right if a later
// relocation fails.
let new = self.write_page(&bytes[..MARKER_OFFSET], false, Purpose::Collect)?;
if let Some(object) = self.objects.get_mut(&id) {
object.pages[slot] = new as u16;
}
self.sectors[Self::sector_of(new)].live += 1;
self.sectors[sector].live -= 1;
moved.push(page as u16);
}
Ok(())
}
}