Skip to main content

unkernel_rs/
disk.rs

1//! Block device abstraction (`wda` read-only distro image, `wdb` persistent writable ext4
2//! overlay disk) and native `KWSPARS1` (optional gzip) sparse disk template unpacker.
3
4use flate2::read::GzDecoder;
5use serde::{Deserialize, Serialize};
6use std::collections::HashMap;
7use std::fs::{self, File, OpenOptions};
8use std::io::{self, Read};
9use std::path::{Path, PathBuf};
10use std::sync::Mutex;
11use wasmtime::error::Context;
12use wasmtime::{Result, bail};
13
14fn file_read_exact_at(file: &File, dst: &mut [u8], off: u64) -> io::Result<()> {
15    #[cfg(unix)]
16    {
17        use std::os::unix::fs::FileExt;
18        file.read_exact_at(dst, off)
19    }
20    #[cfg(windows)]
21    {
22        use std::os::windows::fs::FileExt;
23        let mut pos = 0usize;
24        while pos < dst.len() {
25            let n = file.seek_read(&mut dst[pos..], off + pos as u64)?;
26            if n == 0 {
27                return Err(io::Error::new(
28                    io::ErrorKind::UnexpectedEof,
29                    "unexpected EOF reading block device",
30                ));
31            }
32            pos += n;
33        }
34        Ok(())
35    }
36}
37
38fn file_write_all_at(file: &File, src: &[u8], off: u64) -> io::Result<()> {
39    #[cfg(unix)]
40    {
41        use std::os::unix::fs::FileExt;
42        file.write_all_at(src, off)
43    }
44    #[cfg(windows)]
45    {
46        use std::os::windows::fs::FileExt;
47        let mut pos = 0usize;
48        while pos < src.len() {
49            let n = file.seek_write(&src[pos..], off + pos as u64)?;
50            if n == 0 {
51                return Err(io::Error::new(
52                    io::ErrorKind::WriteZero,
53                    "short write to block device",
54                ));
55            }
56            pos += n;
57        }
58        Ok(())
59    }
60}
61
62fn erofs_error() -> io::Error {
63    #[cfg(unix)]
64    {
65        io::Error::from_raw_os_error(libc::EROFS)
66    }
67    #[cfg(not(unix))]
68    {
69        io::Error::new(io::ErrorKind::ReadOnlyFilesystem, "read-only disk")
70    }
71}
72
73#[cfg(windows)]
74fn mark_sparse(file: &File) {
75    use std::os::windows::io::AsRawHandle;
76    const FSCTL_SET_SPARSE: u32 = 0x0009_00C4;
77    #[link(name = "kernel32")]
78    unsafe extern "system" {
79        fn DeviceIoControl(
80            h_device: *mut core::ffi::c_void,
81            dw_io_control_code: u32,
82            lp_in_buffer: *const core::ffi::c_void,
83            n_in_buffer_size: u32,
84            lp_out_buffer: *mut core::ffi::c_void,
85            n_out_buffer_size: u32,
86            lp_bytes_returned: *mut u32,
87            lp_overlapped: *mut core::ffi::c_void,
88        ) -> i32;
89    }
90    let mut bytes_returned: u32 = 0;
91    unsafe {
92        let _ = DeviceIoControl(
93            file.as_raw_handle(),
94            FSCTL_SET_SPARSE,
95            std::ptr::null(),
96            0,
97            std::ptr::null_mut(),
98            0,
99            &mut bytes_returned,
100            std::ptr::null_mut(),
101        );
102    }
103}
104
105pub const F_RO: u32 = 1;
106pub const F_FLUSH: u32 = 2;
107pub const F_DISCARD: u32 = 4;
108pub const F_WRITE_ZEROES: u32 = 8;
109
110const KWSPARSE_MAGIC: &[u8; 8] = b"KWSPARS1";
111const KWSPARSE_HEADER: usize = 24;
112const COW_BLOCK_SIZE: usize = 4096;
113
114/// Create a sparse ext4 disk file at `dest` from a bundled `unkernel.datadisk` (`KWSPARS1`,
115/// gzipped or raw). Written atomically via a temporary sibling file.
116pub fn create_disk_from_kwsparse(dest: &Path, raw_or_gz: &[u8]) -> Result<u64> {
117    if raw_or_gz.is_empty() {
118        bail!("bundle contains no unkernel.datadisk template");
119    }
120    let decoded;
121    let bytes: &[u8] = if raw_or_gz.len() >= 2 && raw_or_gz[0] == 0x1f && raw_or_gz[1] == 0x8b {
122        let mut gz = GzDecoder::new(raw_or_gz);
123        let mut out = Vec::new();
124        gz.read_to_end(&mut out)
125            .context("gunzip unkernel.datadisk")?;
126        decoded = out;
127        &decoded
128    } else {
129        raw_or_gz
130    };
131
132    if bytes.len() < KWSPARSE_HEADER || &bytes[0..8] != KWSPARSE_MAGIC {
133        bail!("not a KWSPARS1 disk template");
134    }
135    let size = u64::from_le_bytes(bytes[8..16].try_into().unwrap());
136    let block_size = u32::from_le_bytes(bytes[16..20].try_into().unwrap()) as usize;
137    let nblocks = u32::from_le_bytes(bytes[20..24].try_into().unwrap()) as usize;
138
139    if block_size < 512 || !block_size.is_power_of_two() {
140        bail!("kwsparse: invalid block size {block_size}");
141    }
142    let data_at = KWSPARSE_HEADER + 8 * nblocks;
143    let expected_len = data_at
144        .checked_add(nblocks * block_size)
145        .ok_or_else(|| wasmtime::format_err!("kwsparse size overflow"))?;
146    if bytes.len() != expected_len {
147        bail!(
148            "kwsparse: {} bytes != expected {} for {} blocks",
149            bytes.len(),
150            expected_len,
151            nblocks
152        );
153    }
154
155    if let Some(parent) = dest.parent()
156        && !parent.as_os_str().is_empty()
157    {
158        fs::create_dir_all(parent).with_context(|| format!("mkdir {}", parent.display()))?;
159    }
160
161    let tmp = dest.with_extension(format!("tmp-{}", std::process::id()));
162    let res = (|| -> Result<()> {
163        let f = OpenOptions::new()
164            .create_new(true)
165            .read(true)
166            .write(true)
167            .open(&tmp)
168            .with_context(|| format!("create {}", tmp.display()))?;
169        #[cfg(windows)]
170        mark_sparse(&f);
171        f.set_len(size)?;
172        let mut prev: i64 = -1;
173        for i in 0..nblocks {
174            let idx = u64::from_le_bytes(
175                bytes[KWSPARSE_HEADER + 8 * i..KWSPARSE_HEADER + 8 * (i + 1)]
176                    .try_into()
177                    .unwrap(),
178            );
179            let off = idx
180                .checked_mul(block_size as u64)
181                .ok_or_else(|| wasmtime::format_err!("kwsparse offset overflow"))?;
182            if (idx as i64) <= prev || off + (block_size as u64) > size {
183                bail!("kwsparse: invalid or unsorted block index {idx}");
184            }
185            prev = idx as i64;
186            let blk = &bytes[data_at + i * block_size..data_at + (i + 1) * block_size];
187            file_write_all_at(&f, blk, off)?;
188        }
189        f.sync_all()?;
190        Ok(())
191    })();
192
193    if let Err(e) = res {
194        let _ = fs::remove_file(&tmp);
195        return Err(e);
196    }
197    #[cfg(windows)]
198    if dest.exists() {
199        let _ = fs::remove_file(dest);
200    }
201    fs::rename(&tmp, dest)
202        .with_context(|| format!("rename {} -> {}", tmp.display(), dest.display()))?;
203    Ok(size)
204}
205
206#[derive(Serialize, Deserialize)]
207struct PortableDiskSnapshot {
208    base_path: PathBuf,
209    size: u64,
210    dirty_blocks: Vec<(u64, Vec<u8>)>,
211}
212
213/// Cloneable in-memory snapshot of a block device's 4 KiB COW overlay anchored to `base_path`.
214/// Allows branching multiple independent VMs from an exact ext4 rootfs state in < 1 ms.
215#[derive(Clone)]
216pub struct DiskSnapshot {
217    pub base_path: PathBuf,
218    pub size: u64,
219    dirty_blocks: HashMap<u64, Box<[u8; COW_BLOCK_SIZE]>>,
220}
221
222impl Serialize for DiskSnapshot {
223    fn serialize<S: serde::Serializer>(
224        &self,
225        serializer: S,
226    ) -> std::result::Result<S::Ok, S::Error> {
227        let mut dirty: Vec<(u64, Vec<u8>)> = self
228            .dirty_blocks
229            .iter()
230            .map(|(&idx, blk)| (idx, blk.as_slice().to_vec()))
231            .collect();
232        dirty.sort_by_key(|(idx, _)| *idx);
233        PortableDiskSnapshot {
234            base_path: self.base_path.clone(),
235            size: self.size,
236            dirty_blocks: dirty,
237        }
238        .serialize(serializer)
239    }
240}
241
242impl<'de> Deserialize<'de> for DiskSnapshot {
243    fn deserialize<D: serde::Deserializer<'de>>(
244        deserializer: D,
245    ) -> std::result::Result<Self, D::Error> {
246        let p = PortableDiskSnapshot::deserialize(deserializer)?;
247        let mut dirty_blocks = HashMap::with_capacity(p.dirty_blocks.len());
248        for (idx, bytes) in p.dirty_blocks {
249            if bytes.len() != COW_BLOCK_SIZE {
250                return Err(serde::de::Error::custom(format!(
251                    "invalid COW block size {} (expected {COW_BLOCK_SIZE})",
252                    bytes.len()
253                )));
254            }
255            let mut arr = Box::new([0u8; COW_BLOCK_SIZE]);
256            arr.copy_from_slice(&bytes);
257            dirty_blocks.insert(idx, arr);
258        }
259        Ok(Self {
260            base_path: p.base_path,
261            size: p.size,
262            dirty_blocks,
263        })
264    }
265}
266
267impl std::fmt::Debug for DiskSnapshot {
268    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
269        f.debug_struct("DiskSnapshot")
270            .field("base_path", &self.base_path)
271            .field("size", &self.size)
272            .field("dirty_blocks", &self.dirty_blocks.len())
273            .finish()
274    }
275}
276
277impl DiskSnapshot {
278    pub fn dirty_block_count(&self) -> usize {
279        self.dirty_blocks.len()
280    }
281
282    pub fn dirty_bytes(&self) -> usize {
283        self.dirty_blocks.len() * COW_BLOCK_SIZE
284    }
285}
286
287/// Host block device backing `/dev/wda`, `/dev/wdb`, etc.
288pub struct BlockDevice {
289    base_path: PathBuf,
290    file: File,
291    pub size: u64,
292    pub read_only: bool,
293    /// When `Some`, writes go to an in-memory 4 KiB copy-on-write overlay and never mutate `file`.
294    cow: Option<Mutex<HashMap<u64, Box<[u8; COW_BLOCK_SIZE]>>>>,
295}
296
297impl BlockDevice {
298    pub fn open_readonly(path: &Path) -> Result<Self> {
299        let file = File::open(path).with_context(|| format!("open disk {}", path.display()))?;
300        let size = file.metadata()?.len();
301        Ok(Self {
302            base_path: path.to_path_buf(),
303            file,
304            size,
305            read_only: true,
306            cow: None,
307        })
308    }
309
310    /// Open a persistent data disk (read-write, read-only, or in-memory snapshot COW).
311    pub fn open_data_disk(path: &Path, read_only: bool, snapshot_cow: bool) -> Result<Self> {
312        if read_only || snapshot_cow {
313            let file = File::open(path).with_context(|| format!("open disk {}", path.display()))?;
314            let size = file.metadata()?.len();
315            Ok(Self {
316                base_path: path.to_path_buf(),
317                file,
318                size,
319                read_only: read_only && !snapshot_cow,
320                cow: if snapshot_cow {
321                    Some(Mutex::new(HashMap::new()))
322                } else {
323                    None
324                },
325            })
326        } else {
327            let file = OpenOptions::new()
328                .read(true)
329                .write(true)
330                .open(path)
331                .with_context(|| format!("open writable disk {}", path.display()))?;
332            let size = file.metadata()?.len();
333            Ok(Self {
334                base_path: path.to_path_buf(),
335                file,
336                size,
337                read_only: false,
338                cow: None,
339            })
340        }
341    }
342
343    /// Open a writable COW [`BlockDevice`] seeded from an existing [`DiskSnapshot`].
344    /// Never mutates `snap.base_path`; further writes stay isolated to this branch.
345    pub fn from_snapshot(snap: &DiskSnapshot) -> Result<Self> {
346        let file = File::open(&snap.base_path)
347            .with_context(|| format!("open snapshot base disk {}", snap.base_path.display()))?;
348        Ok(Self {
349            base_path: snap.base_path.clone(),
350            file,
351            size: snap.size,
352            read_only: false,
353            cow: Some(Mutex::new(snap.dirty_blocks.clone())),
354        })
355    }
356
357    /// Capture a cloneable [`DiskSnapshot`] of this device's current state (< 1 ms for COW disks).
358    pub fn snapshot(&self) -> Result<DiskSnapshot> {
359        let dirty_blocks = match &self.cow {
360            Some(cow_mu) => cow_mu.lock().unwrap().clone(),
361            None => {
362                if !self.read_only {
363                    self.file.sync_data()?;
364                }
365                HashMap::new()
366            }
367        };
368        Ok(DiskSnapshot {
369            base_path: self.base_path.clone(),
370            size: self.size,
371            dirty_blocks,
372        })
373    }
374
375    pub fn flags(&self) -> u32 {
376        if self.read_only {
377            F_RO
378        } else {
379            F_FLUSH | F_DISCARD | F_WRITE_ZEROES
380        }
381    }
382
383    pub fn read_at(&self, mut off: u64, mut dst: &mut [u8]) -> std::io::Result<()> {
384        if let Some(cow_mu) = &self.cow {
385            let cow = cow_mu.lock().unwrap();
386            while !dst.is_empty() {
387                let blk_idx = off / COW_BLOCK_SIZE as u64;
388                let in_blk = (off % COW_BLOCK_SIZE as u64) as usize;
389                let take = (COW_BLOCK_SIZE - in_blk).min(dst.len());
390                if let Some(blk) = cow.get(&blk_idx) {
391                    dst[..take].copy_from_slice(&blk[in_blk..in_blk + take]);
392                } else {
393                    file_read_exact_at(&self.file, &mut dst[..take], off)?;
394                }
395                off += take as u64;
396                dst = &mut dst[take..];
397            }
398            Ok(())
399        } else {
400            file_read_exact_at(&self.file, dst, off)
401        }
402    }
403
404    pub fn write_at(&self, mut off: u64, mut src: &[u8]) -> std::io::Result<()> {
405        if self.read_only {
406            return Err(erofs_error());
407        }
408        if let Some(cow_mu) = &self.cow {
409            let mut cow = cow_mu.lock().unwrap();
410            while !src.is_empty() {
411                let blk_idx = off / COW_BLOCK_SIZE as u64;
412                let in_blk = (off % COW_BLOCK_SIZE as u64) as usize;
413                let take = (COW_BLOCK_SIZE - in_blk).min(src.len());
414                let entry = match cow.entry(blk_idx) {
415                    std::collections::hash_map::Entry::Occupied(e) => e.into_mut(),
416                    std::collections::hash_map::Entry::Vacant(v) => {
417                        let mut buf = Box::new([0u8; COW_BLOCK_SIZE]);
418                        let blk_off = blk_idx * COW_BLOCK_SIZE as u64;
419                        let valid_len =
420                            ((self.size.saturating_sub(blk_off)) as usize).min(COW_BLOCK_SIZE);
421                        if valid_len > 0 {
422                            file_read_exact_at(&self.file, &mut buf[..valid_len], blk_off)?;
423                        }
424                        v.insert(buf)
425                    }
426                };
427                entry[in_blk..in_blk + take].copy_from_slice(&src[..take]);
428                off += take as u64;
429                src = &src[take..];
430            }
431            Ok(())
432        } else {
433            file_write_all_at(&self.file, src, off)
434        }
435    }
436
437    pub fn flush(&self) -> std::io::Result<()> {
438        if self.read_only || self.cow.is_some() {
439            return Ok(());
440        }
441        self.file.sync_data()
442    }
443
444    pub fn write_zeroes(&self, mut off: u64, mut len: u64) -> std::io::Result<()> {
445        if self.read_only {
446            return Err(erofs_error());
447        }
448        let zeros = [0u8; 65536];
449        while len > 0 {
450            let n = (len as usize).min(zeros.len());
451            self.write_at(off, &zeros[..n])?;
452            off += n as u64;
453            len -= n as u64;
454        }
455        Ok(())
456    }
457
458    pub fn discard(&self, off: u64, len: u64) -> std::io::Result<()> {
459        if self.read_only {
460            return Err(erofs_error());
461        }
462        if self.cow.is_some() {
463            return self.write_zeroes(off, len);
464        }
465        #[cfg(target_os = "linux")]
466        {
467            use std::os::unix::io::AsRawFd;
468            let rc = unsafe {
469                libc::fallocate(
470                    self.file.as_raw_fd(),
471                    libc::FALLOC_FL_PUNCH_HOLE | libc::FALLOC_FL_KEEP_SIZE,
472                    off as libc::off_t,
473                    len as libc::off_t,
474                )
475            };
476            if rc == 0 {
477                return Ok(());
478            }
479        }
480        self.write_zeroes(off, len)
481    }
482}