1use std::fs::File;
50use std::os::fd::AsFd;
51use std::os::unix::fs::FileExt;
52
53const FALLBACK_BUF_SIZE: usize = 1024 * 1024;
55
56#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, clap::ValueEnum)]
61pub enum ReflinkMode {
62 #[default]
64 Auto,
65 Never,
67}
68
69pub 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
90fn 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
112fn 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 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 return copy_sparse_fallback(src, dst, copied, len);
142 }
143 Err(nix::errno::Errno::EPERM) if copied == 0 => {
144 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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
159enum SparseProbe {
160 Data(u64),
162 TrailingHole,
165 Unsupported,
168}
169
170fn 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 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
195fn 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 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 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 read_eof = Some(end);
263 break;
264 }
265 off = extent.end;
266 }
267 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 nix::unistd::ftruncate(dst.as_fd(), to_off_t(final_size)?).map_err(std::io::Error::from)?;
273 }
274 Ok(final_size)
276}
277
278enum CopyExtent {
279 Sparse(std::ops::Range<u64>),
280 Dense,
281 End,
282}
283
284fn 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 return Ok(CopyExtent::Dense);
313 }
314 Ok(CopyExtent::Sparse(data..hole))
315}
316
317fn 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
349fn 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 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 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 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 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 }
867
868 #[test]
869 fn copies_large_file_fully() {
870 let tmp = tempfile::tempdir().unwrap();
871 let len: usize = 8 * 1024 * 1024;
872 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 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 let copied = copy_file_data(&src, &dst, logical, ReflinkMode::Never).unwrap();
904 assert_eq!(copied, logical);
905 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 assert_eq!(&got[..head.len()], head);
912 assert_eq!(&got[tail_off as usize..], tail);
913 let dst_meta = std::fs::metadata(tmp.path().join("dst")).unwrap();
915 assert_eq!(dst_meta.len(), logical);
916 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 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 let _dst = make_file(tmp.path(), "dst");
950 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 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 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 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 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 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 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 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 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 let tmp = tempfile::tempdir().unwrap();
1110 let len: usize = 3 * FALLBACK_BUF_SIZE + 777; let mut data: Vec<u8> = (0..len)
1112 .map(|i| (i.wrapping_mul(37) ^ (i >> 5)) as u8)
1113 .collect();
1114 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 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 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}