Skip to main content

link_cli/storage/
mapped_flush.rs

1//! Lifetime-checked barrier for an owned, offset-zero file mapping.
2use std::fs::File;
3use std::io;
4use std::sync::{Arc, Mutex};
5
6#[derive(Clone, Copy, Debug)]
7struct View {
8    address: usize,
9    bytes: usize,
10}
11
12#[derive(Debug)]
13enum Mapping {
14    Unmapped,
15    Ready(View),
16    Invalidated,
17    Closed,
18}
19
20#[derive(Debug)]
21struct State {
22    file: Option<File>,
23    mapping: Mapping,
24}
25
26/// A flush barrier belonging to one [`PersistentFileMapped`](super::PersistentFileMapped).
27///
28/// Clones follow successful remaps. Flushing an invalidated or dropped owner
29/// fails without touching its old address. On Windows the view is flushed
30/// before its owned file handle; on Unix the shared mapping uses the file's
31/// synchronous writeback. Callers must serialize logical writes themselves.
32#[derive(Clone, Debug)]
33pub struct MappedFlush(Arc<Mutex<State>>);
34
35impl MappedFlush {
36    pub(super) fn new(file: File) -> Self {
37        Self(Arc::new(Mutex::new(State {
38            file: Some(file),
39            mapping: Mapping::Unmapped,
40        })))
41    }
42
43    /// Synchronizes this owner's mapped writes, propagating view/file errors.
44    ///
45    /// This does not repair torn pages or make a transaction atomic. Storage
46    /// and devices must honor their platform's synchronization contract.
47    pub fn flush(&self) -> io::Result<()> {
48        self.flush_with(&SystemIo)
49    }
50
51    pub(super) fn clone_file(&self) -> io::Result<File> {
52        let state = self
53            .0
54            .lock()
55            .map_err(|_| io::Error::other("mapped flush ownership is poisoned"))?;
56        state
57            .file
58            .as_ref()
59            .ok_or_else(|| {
60                io::Error::new(io::ErrorKind::BrokenPipe, "mapped flush file is closed")
61            })?
62            .try_clone()
63    }
64
65    fn flush_with(&self, io: &impl FlushIo) -> io::Result<()> {
66        let state = self
67            .0
68            .lock()
69            .map_err(|_| io::Error::other("mapped flush ownership is poisoned"))?;
70        flush(&state, io)
71    }
72
73    // Clear under the same lock used by flush before the owner can unmap.
74    // Recovery from poisoning is only for lifetime bookkeeping, never success
75    // reporting. flush() continues to fail on a poisoned mutex.
76    pub(super) fn invalidate(&self) {
77        let mut state = self.0.lock().unwrap_or_else(|error| error.into_inner());
78        state.mapping = Mapping::Invalidated;
79    }
80
81    pub(super) fn publish<T>(&self, items: &[T]) {
82        let mut state = self.0.lock().unwrap_or_else(|error| error.into_inner());
83        state.mapping = if items.is_empty() {
84            Mapping::Unmapped
85        } else {
86            Mapping::Ready(View {
87                address: items.as_ptr() as usize,
88                bytes: std::mem::size_of_val(items),
89            })
90        };
91    }
92
93    pub(super) fn close(&self) {
94        let mut state = self.0.lock().unwrap_or_else(|error| error.into_inner());
95        // Drop cannot report I/O errors. Explicit flush is the checked barrier.
96        if !self.0.is_poisoned() {
97            let _ = flush(&state, &SystemIo);
98        }
99        state.mapping = Mapping::Closed;
100        // Retained logical handles must not retain an open file after close.
101        state.file.take();
102    }
103}
104
105trait FlushIo {
106    fn view(&self, view: View) -> io::Result<()>;
107    fn file(&self, file: &File) -> io::Result<()>;
108}
109
110fn flush(state: &State, io: &impl FlushIo) -> io::Result<()> {
111    match state.mapping {
112        Mapping::Ready(view) => io.view(view)?,
113        Mapping::Unmapped => {}
114        Mapping::Invalidated => {
115            return Err(io::Error::other(
116                "mapped flush owner has an unfinished remap",
117            ));
118        }
119        Mapping::Closed => {
120            return Err(io::Error::new(
121                io::ErrorKind::BrokenPipe,
122                "mapped flush owner is closed",
123            ));
124        }
125    }
126    let file = state
127        .file
128        .as_ref()
129        .ok_or_else(|| io::Error::new(io::ErrorKind::BrokenPipe, "mapped flush file is closed"))?;
130    io.file(file)
131}
132
133struct SystemIo;
134
135impl FlushIo for SystemIo {
136    fn view(&self, view: View) -> io::Result<()> {
137        #[cfg(windows)]
138        {
139            // SAFETY: the owner publishes only its actual offset-zero mapping.
140            // Its state lock remains held until both barriers finish; resize
141            // and Drop invalidate the descriptor under that lock before unmap.
142            if unsafe {
143                windows_sys::Win32::System::Memory::FlushViewOfFile(
144                    view.address as *const _,
145                    view.bytes,
146                )
147            } == 0
148            {
149                return Err(io::Error::last_os_error());
150            }
151        }
152        #[cfg(not(windows))]
153        let _ = (view.address, view.bytes);
154        Ok(())
155    }
156
157    fn file(&self, file: &File) -> io::Result<()> {
158        file.sync_all()
159    }
160}
161
162#[cfg(test)]
163#[path = "mapped_flush_tests.rs"]
164mod tests;