use std::fs::File;
use std::sync::atomic::{AtomicBool, Ordering};
const STEP: u64 = 8 * 1024 * 1024;
const ALIGN: u64 = 4096;
pub fn punch_whole_blocks(file: &File, from: u64, read_to: u64) -> Option<u64> {
let upto = read_to - read_to % ALIGN;
if upto < from + STEP {
return None;
}
match punch(file, from, upto - from) {
Ok(()) => Some(upto),
Err(e) => {
static WARNED: AtomicBool = AtomicBool::new(false);
if !WARNED.swap(true, Ordering::Relaxed) {
tracing::warn!(
"cannot give disk space back while merging ({e}); \
--reclaim-chunks only deletes each run at its end"
);
}
None
}
}
}
#[cfg(target_os = "macos")]
#[allow(
unsafe_code,
reason = "fcntl(F_PUNCHHOLE) takes a pointer to a fpunchhole_t that lives through the call"
)]
fn punch(file: &File, offset: u64, len: u64) -> std::io::Result<()> {
use std::os::fd::AsRawFd;
let request = libc::fpunchhole_t {
fp_flags: 0,
reserved: 0,
fp_offset: libc::off_t::try_from(offset).map_err(std::io::Error::other)?,
fp_length: libc::off_t::try_from(len).map_err(std::io::Error::other)?,
};
let result = unsafe { libc::fcntl(file.as_raw_fd(), libc::F_PUNCHHOLE, &request) };
if result == -1 {
return Err(std::io::Error::last_os_error());
}
Ok(())
}
#[cfg(target_os = "linux")]
#[allow(
unsafe_code,
reason = "fallocate(PUNCH_HOLE | KEEP_SIZE) takes only integers and a descriptor"
)]
fn punch(file: &File, offset: u64, len: u64) -> std::io::Result<()> {
use std::os::fd::AsRawFd;
let result = unsafe {
libc::fallocate(
file.as_raw_fd(),
libc::FALLOC_FL_PUNCH_HOLE | libc::FALLOC_FL_KEEP_SIZE,
libc::off_t::try_from(offset).map_err(std::io::Error::other)?,
libc::off_t::try_from(len).map_err(std::io::Error::other)?,
)
};
if result == -1 {
return Err(std::io::Error::last_os_error());
}
Ok(())
}
#[cfg(not(any(target_os = "macos", target_os = "linux")))]
fn punch(_file: &File, _offset: u64, _len: u64) -> std::io::Result<()> {
Err(std::io::Error::from(std::io::ErrorKind::Unsupported))
}
#[cfg(test)]
mod tests {
use super::*;
use std::io::Write;
#[test]
fn nothing_is_freed_before_a_step_is_ready() {
let file = tempfile::tempfile().expect("tempfile");
assert_eq!(punch_whole_blocks(&file, 0, STEP - 1), None);
}
#[test]
fn a_punched_file_keeps_its_length_and_reads_zeros_in_the_hole() {
let dir = tempfile::tempdir().expect("tmpdir");
let path = dir.path().join("hole");
let mut file = File::create(&path).expect("create");
file.write_all(&vec![0xAB; (STEP * 2) as usize])
.expect("write");
file.sync_all().expect("sync");
drop(file);
let file = std::fs::OpenOptions::new()
.read(true)
.write(true)
.open(&path)
.expect("open");
let Some(upto) = punch_whole_blocks(&file, 0, STEP + 5000) else {
eprintln!("skipped: this file system cannot punch holes");
return;
};
assert_eq!(upto % ALIGN, 0);
assert!(upto >= STEP);
let data = std::fs::read(&path).expect("read");
assert_eq!(data.len() as u64, STEP * 2);
assert!(data[..upto as usize].iter().all(|b| *b == 0));
assert!(data[upto as usize..].iter().all(|b| *b == 0xAB));
}
}