1#![deny(
8 clippy::unwrap_used,
9 clippy::too_many_lines,
10 clippy::cast_possible_truncation
11)]
12
13mod staging;
14pub(crate) use staging::StagedPageBatch;
15
16use super::page::{Page, PageError, PageType, PAGE_SIZE};
17use reddb_file::{VfsFile, PAGED_SUPERBLOCK_SLOT_SIZE, PAGED_SUPERBLOCK_ZONE_SIZE};
18use std::io::{self, SeekFrom};
19
20mod dwb_publication;
21
22pub(crate) fn requires_dwb_publication<F: VfsFile>(file: &mut F) -> Result<bool, PagerIoError> {
23 dwb_publication::enabled(file)
24}
25
26pub const DWB_ZONE_START_PAGE: u32 = 3;
27pub const DWB_ZONE_PAGES: u32 = 64;
28pub const DWB_ZONE_BYTES: usize = DWB_ZONE_PAGES as usize * PAGE_SIZE;
29pub const FIRST_ALLOCATABLE_PAGE: u32 = DWB_ZONE_START_PAGE + DWB_ZONE_PAGES;
30pub const DWB_MAX_PAGES_PER_FRAME: usize =
31 (DWB_ZONE_BYTES - reddb_file::PAGED_DWB_HEADER_SIZE) / reddb_file::PAGED_DWB_ENTRY_SIZE;
32
33#[derive(Debug)]
34pub enum PagerIoError {
35 Io(io::Error),
36 Page(PageError),
37 InvalidDatabase(String),
38}
39
40impl std::fmt::Display for PagerIoError {
41 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
42 match self {
43 Self::Io(error) => write!(f, "I/O error: {error}"),
44 Self::Page(error) => write!(f, "Page error: {error}"),
45 Self::InvalidDatabase(message) => write!(f, "Invalid database: {message}"),
46 }
47 }
48}
49
50impl std::error::Error for PagerIoError {
51 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
52 match self {
53 Self::Io(error) => Some(error),
54 Self::Page(error) => Some(error),
55 Self::InvalidDatabase(_) => None,
56 }
57 }
58}
59
60impl From<io::Error> for PagerIoError {
61 fn from(error: io::Error) -> Self {
62 Self::Io(error)
63 }
64}
65
66impl From<PageError> for PagerIoError {
67 fn from(error: PageError) -> Self {
68 Self::Page(error)
69 }
70}
71
72pub fn read_page<F: VfsFile>(
73 file: &mut F,
74 page_id: u32,
75 verify_checksum: bool,
76) -> Result<Page, PagerIoError> {
77 file.seek(SeekFrom::Start(u64::from(page_id) * PAGE_SIZE as u64))?;
78 let mut buffer = [0u8; PAGE_SIZE];
79 file.read_exact(&mut buffer)?;
80 let page = Page::from_bytes(buffer);
81 if verify_checksum && page_id != 0 {
83 page.verify_checksum()?;
84 check_page_identity(&page, page_id)?;
85 }
86 Ok(page)
87}
88
89pub fn check_page_identity(page: &Page, expected: u32) -> Result<(), PagerIoError> {
91 if expected != 0 && page.page_id() != expected {
92 return Err(PagerIoError::InvalidDatabase(format!(
93 "page identity mismatch: requested {expected}, found {}",
94 page.page_id()
95 )));
96 }
97 Ok(())
98}
99
100pub fn write_page<F: VfsFile>(file: &mut F, page_id: u32, page: &Page) -> Result<(), PagerIoError> {
102 file.seek(SeekFrom::Start(u64::from(page_id) * PAGE_SIZE as u64))?;
103 file.write_all(page.as_bytes())?;
104 Ok(())
105}
106
107pub fn read_superblock_zone<F: VfsFile>(
108 file: &mut F,
109) -> Result<[u8; PAGED_SUPERBLOCK_ZONE_SIZE], PagerIoError> {
110 let len = file.file_len()?;
111 let mut zone = [0u8; PAGED_SUPERBLOCK_ZONE_SIZE];
112 let readable = usize::try_from(len.min(PAGED_SUPERBLOCK_ZONE_SIZE as u64))
113 .expect("readable prefix is bounded by the superblock zone");
114 if readable > 0 {
115 file.seek(SeekFrom::Start(0))?;
116 file.read_exact(&mut zone[..readable])?;
117 }
118 Ok(zone)
119}
120
121pub fn write_superblock_slot<F: VfsFile>(
123 file: &mut F,
124 slot: &mut [u8; PAGED_SUPERBLOCK_SLOT_SIZE],
125 copy_index: usize,
126 generation: u64,
127) -> Result<(), PagerIoError> {
128 reddb_file::seal_paged_superblock_slot(slot, copy_index, generation)
129 .map_err(|error| PagerIoError::InvalidDatabase(error.to_string()))?;
130 file.seek(SeekFrom::Start(reddb_file::paged_superblock_slot_offset(
131 copy_index,
132 )))?;
133 file.write_all(slot)?;
134 file.sync_all()?;
135 Ok(())
136}
137
138pub fn dwb_zone_offset() -> u64 {
139 u64::from(DWB_ZONE_START_PAGE) * PAGE_SIZE as u64
140}
141
142pub fn clear_dwb_zone<F: VfsFile>(file: &mut F) -> Result<(), PagerIoError> {
144 clear_dwb_prefix(file, DWB_ZONE_PAGES)
145}
146
147fn clear_dwb_prefix<F: VfsFile>(file: &mut F, pages: u32) -> Result<(), PagerIoError> {
148 assert!(pages <= DWB_ZONE_PAGES, "DWB prefix fits its reserved zone");
149 for page_id in DWB_ZONE_START_PAGE..DWB_ZONE_START_PAGE + pages {
150 let mut page = Page::new(PageType::Header, page_id);
151 page.update_checksum();
152 write_page(file, page_id, &page)?;
153 }
154 file.sync_all()?;
155 Ok(())
156}
157
158pub fn dwb_zone_is_clear(buffer: &[u8]) -> bool {
159 if buffer.len() != DWB_ZONE_BYTES {
160 return false;
161 }
162 for (index, chunk) in buffer.chunks_exact(PAGE_SIZE).enumerate() {
163 let Ok(page) = Page::from_slice(chunk) else {
164 return false;
165 };
166 if page.verify_checksum().is_err()
167 || page.page_id()
168 != DWB_ZONE_START_PAGE
169 + u32::try_from(index).expect("DWB page index is bounded by its zone")
170 || page.page_type().ok() != Some(PageType::Header)
171 {
172 return false;
173 }
174 }
175 true
176}
177
178pub fn write_pages<F: VfsFile>(
183 file: &mut F,
184 pages: &[(u32, Page)],
185 double_write: bool,
186) -> Result<(), PagerIoError> {
187 if !double_write {
188 for (page_id, page) in pages {
189 write_page(file, *page_id, page)?;
190 }
191 return Ok(());
192 }
193
194 let protected = dwb_publication::enabled(file)?;
195 for chunk in pages.chunks(DWB_MAX_PAGES_PER_FRAME.max(1)) {
196 let buffer = reddb_file::encode_paged_dwb_frame(
197 chunk
198 .iter()
199 .map(|(page_id, page)| (*page_id, page.as_bytes())),
200 );
201 assert!(buffer.len() <= DWB_ZONE_BYTES, "DWB frame fits its zone");
202 let mut publication = protected.then(|| dwb_publication::publication(&buffer));
203 if protected {
204 let mut seen = std::collections::HashSet::new();
205 if chunk.iter().any(|(id, _)| {
206 *id == 0
207 || (DWB_ZONE_START_PAGE..FIRST_ALLOCATABLE_PAGE).contains(id)
208 || !seen.insert(*id)
209 }) {
210 return Err(PagerIoError::InvalidDatabase(
211 "invalid DWB publication ownership".into(),
212 ));
213 }
214 }
215 if let Some(publication) = publication {
216 dwb_publication::publish(file, publication)?;
217 }
218 file.seek(SeekFrom::Start(dwb_zone_offset()))?;
219 file.write_all(&buffer)?;
220 file.sync_all()?;
221 if let Some(publication) = publication.as_mut() {
222 publication.phase = reddb_file::file_format::DwbPhase::Ready;
223 dwb_publication::publish(file, *publication)?;
224 }
225 for (page_id, page) in chunk {
226 write_page(file, *page_id, page)?;
227 }
228 file.sync_all()?;
229 if let Some(publication) = publication {
230 let dirty_pages = publication
233 .frame_bytes
234 .div_ceil(u32::try_from(PAGE_SIZE).expect("page size fits u32"));
235 dwb_publication::consume(file, publication, dirty_pages)?;
236 }
237 }
238 if !protected && !pages.is_empty() {
244 clear_dwb_zone(file)?;
245 }
246 Ok(())
247}
248
249fn has_complete_dwb_zone<F: VfsFile>(file: &mut F) -> Result<bool, PagerIoError> {
250 if file.file_len()? >= dwb_zone_offset() + DWB_ZONE_BYTES as u64 {
251 return Ok(true);
252 }
253 if dwb_publication::enabled(file)? {
256 return Err(PagerIoError::InvalidDatabase(
257 "DWB generation authority: reserved zone is truncated".into(),
258 ));
259 }
260 Ok(false)
261}
262
263pub fn recover_from_dwb<F: VfsFile>(file: &mut F) -> Result<(), PagerIoError> {
267 if !has_complete_dwb_zone(file)? {
268 return Ok(());
269 }
270 if !dwb_publication::enabled(file)? {
271 return staging::recover(file);
272 }
273 let buffer = read_guarded_dwb_zone(file)?;
274 let plan = dwb_publication::plan(file, &buffer)?.ok_or_else(|| {
275 PagerIoError::InvalidDatabase("DWB generation authority disappeared during recovery".into())
276 })?;
277 let authority = match plan {
278 dwb_publication::Recovery::Unchanged => return Ok(()),
279 dwb_publication::Recovery::Discard(authority) => authority,
280 dwb_publication::Recovery::Apply(authority) => {
281 let mut ready = authority;
285 ready.phase = reddb_file::file_format::DwbPhase::Ready;
286 dwb_publication::publish(file, ready)?;
287 let entries = reddb_file::decode_paged_dwb_frame(&buffer)
288 .map_err(|error| PagerIoError::InvalidDatabase(error.to_string()))?;
289 for entry in entries {
290 write_page(file, entry.page_id, &Page::from_bytes(entry.page))?;
291 }
292 file.sync_all()?;
293 authority
294 }
295 };
296 dwb_publication::consume(file, authority, DWB_ZONE_PAGES)
297}
298
299pub fn read_dwb_pages<F: VfsFile>(file: &mut F) -> Result<Vec<(u32, Page)>, PagerIoError> {
303 if !has_complete_dwb_zone(file)? {
304 return Ok(Vec::new());
305 }
306 if !dwb_publication::enabled(file)? {
307 return staging::read_pages(file);
308 }
309 let buffer = read_guarded_dwb_zone(file)?;
310 let plan = dwb_publication::plan(file, &buffer)?.ok_or_else(|| {
311 PagerIoError::InvalidDatabase("DWB generation authority disappeared during recovery".into())
312 })?;
313 if !matches!(plan, dwb_publication::Recovery::Apply(_)) {
314 return Ok(Vec::new());
315 }
316 Ok(reddb_file::decode_paged_dwb_frame(&buffer)
317 .map_err(|error| PagerIoError::InvalidDatabase(error.to_string()))?
318 .into_iter()
319 .map(|entry| (entry.page_id, Page::from_bytes(entry.page)))
320 .collect())
321}
322
323fn read_guarded_dwb_zone<F: VfsFile>(file: &mut F) -> Result<Vec<u8>, PagerIoError> {
324 if DWB_ZONE_BYTES > file.max_read_buffer_bytes() {
325 return Err(PagerIoError::InvalidDatabase(
326 "guarded double-write recovery exceeds the owned read budget".into(),
327 ));
328 }
329 let mut buffer = vec![0u8; DWB_ZONE_BYTES];
330 file.seek(SeekFrom::Start(dwb_zone_offset()))?;
331 file.read_exact(&mut buffer)?;
332 Ok(buffer)
333}