Skip to main content

common/
copy_data.rs

1//! Low-level data-copy primitive used by the copy path.
2//!
3//! This replaces `std::fs::copy` so the copy path can keep the destination fd
4//! open across the data copy and the subsequent metadata operations (closing
5//! the TOCTOU window between writing bytes and setting times/owner/mode).
6//!
7//! With [`ReflinkMode::Auto`], the copy uses a three-tier fallback chain, fastest first:
8//! 1. the in-kernel `copy_file_range` syscall, which is reflink- and
9//!    server-side-copy capable (e.g. on Btrfs/XFS/NFSv4.2);
10//! 2. when the kernel or filesystem cannot satisfy that, a sparse-aware
11//!    userspace copy that walks the source with `SEEK_DATA`/`SEEK_HOLE` and
12//!    preserves holes;
13//! 3. when the filesystem does not even support `SEEK_DATA`/`SEEK_HOLE` (some
14//!    FUSE/older/unusual filesystems return `EINVAL`/`ENOTSUP` for those
15//!    `lseek` whences), a plain dense read/write copy loop, which always works
16//!    on any regular file (this mirrors what `std::fs::copy` would have done
17//!    and exists purely for robustness — it does not preserve holes).
18//!
19//! [`ReflinkMode::Never`] starts at tier 2, bypassing `copy_file_range` and all
20//! of its acceleration. It still preserves holes when the filesystem supports
21//! `SEEK_DATA`/`SEEK_HOLE`.
22//!
23//! # Snapshot-size semantics
24//!
25//! Callers pass `len`, the size captured when the source was classified. Both
26//! the primary and fallback paths copy *up to* `len` and agree on the result:
27//! - a source that *grew* after classification is intentionally **not**
28//!   over-copied — we copy at most `len` bytes and `dst` ends at `len`;
29//! - a source that *shrank* below `len` (e.g. a concurrent truncate — holding
30//!   the fd does not prevent it) copies and returns only what the source
31//!   provides and sizes `dst` to that actual end, **not** to `len` (no
32//!   spurious trailing padding);
33//! - a *legitimate* sparse trailing hole (the source's logical size still
34//!   equals `len`) keeps `dst` sized to `len`. Whether the trailing region is
35//!   left *unallocated* depends on the path: the sparse-aware fallback (tier 2)
36//!   preserves the hole, and the primary `copy_file_range` (tier 1) does so only
37//!   on reflink/sparse-capable filesystems (e.g. Btrfs/XFS) — on others (e.g.
38//!   ext4) the size is still `len` but the region may be fully allocated.
39//!
40//! These size bounds describe successful copies, not a consistent content snapshot
41//! of a source that is modified during the copy. Errors do not roll back writes.
42//!
43//! # Durability
44//!
45//! These are synchronous syscalls, so once they return the writes are in the
46//! kernel. This function deliberately does **not** `fsync`/`flush` — durability
47//! is out of scope here. mtime correctness is the caller's responsibility (it
48//! sets times after this returns).
49use std::fs::File;
50use std::os::fd::AsFd;
51use std::os::unix::fs::FileExt;
52
53/// Maximum userspace copy buffer size (1 MiB), bounded further by each extent.
54const FALLBACK_BUF_SIZE: usize = 1024 * 1024;
55
56/// Whether local file copies may use reflink-capable acceleration.
57///
58/// A clone-required `always` mode is intentionally deferred until there is a
59/// concrete need for its additional guarantees and failure semantics.
60#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, clap::ValueEnum)]
61pub enum ReflinkMode {
62    /// Allow filesystem acceleration, falling back to read/write copying.
63    #[default]
64    Auto,
65    /// Use sparse-aware read/write copying without reflink-capable acceleration.
66    Never,
67}
68
69/// Copy up to `len` bytes between held file descriptors with the chosen policy.
70///
71/// Copies from byte zero in the source to byte zero in the destination, regardless
72/// of their current seek positions, and returns the logical number of bytes copied.
73/// File cursor positions after copying are unspecified. Errors may leave a partially
74/// written destination; writes are not rolled back.
75/// The destination must be empty and exclusively owned by this copy operation.
76/// `Never` bypasses all `copy_file_range` acceleration, including non-reflink
77/// kernel and server-side copying. See the module docs for size and durability semantics.
78pub fn copy_file_data(
79    src: &File,
80    dst: &File,
81    len: u64,
82    reflink: ReflinkMode,
83) -> std::io::Result<u64> {
84    match reflink {
85        ReflinkMode::Auto => copy_file_range_all(src, dst, len),
86        ReflinkMode::Never => copy_sparse_fallback(src, dst, 0, len),
87    }
88}
89
90/// Copy up to `len` bytes from `src` to `dst` using the in-kernel
91/// `copy_file_range` (reflink/server-side capable), falling back to a
92/// sparse-aware userspace copy when the kernel/filesystem can't. Both files are
93/// already open; copies start at byte `0` of each via explicit offsets, ignoring
94/// the descriptors' cursors. Returns the number of bytes copied.
95/// The destination must be empty and exclusively owned by this copy operation.
96///
97/// See the module docs for snapshot-size and durability semantics.
98fn copy_file_range_all(src: &File, dst: &File, len: u64) -> std::io::Result<u64> {
99    copy_file_range_all_with(src, dst, len, |src_offset, dst_offset, remaining| {
100        #[cfg(test)]
101        crate::testutils::record_copy_file_range_call();
102        nix::fcntl::copy_file_range(
103            src.as_fd(),
104            Some(src_offset),
105            dst.as_fd(),
106            Some(dst_offset),
107            remaining,
108        )
109    })
110}
111
112/// Run positioned kernel-copy attempts from the confirmed prefix. The syscall
113/// must report no confirmed progress on error. Counts above the requested length
114/// are rejected with `EIO`; rejecting a count does not undo any kernel writes.
115/// Mutated offset arguments are discarded; only an accepted byte count advances
116/// the prefix used to initialize both offsets on the next attempt.
117fn copy_file_range_all_with(
118    src: &File,
119    dst: &File,
120    len: u64,
121    mut copy_range: impl FnMut(&mut i64, &mut i64, usize) -> nix::Result<usize>,
122) -> std::io::Result<u64> {
123    let mut copied: u64 = 0;
124    while copied < len {
125        let remaining = usize::try_from(len - copied).unwrap_or(usize::MAX);
126        // explicit offsets make copying independent of the descriptors' cursors.
127        // derive both from confirmed progress, including after an interrupted call.
128        let mut src_offset = i64::try_from(copied).map_err(|_| nix::errno::Errno::EOVERFLOW)?;
129        let mut dst_offset = src_offset;
130        match copy_range(&mut src_offset, &mut dst_offset, remaining) {
131            Ok(0)
132            | Err(
133                nix::errno::Errno::ENOSYS
134                | nix::errno::Errno::EXDEV
135                | nix::errno::Errno::EINVAL
136                | nix::errno::Errno::EOPNOTSUPP,
137            ) => {
138                // eof or unsupported kernel copying: finish through the userspace path.
139                // it returns the reconciled total size, which can be below `copied`
140                // if the source shrank beneath the prefix already written.
141                return copy_sparse_fallback(src, dst, copied, len);
142            }
143            Err(nix::errno::Errno::EPERM) if copied == 0 => {
144                // syscall permission may be denied while positioned I/O is allowed.
145                return copy_sparse_fallback(src, dst, 0, len);
146            }
147            Ok(n) if n > remaining => return Err(nix::errno::Errno::EIO.into()),
148            Ok(n) => copied += n as u64,
149            Err(nix::errno::Errno::EINTR) => continue,
150            Err(errno) => return Err(std::io::Error::from(errno)),
151        }
152    }
153    Ok(copied)
154}
155
156/// Classification of a `SEEK_DATA` probe, used to decide whether the
157/// sparse fallback can run or must degrade to a dense read/write copy.
158#[derive(Debug, Clone, Copy, PartialEq, Eq)]
159enum SparseProbe {
160    /// `SEEK_DATA` found a data region starting at this offset.
161    Data(u64),
162    /// `SEEK_DATA` returned `ENXIO`: no data at or after the probe offset, i.e.
163    /// the rest of the file up to its logical end is a hole.
164    TrailingHole,
165    /// The filesystem does not support `SEEK_DATA`/`SEEK_HOLE` (`EINVAL` or
166    /// `ENOTSUP`/`EOPNOTSUPP`): the caller must fall back to a dense copy.
167    Unsupported,
168}
169
170/// Classify the result of an `lseek(.., SEEK_DATA)` probe (the testable seam for
171/// the sparse-vs-dense routing decision).
172///
173/// - `Ok(off)` -> [`SparseProbe::Data`] at `off`;
174/// - `ENXIO` -> [`SparseProbe::TrailingHole`] (a legitimate trailing hole, not
175///   an error: the file simply has no more data);
176/// - `EINVAL` / `EOPNOTSUPP` (== `ENOTSUP` on Linux) -> [`SparseProbe::Unsupported`],
177///   meaning the filesystem rejects the `SEEK_DATA`/`SEEK_HOLE` whences and the
178///   sparse walk can't run on it;
179/// - any other errno (e.g. `EIO`, `EBADF`) is a genuine failure and is
180///   propagated — we deliberately do **not** mask real I/O errors as
181///   "unsupported".
182fn classify_seek_data(result: nix::Result<libc::off_t>) -> std::io::Result<SparseProbe> {
183    match result {
184        Ok(off) => Ok(SparseProbe::Data(off as u64)),
185        Err(nix::errno::Errno::ENXIO) => Ok(SparseProbe::TrailingHole),
186        // note: ENOTSUP == EOPNOTSUPP numerically on Linux, so this arm also
187        // covers ENOTSUP.
188        Err(nix::errno::Errno::EINVAL | nix::errno::Errno::EOPNOTSUPP) => {
189            Ok(SparseProbe::Unsupported)
190        }
191        Err(errno) => Err(std::io::Error::from(errno)),
192    }
193}
194
195/// Sparse-aware userspace copy of the range `[start, len)` from `src` to `dst`,
196/// with a dense read/write copy as a final fallback.
197///
198/// Used for `Never` and as the fallback when `copy_file_range` is unsupported. It first probes
199/// the source with `SEEK_DATA`; if the filesystem supports it, it walks the
200/// source's data regions with `SEEK_DATA`/`SEEK_HOLE` and copies only the data
201/// extents, so holes (e.g. in a sparse VM or Lustre image) are preserved
202/// instead of being expanded to fully-allocated zeros. If the filesystem does
203/// not support those whences (some FUSE/older/unusual filesystems return
204/// `EINVAL`/`ENOTSUP`), it degrades to a plain read/write loop
205/// that always works on a regular file (this matches what `std::fs::copy` would
206/// have done — see the module docs). A genuine I/O error during the probe (e.g.
207/// `EIO`) is propagated rather than masked as "unsupported".
208///
209/// The final size is reconciled with the source's *actual* end so this path
210/// agrees with the primary one on a shrunk source: after the data loop it
211/// bounds the final size by `len`, `SEEK_END`, and any earlier EOF observed by a
212/// read, then sizes `dst` to that end if needed. An observed read EOF also bounds
213/// virtual files whose advertised size exceeds their readable data.
214/// A legitimate trailing hole (source logical size still == `len`) leaves
215/// `actual_eof == len`, so `dst` ends at `len` with the trailing region
216/// unallocated; a source that shrank below `len` (`actual_eof < len`) sizes
217/// `dst` to `actual_eof` rather than padding a spurious hole up to `len`.
218///
219/// Returns the reconciled total logical size, including the already-copied prefix.
220/// The result can be below `start` if the source shrank beneath that prefix.
221/// The destination must contain only the already-copied prefix `[0, start)`
222/// and remain exclusively owned by this copy operation. `start` must not exceed `len`.
223fn copy_sparse_fallback(src: &File, dst: &File, start: u64, len: u64) -> std::io::Result<u64> {
224    copy_sparse_fallback_with_seek(src, dst, start, len, |offset, whence| {
225        nix::unistd::lseek(src.as_fd(), offset, whence)
226    })
227}
228
229fn copy_sparse_fallback_with_seek(
230    src: &File,
231    dst: &File,
232    start: u64,
233    len: u64,
234    mut seek: impl FnMut(libc::off_t, nix::unistd::Whence) -> nix::Result<libc::off_t>,
235) -> std::io::Result<u64> {
236    debug_assert!(start <= len);
237    if start == len {
238        // the destination already contains the prefix; an empty source needs no work.
239        return Ok(len);
240    }
241    let mut off = start;
242    let mut written_end = start;
243    let mut read_eof = None;
244    let mut buf = Vec::new();
245    while off < len {
246        let extent = match next_copy_extent(&mut seek, off, len)? {
247            CopyExtent::Sparse(extent) => extent,
248            CopyExtent::Dense => off..len,
249            CopyExtent::End => break,
250        };
251        // allocate only for data, cap small extents, and reuse the buffer across the walk.
252        let capacity = (extent.end - extent.start).min(FALLBACK_BUF_SIZE as u64) as usize;
253        if buf.len() < capacity {
254            buf.resize(capacity, 0);
255        }
256        let end = copy_data_extent(src, dst, extent.start, extent.end, &mut buf[..capacity])?;
257        if end > extent.start {
258            written_end = end;
259        }
260        if end < extent.end {
261            // virtual files can advertise extents and a SEEK_END beyond readable data.
262            read_eof = Some(end);
263            break;
264        }
265        off = extent.end;
266    }
267    // keep the post-loop EOF observation: a source can shrink even after the last write.
268    let actual_eof = seek(0, nix::unistd::Whence::SeekEnd).map_err(std::io::Error::from)? as u64;
269    let final_size = len.min(actual_eof).min(read_eof.unwrap_or(len));
270    if written_end != final_size {
271        // extend trailing holes or remove bytes beyond a concurrently shortened source.
272        nix::unistd::ftruncate(dst.as_fd(), to_off_t(final_size)?).map_err(std::io::Error::from)?;
273    }
274    // the same finalizer accounts for the entire walk, including any dense remainder.
275    Ok(final_size)
276}
277
278enum CopyExtent {
279    Sparse(std::ops::Range<u64>),
280    Dense,
281    End,
282}
283
284/// Find the next extent, degrading to a dense remainder if sparse probes cannot advance.
285fn next_copy_extent(
286    seek: &mut impl FnMut(libc::off_t, nix::unistd::Whence) -> nix::Result<libc::off_t>,
287    off: u64,
288    len: u64,
289) -> std::io::Result<CopyExtent> {
290    let data = match classify_seek_data(seek(to_off_t(off)?, nix::unistd::Whence::SeekData))? {
291        SparseProbe::Data(data) => data,
292        SparseProbe::TrailingHole => return Ok(CopyExtent::End),
293        SparseProbe::Unsupported => return Ok(CopyExtent::Dense),
294    };
295    if data < off {
296        return Ok(CopyExtent::Dense);
297    }
298    if data >= len {
299        return Ok(CopyExtent::End);
300    }
301    let hole = match seek(to_off_t(data)?, nix::unistd::Whence::SeekHole) {
302        Ok(hole) => (hole as u64).min(len),
303        Err(nix::errno::Errno::ENXIO) => len,
304        Err(nix::errno::Errno::EINVAL | nix::errno::Errno::EOPNOTSUPP) => {
305            return Ok(CopyExtent::Dense);
306        }
307        Err(errno) => return Err(std::io::Error::from(errno)),
308    };
309    if hole <= data {
310        // concurrent hole punching can invalidate the preceding SEEK_DATA result.
311        // copying the remainder densely also bounds progress on anomalous filesystems.
312        return Ok(CopyExtent::Dense);
313    }
314    Ok(CopyExtent::Sparse(data..hole))
315}
316
317/// Copy an extent with positioned I/O, retrying interruptions and handling short transfers.
318/// Returns the offset reached, which can be below `to` if a read reaches EOF.
319fn copy_data_extent(
320    src: &impl FileExt,
321    dst: &impl FileExt,
322    from: u64,
323    to: u64,
324    buf: &mut [u8],
325) -> std::io::Result<u64> {
326    let mut pos = from;
327    while pos < to {
328        let want = (to - pos).min(buf.len() as u64) as usize;
329        let n = match src.read_at(&mut buf[..want], pos) {
330            Ok(0) => break,
331            Ok(n) => n,
332            Err(err) if err.kind() == std::io::ErrorKind::Interrupted => continue,
333            Err(err) => return Err(err),
334        };
335        let mut written = 0;
336        while written < n {
337            match dst.write_at(&buf[written..n], pos + written as u64) {
338                Ok(0) => return Err(std::io::ErrorKind::WriteZero.into()),
339                Ok(w) => written += w,
340                Err(err) if err.kind() == std::io::ErrorKind::Interrupted => continue,
341                Err(err) => return Err(err),
342            }
343        }
344        pos += n as u64;
345    }
346    Ok(pos)
347}
348
349/// Convert a `u64` byte offset/length to the libc `off_t` expected by nix's
350/// lseek/ftruncate, mapping overflow to an io error rather than panicking.
351fn to_off_t(value: u64) -> std::io::Result<libc::off_t> {
352    libc::off_t::try_from(value).map_err(|_| {
353        std::io::Error::new(
354            std::io::ErrorKind::InvalidInput,
355            "file offset exceeds off_t range",
356        )
357    })
358}
359
360#[cfg(test)]
361mod tests {
362    use super::*;
363    use std::io::Write as _;
364    use std::os::unix::fs::MetadataExt;
365
366    fn dense_copy(src: &File, dst: &File, start: u64, len: u64) -> std::io::Result<u64> {
367        copy_sparse_fallback_with_seek(src, dst, start, len, |offset, whence| match whence {
368            nix::unistd::Whence::SeekData | nix::unistd::Whence::SeekHole => {
369                Err(nix::errno::Errno::EOPNOTSUPP)
370            }
371            _ => nix::unistd::lseek(src.as_fd(), offset, whence),
372        })
373    }
374
375    fn make_file(dir: &std::path::Path, name: &str) -> File {
376        std::fs::OpenOptions::new()
377            .read(true)
378            .write(true)
379            .create(true)
380            .truncate(true)
381            .open(dir.join(name))
382            .expect("open temp file")
383    }
384
385    fn copies_with_seek_results(
386        start: u64,
387        probes: &[(nix::unistd::Whence, libc::off_t, nix::Result<libc::off_t>)],
388    ) {
389        let tmp = tempfile::tempdir().unwrap();
390        let contents = b"0123456789abcdef";
391        let mut src = make_file(tmp.path(), "src");
392        src.write_all(contents).unwrap();
393        let mut dst = make_file(tmp.path(), "dst");
394        dst.write_all(&contents[..start as usize]).unwrap();
395        let mut probes = probes.iter();
396        let copied = copy_sparse_fallback_with_seek(
397            &src,
398            &dst,
399            start,
400            contents.len() as u64,
401            |offset, whence| {
402                if matches!(whence, nix::unistd::Whence::SeekEnd) {
403                    return nix::unistd::lseek(src.as_fd(), offset, whence);
404                }
405                // exhausting the script fails promptly if the walker loops instead of degrading.
406                let &(expected_whence, expected_offset, result) = probes.next().unwrap();
407                assert_eq!(
408                    (whence as i32, offset),
409                    (expected_whence as i32, expected_offset)
410                );
411                result
412            },
413        )
414        .unwrap();
415        assert!(probes.next().is_none());
416        assert_eq!(copied, contents.len() as u64);
417        assert_eq!(std::fs::read(tmp.path().join("dst")).unwrap(), contents);
418    }
419
420    fn copies_with_kernel_results(
421        src: &File,
422        dst: &File,
423        len: u64,
424        steps: &[(i64, usize, nix::Result<usize>)],
425        mut before_step: impl FnMut(usize),
426    ) -> std::io::Result<u64> {
427        let mut steps = steps.iter().enumerate();
428        let copied =
429            copy_file_range_all_with(src, dst, len, |src_offset, dst_offset, remaining| {
430                let (step, &(offset, expected_remaining, result)) = steps.next().unwrap();
431                assert_eq!(
432                    (*src_offset, *dst_offset, remaining),
433                    (offset, offset, expected_remaining)
434                );
435                before_step(step);
436                match result {
437                    Ok(n) if n <= remaining => {
438                        let mut bytes = vec![0; n];
439                        src.read_exact_at(&mut bytes, *src_offset as u64).unwrap();
440                        dst.write_all_at(&bytes, *dst_offset as u64).unwrap();
441                        *src_offset += n as i64;
442                        *dst_offset += n as i64;
443                    }
444                    _ => {}
445                }
446                result
447            });
448        assert!(steps.next().is_none());
449        copied
450    }
451
452    #[test]
453    fn falls_back_when_kernel_copy_is_denied_before_progress() {
454        for interrupted in [false, true] {
455            for len in [7, 16, 20] {
456                let tmp = tempfile::tempdir().unwrap();
457                let contents = b"0123456789abcdef";
458                let mut src = make_file(tmp.path(), "src");
459                src.write_all(contents).unwrap();
460                let dst = make_file(tmp.path(), "dst");
461                nix::unistd::lseek(src.as_fd(), 3, nix::unistd::Whence::SeekSet).unwrap();
462                nix::unistd::lseek(dst.as_fd(), 11, nix::unistd::Whence::SeekSet).unwrap();
463                let mut steps = Vec::new();
464                if interrupted {
465                    steps.push((0, len as usize, Err(nix::errno::Errno::EINTR)));
466                }
467                steps.push((0, len as usize, Err(nix::errno::Errno::EPERM)));
468                let copied = copies_with_kernel_results(&src, &dst, len, &steps, |_| {}).unwrap();
469                let expected_len = len.min(contents.len() as u64);
470                assert_eq!(copied, expected_len);
471                assert_eq!(
472                    std::fs::read(tmp.path().join("dst")).unwrap(),
473                    &contents[..expected_len as usize]
474                );
475            }
476        }
477    }
478
479    #[test]
480    fn propagates_permission_errors_after_partial_kernel_copy() {
481        for interrupted in [false, true] {
482            let tmp = tempfile::tempdir().unwrap();
483            let contents = b"0123456789abcdef";
484            let mut src = make_file(tmp.path(), "src");
485            src.write_all(contents).unwrap();
486            let dst = make_file(tmp.path(), "dst");
487            let mut steps = vec![(0, 16, Ok(8))];
488            if interrupted {
489                steps.push((8, 8, Err(nix::errno::Errno::EINTR)));
490            }
491            steps.push((8, 8, Err(nix::errno::Errno::EPERM)));
492            let error = copies_with_kernel_results(&src, &dst, 16, &steps, |_| {}).unwrap_err();
493            assert_eq!(error.raw_os_error(), Some(libc::EPERM));
494            assert_eq!(
495                std::fs::read(tmp.path().join("dst")).unwrap(),
496                &contents[..8]
497            );
498        }
499    }
500
501    #[test]
502    fn propagates_fallback_errors_after_initial_kernel_permission_denial() {
503        let tmp = tempfile::tempdir().unwrap();
504        let mut src = make_file(tmp.path(), "src");
505        src.write_all(b"0123456789abcdef").unwrap();
506        drop(make_file(tmp.path(), "dst"));
507        let dst = File::open(tmp.path().join("dst")).unwrap();
508        let error = copies_with_kernel_results(
509            &src,
510            &dst,
511            16,
512            &[(0, 16, Err(nix::errno::Errno::EPERM))],
513            |_| {},
514        )
515        .unwrap_err();
516        assert_eq!(error.raw_os_error(), Some(libc::EBADF));
517        assert_eq!(dst.metadata().unwrap().len(), 0);
518    }
519
520    #[test]
521    fn rejects_kernel_copy_counts_larger_than_remaining() {
522        for prefix in [0, 8] {
523            let remaining = 16 - prefix;
524            for reported in [remaining + 1, usize::MAX] {
525                let tmp = tempfile::tempdir().unwrap();
526                let contents = b"0123456789abcdef";
527                let mut src = make_file(tmp.path(), "src");
528                src.write_all(contents).unwrap();
529                let dst = make_file(tmp.path(), "dst");
530                let mut steps = Vec::new();
531                if prefix != 0 {
532                    steps.push((0, 16, Ok(prefix)));
533                }
534                steps.push((prefix as i64, remaining, Ok(reported)));
535                let error = copies_with_kernel_results(&src, &dst, 16, &steps, |_| {}).unwrap_err();
536                assert_eq!(error.raw_os_error(), Some(libc::EIO));
537                assert_eq!(
538                    std::fs::read(tmp.path().join("dst")).unwrap(),
539                    &contents[..prefix]
540                );
541            }
542        }
543    }
544
545    #[test]
546    fn falls_back_from_the_confirmed_prefix_for_each_outcome() {
547        for outcome in [
548            Ok(0),
549            Err(nix::errno::Errno::ENOSYS),
550            Err(nix::errno::Errno::EXDEV),
551            Err(nix::errno::Errno::EINVAL),
552            Err(nix::errno::Errno::EOPNOTSUPP),
553        ] {
554            let tmp = tempfile::tempdir().unwrap();
555            let contents = b"0123456789abcdef";
556            let mut src = make_file(tmp.path(), "src");
557            src.write_all(contents).unwrap();
558            let dst = make_file(tmp.path(), "dst");
559            let copied = copies_with_kernel_results(
560                &src,
561                &dst,
562                16,
563                &[(0, 16, Ok(8)), (8, 8, outcome)],
564                |_| {},
565            )
566            .unwrap();
567            assert_eq!(copied, contents.len() as u64);
568            assert_eq!(std::fs::read(tmp.path().join("dst")).unwrap(), contents);
569        }
570    }
571
572    #[test]
573    fn reports_final_size_when_source_shrinks_after_partial_kernel_copy() {
574        for final_len in [0, 3, 8, 12] {
575            let tmp = tempfile::tempdir().unwrap();
576            let contents = b"0123456789abcdef";
577            let mut src = make_file(tmp.path(), "src");
578            src.write_all(contents).unwrap();
579            let dst = make_file(tmp.path(), "dst");
580            let copied = copies_with_kernel_results(
581                &src,
582                &dst,
583                16,
584                &[(0, 16, Ok(8)), (8, 8, Err(nix::errno::Errno::EXDEV))],
585                |step| {
586                    if step == 1 {
587                        src.set_len(final_len).unwrap();
588                    }
589                },
590            )
591            .unwrap();
592            assert_eq!(copied, final_len);
593            assert_eq!(dst.metadata().unwrap().len(), final_len);
594            assert_eq!(
595                std::fs::read(tmp.path().join("dst")).unwrap(),
596                &contents[..final_len as usize]
597            );
598        }
599    }
600
601    #[test]
602    fn retries_interrupted_kernel_copies_without_restarting_the_prefix() {
603        let tmp = tempfile::tempdir().unwrap();
604        let contents = b"0123456789abcdef";
605        let mut src = make_file(tmp.path(), "src");
606        src.write_all(contents).unwrap();
607        let dst = make_file(tmp.path(), "dst");
608        let copied = copies_with_kernel_results(
609            &src,
610            &dst,
611            16,
612            &[
613                (0, 16, Ok(8)),
614                (8, 8, Err(nix::errno::Errno::EINTR)),
615                (8, 8, Ok(8)),
616            ],
617            |_| {},
618        )
619        .unwrap();
620        assert_eq!(copied, contents.len() as u64);
621        assert_eq!(std::fs::read(tmp.path().join("dst")).unwrap(), contents);
622    }
623
624    #[test]
625    fn counts_the_sparse_prefix_when_later_probes_are_unsupported() {
626        use nix::unistd::Whence::{SeekData, SeekHole};
627        for errno in [nix::errno::Errno::EINVAL, nix::errno::Errno::EOPNOTSUPP] {
628            copies_with_seek_results(
629                4,
630                &[
631                    (SeekData, 4, Ok(4)),
632                    (SeekHole, 4, Ok(8)),
633                    (SeekData, 8, Err(errno)),
634                ],
635            );
636        }
637    }
638
639    #[test]
640    fn copies_densely_when_hole_probes_are_unsupported() {
641        use nix::unistd::Whence::{SeekData, SeekHole};
642        for errno in [nix::errno::Errno::EINVAL, nix::errno::Errno::EOPNOTSUPP] {
643            copies_with_seek_results(4, &[(SeekData, 4, Ok(4)), (SeekHole, 4, Err(errno))]);
644        }
645    }
646
647    #[test]
648    fn copies_densely_when_sparse_probes_do_not_advance() {
649        use nix::unistd::Whence::{SeekData, SeekHole};
650        copies_with_seek_results(4, &[(SeekData, 4, Ok(0))]);
651        for hole in [0, 4] {
652            copies_with_seek_results(4, &[(SeekData, 4, Ok(4)), (SeekHole, 4, Ok(hole))]);
653        }
654    }
655
656    #[test]
657    fn propagates_io_errors_from_hole_probes() {
658        let tmp = tempfile::tempdir().unwrap();
659        let mut src = make_file(tmp.path(), "src");
660        src.write_all(b"data").unwrap();
661        let dst = make_file(tmp.path(), "dst");
662        let error = copy_sparse_fallback_with_seek(&src, &dst, 0, 4, |_, whence| match whence {
663            nix::unistd::Whence::SeekData => Ok(0),
664            nix::unistd::Whence::SeekHole => Err(nix::errno::Errno::EIO),
665            _ => unreachable!(),
666        })
667        .unwrap_err();
668        assert_eq!(error.raw_os_error(), Some(libc::EIO));
669    }
670
671    #[test]
672    fn retries_interrupted_extent_io_and_completes_short_writes() {
673        let tmp = tempfile::tempdir().unwrap();
674        let contents = b"interrupted reads and short writes";
675        let mut src = make_file(tmp.path(), "src");
676        src.write_all(contents).unwrap();
677        let dst = make_file(tmp.path(), "dst");
678        let src = crate::testutils::InterruptedFile::new(src);
679        let dst = crate::testutils::InterruptedFile::new(dst);
680        copy_data_extent(&src, &dst, 0, contents.len() as u64, &mut [0; 8]).unwrap();
681        assert_eq!(std::fs::read(tmp.path().join("dst")).unwrap(), contents);
682    }
683
684    #[test]
685    fn does_not_pad_past_read_eof_when_seek_reports_a_larger_size() {
686        for start in [0, 3] {
687            for sparse in [false, true] {
688                let tmp = tempfile::tempdir().unwrap();
689                let contents = b"short";
690                let mut src = make_file(tmp.path(), "src");
691                src.write_all(contents).unwrap();
692                let mut dst = make_file(tmp.path(), "dst");
693                dst.write_all(&contents[..start as usize]).unwrap();
694                // model regular virtual files whose advertised extents exceed readable data.
695                let copied =
696                    copy_sparse_fallback_with_seek(
697                        &src,
698                        &dst,
699                        start,
700                        16,
701                        |_, whence| match whence {
702                            nix::unistd::Whence::SeekData if sparse => Ok(start as libc::off_t),
703                            nix::unistd::Whence::SeekData => Err(nix::errno::Errno::EOPNOTSUPP),
704                            nix::unistd::Whence::SeekHole | nix::unistd::Whence::SeekEnd => Ok(16),
705                            _ => unreachable!(),
706                        },
707                    )
708                    .unwrap();
709                assert_eq!(copied, contents.len() as u64);
710                assert_eq!(std::fs::read(tmp.path().join("dst")).unwrap(), contents);
711            }
712        }
713    }
714
715    #[test]
716    fn reconciles_a_source_shrunk_after_the_last_extent() {
717        for start in [0, 4] {
718            let tmp = tempfile::tempdir().unwrap();
719            let contents = b"0123456789abcdef";
720            let mut src = make_file(tmp.path(), "src");
721            src.write_all(contents).unwrap();
722            let mut dst = make_file(tmp.path(), "dst");
723            dst.write_all(&contents[..start as usize]).unwrap();
724            let copied = copy_sparse_fallback_with_seek(
725                &src,
726                &dst,
727                start,
728                contents.len() as u64,
729                |offset, whence| match whence {
730                    nix::unistd::Whence::SeekData => Ok(start as libc::off_t),
731                    nix::unistd::Whence::SeekHole => Ok(contents.len() as libc::off_t),
732                    nix::unistd::Whence::SeekEnd => {
733                        src.set_len(3).unwrap();
734                        nix::unistd::lseek(src.as_fd(), offset, whence)
735                    }
736                    _ => unreachable!(),
737                },
738            )
739            .unwrap();
740            assert_eq!(copied, 3);
741            assert_eq!(std::fs::read(tmp.path().join("dst")).unwrap(), b"012");
742        }
743    }
744
745    #[test]
746    fn copies_bytes_identically() {
747        let tmp = tempfile::tempdir().unwrap();
748        let contents = b"the quick brown fox jumps over the lazy dog";
749        let mut src = make_file(tmp.path(), "src");
750        src.write_all(contents).unwrap();
751        src.sync_all().unwrap();
752        let dst = make_file(tmp.path(), "dst");
753        let copied = copy_file_range_all(&src, &dst, contents.len() as u64).unwrap();
754        assert_eq!(copied, contents.len() as u64);
755        let got = std::fs::read(tmp.path().join("dst")).unwrap();
756        assert_eq!(got, contents);
757    }
758
759    #[test]
760    fn copies_without_copy_file_range_when_reflink_is_disabled() {
761        let tmp = tempfile::tempdir().unwrap();
762        let contents = b"a non-empty source with an unaligned size";
763        let mut src = make_file(tmp.path(), "src");
764        src.write_all(contents).unwrap();
765        for len in [0, 7, contents.len() as u64, contents.len() as u64 + 100] {
766            let dst = make_file(tmp.path(), "never");
767            let calls_before = crate::testutils::copy_file_range_calls();
768            let copied = copy_file_data(&src, &dst, len, ReflinkMode::Never).unwrap();
769            let expected_len = len.min(contents.len() as u64);
770            assert_eq!(copied, expected_len);
771            assert_eq!(
772                std::fs::read(tmp.path().join("never")).unwrap(),
773                &contents[..expected_len as usize]
774            );
775            assert_eq!(crate::testutils::copy_file_range_calls(), calls_before);
776        }
777        // prove that the counter observes an attempted syscall, even without reflink support.
778        let dst = make_file(tmp.path(), "auto");
779        let calls_before = crate::testutils::copy_file_range_calls();
780        copy_file_data(&src, &dst, contents.len() as u64, ReflinkMode::Auto).unwrap();
781        assert!(crate::testutils::copy_file_range_calls() > calls_before);
782        assert_eq!(std::fs::read(tmp.path().join("auto")).unwrap(), contents);
783    }
784
785    #[test]
786    fn copies_from_zero_with_nonzero_source_and_destination_cursors() {
787        let tmp = tempfile::tempdir().unwrap();
788        let contents = b"independent source and destination cursors";
789        let mut src = make_file(tmp.path(), "src");
790        src.write_all(contents).unwrap();
791        for (policy, len) in [
792            (ReflinkMode::Auto, 7),
793            (ReflinkMode::Auto, contents.len() as u64 + 10),
794            (ReflinkMode::Never, contents.len() as u64),
795        ] {
796            let dst = make_file(tmp.path(), "dst");
797            nix::unistd::lseek(src.as_fd(), 3, nix::unistd::Whence::SeekSet).unwrap();
798            nix::unistd::lseek(dst.as_fd(), 11, nix::unistd::Whence::SeekSet).unwrap();
799            let copied = copy_file_data(&src, &dst, len, policy).unwrap();
800            let expected_len = len.min(contents.len() as u64);
801            assert_eq!(copied, expected_len);
802            assert_eq!(
803                std::fs::read(tmp.path().join("dst")).unwrap(),
804                &contents[..expected_len as usize]
805            );
806        }
807    }
808
809    #[test]
810    fn preserves_sparse_suffix_after_partial_kernel_copy() {
811        let tmp = tempfile::tempdir().unwrap();
812        // leave whole 2 MiB regions as holes even on huge-page tmpfs.
813        let logical = 8 * 1024 * 1024;
814        let src = make_file(tmp.path(), "src");
815        src.set_len(logical).unwrap();
816        src.write_all_at(b"head", 0).unwrap();
817        src.write_all_at(b"tail", 4 * 1024 * 1024).unwrap();
818        src.sync_all().unwrap();
819        let dst = make_file(tmp.path(), "dst");
820        let copied = copies_with_kernel_results(
821            &src,
822            &dst,
823            logical,
824            &[
825                (0, logical as usize, Ok(4096)),
826                (4096, logical as usize - 4096, Err(nix::errno::Errno::EXDEV)),
827            ],
828            |_| {},
829        )
830        .unwrap();
831        assert_eq!(copied, logical);
832        assert_eq!(dst.metadata().unwrap().len(), logical);
833        assert_eq!(
834            std::fs::read(tmp.path().join("dst")).unwrap(),
835            std::fs::read(tmp.path().join("src")).unwrap()
836        );
837        let src_allocated = src.metadata().unwrap().blocks() * 512;
838        let dst_allocated = dst.metadata().unwrap().blocks() * 512;
839        assert!(
840            src_allocated < logical,
841            "source fixture is not sparse: allocated {src_allocated} >= logical {logical}"
842        );
843        assert!(
844            dst_allocated < logical,
845            "destination is not sparse: dst={dst_allocated}, src={src_allocated}, logical={logical}"
846        );
847    }
848
849    #[test]
850    fn copies_sparse_contents_and_trailing_hole_with_auto() {
851        let tmp = tempfile::tempdir().unwrap();
852        let logical = 64 * 1024;
853        let src = make_file(tmp.path(), "src");
854        src.set_len(logical).unwrap();
855        src.write_all_at(b"head", 0).unwrap();
856        src.write_all_at(b"middle", logical / 2).unwrap();
857        let dst = make_file(tmp.path(), "dst");
858        let copied = copy_file_data(&src, &dst, logical, ReflinkMode::Auto).unwrap();
859        assert_eq!(copied, logical);
860        assert_eq!(dst.metadata().unwrap().len(), logical);
861        assert_eq!(
862            std::fs::read(tmp.path().join("dst")).unwrap(),
863            std::fs::read(tmp.path().join("src")).unwrap()
864        );
865        // auto may allocate holes on filesystems without sparse copy_file_range support.
866    }
867
868    #[test]
869    fn copies_large_file_fully() {
870        let tmp = tempfile::tempdir().unwrap();
871        let len: usize = 8 * 1024 * 1024;
872        // varied bytes so a truncated/short copy would be detectable.
873        let data: Vec<u8> = (0..len)
874            .map(|i| (i.wrapping_mul(31) ^ (i >> 7)) as u8)
875            .collect();
876        let mut src = make_file(tmp.path(), "src");
877        src.write_all(&data).unwrap();
878        src.sync_all().unwrap();
879        let dst = make_file(tmp.path(), "dst");
880        let copied = copy_file_range_all(&src, &dst, len as u64).unwrap();
881        assert_eq!(copied, len as u64);
882        let got = std::fs::read(tmp.path().join("dst")).unwrap();
883        assert_eq!(got.len(), len);
884        assert!(got == data, "destination bytes differ from source");
885    }
886
887    #[test]
888    fn preserves_holes_when_reflink_is_disabled() {
889        let tmp = tempfile::tempdir().unwrap();
890        let logical: u64 = 8 * 1024 * 1024;
891        let head = b"HEAD-region-bytes";
892        let tail = b"TAIL-region-bytes";
893        let tail_off = logical - tail.len() as u64;
894        let src = make_file(tmp.path(), "src");
895        // create a sparse file: size = logical, small data near start and end,
896        // big hole in the middle.
897        nix::unistd::ftruncate(src.as_fd(), to_off_t(logical).unwrap()).unwrap();
898        src.write_at(head, 0).unwrap();
899        src.write_at(tail, tail_off).unwrap();
900        src.sync_all().unwrap();
901        let dst = make_file(tmp.path(), "dst");
902        // never must preserve holes without relying on copy_file_range support.
903        let copied = copy_file_data(&src, &dst, logical, ReflinkMode::Never).unwrap();
904        assert_eq!(copied, logical);
905        // (a) content byte-equal to src across the whole logical range.
906        let got = std::fs::read(tmp.path().join("dst")).unwrap();
907        let expected = std::fs::read(tmp.path().join("src")).unwrap();
908        assert_eq!(got.len() as u64, logical);
909        assert_eq!(got, expected, "destination content differs from source");
910        // spot-check the data regions explicitly.
911        assert_eq!(&got[..head.len()], head);
912        assert_eq!(&got[tail_off as usize..], tail);
913        // (b) dst size == logical.
914        let dst_meta = std::fs::metadata(tmp.path().join("dst")).unwrap();
915        assert_eq!(dst_meta.len(), logical);
916        // (c) dst is actually sparse: allocated bytes << logical size.
917        let src_meta = std::fs::metadata(tmp.path().join("src")).unwrap();
918        let dst_allocated = dst_meta.blocks() * 512;
919        let src_allocated = src_meta.blocks() * 512;
920        eprintln!(
921            "sparse blocks: src={} blocks ({} bytes), dst={} blocks ({} bytes), logical={} bytes",
922            src_meta.blocks(),
923            src_allocated,
924            dst_meta.blocks(),
925            dst_allocated,
926            logical
927        );
928        assert!(
929            dst_allocated < logical,
930            "destination is not sparse: allocated {dst_allocated} >= logical {logical}"
931        );
932        // dst should be roughly as sparse as src (within a generous factor to
933        // tolerate filesystem block-allocation differences).
934        assert!(
935            dst_allocated <= src_allocated * 4 + 4096,
936            "destination far less sparse than source: dst={dst_allocated} src={src_allocated}"
937        );
938    }
939
940    #[test]
941    fn terminates_on_short_source() {
942        let tmp = tempfile::tempdir().unwrap();
943        let contents = b"short source contents";
944        let real_len = contents.len() as u64;
945        let mut src = make_file(tmp.path(), "src");
946        src.write_all(contents).unwrap();
947        src.sync_all().unwrap();
948        // create the destination so the worker thread can open it for writing.
949        let _dst = make_file(tmp.path(), "dst");
950        // claim a length larger than the real file: must return promptly having
951        // copied exactly the real bytes (the Ok(0)/EOF guard prevents a hang).
952        let claimed = real_len + 4096;
953        let (tx, rx) = std::sync::mpsc::channel();
954        let src_path = tmp.path().join("src");
955        let dst_path = tmp.path().join("dst");
956        std::thread::spawn(move || {
957            let src = std::fs::File::open(&src_path).unwrap();
958            let dst = std::fs::OpenOptions::new()
959                .read(true)
960                .write(true)
961                .open(&dst_path)
962                .unwrap();
963            let copied = copy_file_range_all(&src, &dst, claimed).unwrap();
964            tx.send(copied).unwrap();
965        });
966        let copied = rx
967            .recv_timeout(std::time::Duration::from_secs(10))
968            .expect("copy_file_range_all hung on a short source");
969        assert_eq!(copied, real_len);
970        let got = std::fs::read(tmp.path().join("dst")).unwrap();
971        assert_eq!(got, contents);
972    }
973
974    #[test]
975    fn copies_partial_len_on_both_paths() {
976        // caller asks for fewer bytes than the source has: both paths must copy
977        // exactly `len` bytes, leave dst at `len`, and return `len`.
978        let tmp = tempfile::tempdir().unwrap();
979        let full: Vec<u8> = (0u32..4096).map(|i| (i % 251) as u8).collect();
980        let len: u64 = 1000;
981        let mut src = make_file(tmp.path(), "src");
982        src.write_all(&full).unwrap();
983        src.sync_all().unwrap();
984        // primary path.
985        let dst_cfr = make_file(tmp.path(), "dst_cfr");
986        let copied_cfr = copy_file_range_all(&src, &dst_cfr, len).unwrap();
987        assert_eq!(copied_cfr, len);
988        let got_cfr = std::fs::read(tmp.path().join("dst_cfr")).unwrap();
989        assert_eq!(got_cfr.len() as u64, len);
990        assert_eq!(got_cfr, &full[..len as usize]);
991        // fallback path called directly.
992        let dst_fb = make_file(tmp.path(), "dst_fb");
993        let copied_fb = copy_sparse_fallback(&src, &dst_fb, 0, len).unwrap();
994        assert_eq!(copied_fb, len);
995        let got_fb = std::fs::read(tmp.path().join("dst_fb")).unwrap();
996        assert_eq!(got_fb.len() as u64, len);
997        assert_eq!(got_fb, &full[..len as usize]);
998    }
999
1000    #[test]
1001    fn fallback_shrunk_source_not_padded() {
1002        // locks the primary/fallback reconciliation: when `len` exceeds the
1003        // source size, the fallback must size dst to the actual source end (not
1004        // pad a spurious trailing hole up to `len`) and return the actual bytes.
1005        let tmp = tempfile::tempdir().unwrap();
1006        let contents: Vec<u8> = (0u32..3000).map(|i| (i % 240) as u8).collect();
1007        let s = contents.len() as u64;
1008        let mut src = make_file(tmp.path(), "src");
1009        src.write_all(&contents).unwrap();
1010        src.sync_all().unwrap();
1011        let dst = make_file(tmp.path(), "dst");
1012        let copied = copy_sparse_fallback(&src, &dst, 0, s + 8192).unwrap();
1013        assert_eq!(
1014            copied, s,
1015            "must return actual source bytes, not the claimed len"
1016        );
1017        let dst_meta = std::fs::metadata(tmp.path().join("dst")).unwrap();
1018        assert_eq!(
1019            dst_meta.len(),
1020            s,
1021            "dst must be sized to the source, not padded"
1022        );
1023        let got = std::fs::read(tmp.path().join("dst")).unwrap();
1024        assert_eq!(got, contents);
1025    }
1026
1027    #[test]
1028    fn copies_zero_length() {
1029        let tmp = tempfile::tempdir().unwrap();
1030        let mut src = make_file(tmp.path(), "src");
1031        src.write_all(b"non-empty source contents").unwrap();
1032        src.sync_all().unwrap();
1033        let dst = make_file(tmp.path(), "dst");
1034        let calls_before = crate::testutils::copy_file_range_calls();
1035        let copied = copy_file_range_all(&src, &dst, 0).unwrap();
1036        assert_eq!(copied, 0);
1037        assert_eq!(crate::testutils::copy_file_range_calls(), calls_before);
1038        let dst_meta = std::fs::metadata(tmp.path().join("dst")).unwrap();
1039        assert_eq!(dst_meta.len(), 0, "zero-length copy must leave dst empty");
1040    }
1041
1042    #[test]
1043    fn copies_all_hole_source_when_reflink_is_disabled() {
1044        // a pure-hole source: SEEK_DATA returns ENXIO immediately, so the loop
1045        // does no copies and only ftruncate sizes dst. dst must be all zeros,
1046        // sized to `len`, and sparse.
1047        let tmp = tempfile::tempdir().unwrap();
1048        let logical: u64 = 4 * 1024 * 1024;
1049        let src = make_file(tmp.path(), "src");
1050        nix::unistd::ftruncate(src.as_fd(), to_off_t(logical).unwrap()).unwrap();
1051        src.sync_all().unwrap();
1052        let dst = make_file(tmp.path(), "dst");
1053        let copied = copy_file_data(&src, &dst, logical, ReflinkMode::Never).unwrap();
1054        assert_eq!(copied, logical);
1055        let got = std::fs::read(tmp.path().join("dst")).unwrap();
1056        assert_eq!(got.len() as u64, logical);
1057        assert!(
1058            got.iter().all(|&b| b == 0),
1059            "all-hole copy must be all zeros"
1060        );
1061        let dst_meta = std::fs::metadata(tmp.path().join("dst")).unwrap();
1062        assert_eq!(dst_meta.len(), logical);
1063        let dst_allocated = dst_meta.blocks() * 512;
1064        eprintln!(
1065            "all-hole: dst={} blocks ({dst_allocated} bytes), logical={logical}",
1066            dst_meta.blocks()
1067        );
1068        assert!(
1069            dst_allocated < logical,
1070            "all-hole destination is not sparse: allocated {dst_allocated} >= logical {logical}"
1071        );
1072    }
1073
1074    #[test]
1075    fn classify_seek_data_routes_by_errno() {
1076        // the testable seam for the sparse-vs-dense decision. data offset and a
1077        // legitimate trailing hole stay on the sparse path; the "unsupported"
1078        // errnos route to dense; a genuine I/O error propagates.
1079        assert_eq!(
1080            classify_seek_data(Ok(4096)).unwrap(),
1081            SparseProbe::Data(4096)
1082        );
1083        assert_eq!(
1084            classify_seek_data(Err(nix::errno::Errno::ENXIO)).unwrap(),
1085            SparseProbe::TrailingHole
1086        );
1087        // EINVAL and EOPNOTSUPP (== ENOTSUP on Linux) mean "fs can't SEEK_DATA".
1088        assert_eq!(
1089            classify_seek_data(Err(nix::errno::Errno::EINVAL)).unwrap(),
1090            SparseProbe::Unsupported
1091        );
1092        assert_eq!(
1093            classify_seek_data(Err(nix::errno::Errno::EOPNOTSUPP)).unwrap(),
1094            SparseProbe::Unsupported
1095        );
1096        assert_eq!(
1097            classify_seek_data(Err(nix::errno::Errno::ENOTSUP)).unwrap(),
1098            SparseProbe::Unsupported
1099        );
1100        // a genuine I/O error is NOT masked as "unsupported" — it propagates.
1101        let err = classify_seek_data(Err(nix::errno::Errno::EIO)).unwrap_err();
1102        assert_eq!(err.raw_os_error(), Some(libc::EIO));
1103    }
1104
1105    #[test]
1106    fn dense_copy_is_byte_exact_with_embedded_zeros() {
1107        // dense_copy must reproduce the source byte-for-byte, including embedded
1108        // zero regions (it does not preserve them as holes, just copies zeros).
1109        let tmp = tempfile::tempdir().unwrap();
1110        let len: usize = 3 * FALLBACK_BUF_SIZE + 777; // multiple buffers + a tail.
1111        let mut data: Vec<u8> = (0..len)
1112            .map(|i| (i.wrapping_mul(37) ^ (i >> 5)) as u8)
1113            .collect();
1114        // carve out a couple of embedded zero regions (crossing a buffer edge).
1115        for b in data.iter_mut().take(FALLBACK_BUF_SIZE + 4096).skip(100) {
1116            *b = 0;
1117        }
1118        for b in data
1119            .iter_mut()
1120            .take(2 * FALLBACK_BUF_SIZE)
1121            .skip(2 * FALLBACK_BUF_SIZE - 500)
1122        {
1123            *b = 0;
1124        }
1125        let mut src = make_file(tmp.path(), "src");
1126        src.write_all(&data).unwrap();
1127        src.sync_all().unwrap();
1128        let dst = make_file(tmp.path(), "dst");
1129        let copied = dense_copy(&src, &dst, 0, len as u64).unwrap();
1130        assert_eq!(copied, len as u64);
1131        let got = std::fs::read(tmp.path().join("dst")).unwrap();
1132        assert_eq!(got.len(), len, "dense copy must size dst to the source");
1133        assert!(got == data, "dense copy bytes differ from source");
1134    }
1135
1136    #[test]
1137    fn dense_copy_partial_len_sizes_dst_exactly() {
1138        // when `len` is below the source size, dense_copy copies exactly `len`
1139        // bytes and ftruncates dst to `len` (matching the sparse path).
1140        let tmp = tempfile::tempdir().unwrap();
1141        let full: Vec<u8> = (0u32..8192).map(|i| (i % 251) as u8).collect();
1142        let len: u64 = 5000;
1143        let mut src = make_file(tmp.path(), "src");
1144        src.write_all(&full).unwrap();
1145        src.sync_all().unwrap();
1146        let dst = make_file(tmp.path(), "dst");
1147        let copied = dense_copy(&src, &dst, 0, len).unwrap();
1148        assert_eq!(copied, len);
1149        let got = std::fs::read(tmp.path().join("dst")).unwrap();
1150        assert_eq!(got.len() as u64, len);
1151        assert_eq!(got, &full[..len as usize]);
1152    }
1153
1154    #[test]
1155    fn dense_copy_shrunk_source_not_padded() {
1156        // mirrors `fallback_shrunk_source_not_padded` for the dense path: a `len`
1157        // larger than the source must size dst to the actual source end and
1158        // return the actual bytes, not pad up to `len`.
1159        let tmp = tempfile::tempdir().unwrap();
1160        let contents: Vec<u8> = (0u32..3000).map(|i| (i % 240) as u8).collect();
1161        let s = contents.len() as u64;
1162        let mut src = make_file(tmp.path(), "src");
1163        src.write_all(&contents).unwrap();
1164        src.sync_all().unwrap();
1165        let dst = make_file(tmp.path(), "dst");
1166        let copied = dense_copy(&src, &dst, 0, s + 8192).unwrap();
1167        assert_eq!(
1168            copied, s,
1169            "dense copy must return actual source bytes, not the claimed len"
1170        );
1171        let dst_meta = std::fs::metadata(tmp.path().join("dst")).unwrap();
1172        assert_eq!(dst_meta.len(), s, "dst must be sized to the source");
1173        let got = std::fs::read(tmp.path().join("dst")).unwrap();
1174        assert_eq!(got, contents);
1175    }
1176
1177    #[test]
1178    fn copies_densely_when_the_initial_probe_is_unsupported() {
1179        for errno in [nix::errno::Errno::EINVAL, nix::errno::Errno::EOPNOTSUPP] {
1180            copies_with_seek_results(4, &[(nix::unistd::Whence::SeekData, 4, Err(errno))]);
1181        }
1182    }
1183}