From f6fb5f6e46841bc0d335612a8bcc294adeb12eb2 Mon Sep 17 00:00:00 2001 From: Pierre LE GUEN <26087574+PierreLeGuen@users.noreply.github.com> Date: Sun, 22 Nov 2026 20:32:54 +0000 Subject: [PATCH 1/2] fix(volume): share extents when packing a volume Building a volume copied the filesystem image twice: into a scratch file, then into the GPT image through a 1 MiB userspace buffer. For a large image that doubles the disk space and the time. Clone instead with FICLONE / FICLONERANGE: the partitions are 1 MiB aligned and the data and hash images are padded to whole blocks, so XFS and Btrfs share the extents. Fall back to a copy where cloning is not supported. copy_file_range is not used because it does not reliably clone (it did not on Linux 7.0 with XFS). Tested: packing a 1.1 TB squashfs on XFS no longer needs a second 1.1 TB, and the scratch copy completes immediately. Signed-off-by: Pierre LE GUEN <26087574+PierreLeGuen@users.noreply.github.com> --- dstack/Cargo.lock | 1 + dstack/crates/dstack-volume/Cargo.toml | 1 + dstack/crates/dstack-volume/src/volume.rs | 65 +++++++++++++++++++---- 3 files changed, 58 insertions(+), 9 deletions(-) diff --git a/dstack/Cargo.lock b/dstack/Cargo.lock index 6b4dae1d2c..dc16ec288a 100644 --- a/dstack/Cargo.lock +++ b/dstack/Cargo.lock @@ -2647,6 +2647,7 @@ dependencies = [ "fs-err", "gpt", "hex", + "libc", "serde_json", "sha2 0.10.9", "tempfile", diff --git a/dstack/crates/dstack-volume/Cargo.toml b/dstack/crates/dstack-volume/Cargo.toml index 76262b6feb..aff295957c 100644 --- a/dstack/crates/dstack-volume/Cargo.toml +++ b/dstack/crates/dstack-volume/Cargo.toml @@ -20,6 +20,7 @@ sha2 = { workspace = true, features = ["std"] } hex = { workspace = true, features = ["std"] } fs-err.workspace = true gpt = "4.1.0" +libc.workspace = true tempfile.workspace = true tracing.workspace = true tracing-subscriber.workspace = true diff --git a/dstack/crates/dstack-volume/src/volume.rs b/dstack/crates/dstack-volume/src/volume.rs index ba9ee6ac18..d2c1d5b9d8 100644 --- a/dstack/crates/dstack-volume/src/volume.rs +++ b/dstack/crates/dstack-volume/src/volume.rs @@ -114,7 +114,7 @@ pub fn build_fs_image(fs_image: &Path, output: &Path, salt_hex: &str) -> Result< let tmp = tempfile::tempdir().context("creating volume scratch dir")?; let data_path = tmp.path().join("data.fs"); - fs::copy(fs_image, &data_path) + clone_or_copy_file(fs_image, &data_path) .with_context(|| format!("copying {} into scratch", fs_image.display()))?; seal_data_image(&data_path, len, output, salt_hex) } @@ -368,21 +368,68 @@ fn write_volume_header(out: &mut fs::File, offset: u64, root_hash: &str) -> Resu Ok(()) } +/// Place `src` in `out` at `offset`. On a filesystem with reflinks (XFS, +/// Btrfs) the extents are shared instead of written again (the partitions are +/// 1 MiB aligned and the inputs are padded to whole blocks), so packing a +/// large directory needs no second copy of it on disk. Elsewhere it copies. fn copy_into(src: &Path, out: &mut fs::File, offset: u64) -> Result<()> { - use std::io::{Read, Seek, SeekFrom, Write}; + use std::io::{Seek, SeekFrom}; let mut input = fs::File::open(src)?; + if clone_range(input.file(), out.file(), offset).is_ok() { + return Ok(()); + } out.seek(SeekFrom::Start(offset))?; - let mut buf = vec![0u8; 1 << 20]; - loop { - let n = input.read(&mut buf)?; - if n == 0 { - break; - } - out.write_all(&buf[..n])?; + std::io::copy(&mut input, out)?; + Ok(()) +} + +/// Copy `src` to a new file `dst`, sharing extents where the filesystem can. +fn clone_or_copy_file(src: &Path, dst: &Path) -> Result<()> { + let input = fs::File::open(src)?; + let output = fs::File::create(dst)?; + if clone_range(input.file(), output.file(), 0).is_ok() { + return Ok(()); } + drop(output); + fs::copy(src, dst)?; Ok(()) } +/// `FICLONERANGE` of all of `src` (`src_length` 0: to its end) into `dst` at +/// `dest_offset`. `copy_file_range` does not reliably reflink (not on Linux +/// 7.0 with XFS), so this asks for the clone explicitly. +#[cfg(target_os = "linux")] +fn clone_range(src: &std::fs::File, dst: &std::fs::File, dest_offset: u64) -> std::io::Result<()> { + use std::os::fd::AsRawFd; + #[repr(C)] + struct FileCloneRange { + src_fd: i64, + src_offset: u64, + src_length: u64, + dest_offset: u64, + } + // _IOW(0x94, 13, struct file_clone_range) + const FICLONERANGE: libc::c_ulong = 0x4020_940d; + let arg = FileCloneRange { + src_fd: src.as_raw_fd() as i64, + src_offset: 0, + src_length: 0, + dest_offset, + }; + // SAFETY: FICLONERANGE reads a file_clone_range, which `arg` is laid out as. + let ret = unsafe { libc::ioctl(dst.as_raw_fd(), FICLONERANGE as _, &arg) }; + if ret == 0 { + Ok(()) + } else { + Err(std::io::Error::last_os_error()) + } +} + +#[cfg(not(target_os = "linux"))] +fn clone_range(_: &std::fs::File, _: &std::fs::File, _: u64) -> std::io::Result<()> { + Err(std::io::ErrorKind::Unsupported.into()) +} + fn require_tool(name: &str) -> Result<()> { let present = run_cmd!(which $name >/dev/null 2>&1).is_ok(); if !present { From dabb958331566c0961e615d7b1c9cadf3e853ce0 Mon Sep 17 00:00:00 2001 From: Pierre LE GUEN <26087574+PierreLeGuen@users.noreply.github.com> Date: Thu, 3 Dec 2026 16:17:56 +0000 Subject: [PATCH 2/2] fix(volume): place scratch dirs next to output and keep copy_file_range fast path - Put volume and verity hash scratch directories in output's parent dir via tempfile::tempdir_in so FICLONERANGE stays on the same filesystem and avoids exhausting /tmp. - Pass underlying std::fs::File handles (&mut input.file(), &mut out.file()) to std::io::copy on the fallback path to preserve std's copy_file_range specialization. - Use libc::file_clone_range and libc::FICLONERANGE instead of a local struct and hardcoded ioctl constant. Signed-off-by: Pierre LE GUEN <26087574+PierreLeGuen@users.noreply.github.com> --- dstack/crates/dstack-volume/src/volume.rs | 56 ++++++++++++++++------- 1 file changed, 39 insertions(+), 17 deletions(-) diff --git a/dstack/crates/dstack-volume/src/volume.rs b/dstack/crates/dstack-volume/src/volume.rs index d2c1d5b9d8..2e43708aae 100644 --- a/dstack/crates/dstack-volume/src/volume.rs +++ b/dstack/crates/dstack-volume/src/volume.rs @@ -82,7 +82,7 @@ pub fn build_volume( require_tool("mksquashfs")?; require_tool("veritysetup")?; - let tmp = tempfile::tempdir().context("creating volume scratch dir")?; + let tmp = scratch_dir_for(output).context("creating volume scratch dir")?; let data_path = tmp.path().join("data.fs"); // 1. reproducible squashfs. @@ -112,7 +112,7 @@ pub fn build_fs_image(fs_image: &Path, output: &Path, salt_hex: &str) -> Result< bail!("filesystem image '{}' is empty", fs_image.display()); } - let tmp = tempfile::tempdir().context("creating volume scratch dir")?; + let tmp = scratch_dir_for(output).context("creating volume scratch dir")?; let data_path = tmp.path().join("data.fs"); clone_or_copy_file(fs_image, &data_path) .with_context(|| format!("copying {} into scratch", fs_image.display()))?; @@ -125,7 +125,7 @@ fn seal_data_image( output: &Path, salt_hex: &str, ) -> Result { - let hash_tmp = tempfile::tempdir().context("creating verity hash scratch dir")?; + let hash_tmp = scratch_dir_for(output).context("creating verity hash scratch dir")?; let hash_path = hash_tmp.path().join("verity.hash"); let data_size = data_len.div_ceil(BLOCK) * BLOCK; { @@ -368,18 +368,35 @@ fn write_volume_header(out: &mut fs::File, offset: u64, root_hash: &str) -> Resu Ok(()) } +/// Create a scratch directory next to `output` so temporary blobs live on the +/// same filesystem as the final image (required for `FICLONERANGE` and avoids +/// filling a small `/tmp`). +fn scratch_dir_for(output: &Path) -> std::io::Result { + tempfile::tempdir_in(scratch_parent(output)) +} + +fn scratch_parent(output: &Path) -> &Path { + output + .parent() + .filter(|p| !p.as_os_str().is_empty()) + .unwrap_or_else(|| Path::new(".")) +} + /// Place `src` in `out` at `offset`. On a filesystem with reflinks (XFS, /// Btrfs) the extents are shared instead of written again (the partitions are /// 1 MiB aligned and the inputs are padded to whole blocks), so packing a /// large directory needs no second copy of it on disk. Elsewhere it copies. fn copy_into(src: &Path, out: &mut fs::File, offset: u64) -> Result<()> { use std::io::{Seek, SeekFrom}; - let mut input = fs::File::open(src)?; + let input = fs::File::open(src)?; if clone_range(input.file(), out.file(), offset).is_ok() { return Ok(()); } out.seek(SeekFrom::Start(offset))?; - std::io::copy(&mut input, out)?; + // Copy via the underlying `std::fs::File` handles so `std::io::copy` keeps + // its `copy_file_range` specialization instead of an 8 KiB userspace loop. + std::io::copy(&mut input.file(), &mut out.file()) + .with_context(|| format!("copying {} into output", src.display()))?; Ok(()) } @@ -401,23 +418,14 @@ fn clone_or_copy_file(src: &Path, dst: &Path) -> Result<()> { #[cfg(target_os = "linux")] fn clone_range(src: &std::fs::File, dst: &std::fs::File, dest_offset: u64) -> std::io::Result<()> { use std::os::fd::AsRawFd; - #[repr(C)] - struct FileCloneRange { - src_fd: i64, - src_offset: u64, - src_length: u64, - dest_offset: u64, - } - // _IOW(0x94, 13, struct file_clone_range) - const FICLONERANGE: libc::c_ulong = 0x4020_940d; - let arg = FileCloneRange { + let arg = libc::file_clone_range { src_fd: src.as_raw_fd() as i64, src_offset: 0, src_length: 0, dest_offset, }; - // SAFETY: FICLONERANGE reads a file_clone_range, which `arg` is laid out as. - let ret = unsafe { libc::ioctl(dst.as_raw_fd(), FICLONERANGE as _, &arg) }; + // SAFETY: `FICLONERANGE` reads a `libc::file_clone_range` pointer. + let ret = unsafe { libc::ioctl(dst.as_raw_fd(), libc::FICLONERANGE, &arg) }; if ret == 0 { Ok(()) } else { @@ -534,4 +542,18 @@ mod tests { Ok(()) } + + #[test] + fn scratch_dir_is_created_next_to_output() -> Result<()> { + assert_eq!(scratch_parent(Path::new("volume.img")), Path::new(".")); + assert_eq!( + scratch_parent(Path::new("/data/volumes/volume.img")), + Path::new("/data/volumes") + ); + let dir = tempfile::tempdir()?; + let output = dir.path().join("volume.img"); + let scratch = scratch_dir_for(&output)?; + assert_eq!(scratch.path().parent(), Some(dir.path())); + Ok(()) + } }