use crate::error::Result;
use crate::filesystem::disk_adaptor::DiskAdaptor;
#[cfg(unix)]
use crate::error::Aria2Error;
#[cfg(unix)]
use super::strategies;
#[cfg_attr(target_os = "linux", allow(unused_variables))]
pub(crate) async fn fallocate<D: DiskAdaptor>(
adaptor: &mut D,
length: u64,
secure: bool,
) -> Result<()> {
#[cfg(target_os = "linux")]
{
if let Some(fd) = adaptor.unix_raw_fd() {
if length > i64::MAX as u64 {
return Err(Aria2Error::Io(
"fallocate length exceeds off_t range".into(),
));
}
let ret = unsafe { libc::fallocate(fd, 0 as libc::c_int, 0, length as libc::off_t) };
if ret == 0 {
return Ok(());
}
let errno = unsafe { *libc::__errno_location() };
if errno == libc::EOPNOTSUPP {
tracing::warn!(
length,
"fallocate(2) not supported by filesystem; \
falling back to async zero-fill"
);
adaptor.truncate(length).await?;
return strategies::async_zero_fill(adaptor, length).await;
}
Err(Aria2Error::Io(
std::io::Error::from_raw_os_error(errno).to_string(),
))
} else {
adaptor.truncate(length).await
}
}
#[cfg(all(unix, not(target_os = "linux")))]
{
#[cfg(target_os = "macos")]
{
match adaptor.unix_raw_fd() {
Some(fd) => {
if length > i64::MAX as u64 {
return Err(Aria2Error::Io(
"F_PREALLOCATE length exceeds off_t range".into(),
));
}
adaptor.truncate(length).await?;
let fstore = libc::fstore_t {
fst_flags: libc::F_ALLOCATEALL as libc::c_uint,
fst_posmode: libc::F_PEOFPOSMODE,
fst_offset: 0,
fst_length: length as libc::off_t,
fst_bytesalloc: 0,
};
let ret = unsafe { libc::fcntl(fd, libc::F_PREALLOCATE, &fstore) };
if ret != 0 {
tracing::warn!(
length,
"F_PREALLOCATE failed on macOS, file remains sparse"
);
return Ok(());
}
if secure {
strategies::async_zero_fill(adaptor, length).await
} else {
super::SECURE_FALLOC_WARN_ONCE.call_once(|| {
tracing::warn!(
"F_PREALLOCATE succeeded but does not zero-fill; \
residual disk data may be exposed. \
Enable --secure-falloc=true to zero-fill (at a \
performance cost). This warning is logged once."
);
});
Ok(())
}
}
None => adaptor.truncate(length).await,
}
}
#[cfg(not(target_os = "macos"))]
{
adaptor.truncate(length).await
}
}
#[cfg(not(unix))]
{
super::windows::fallocate_windows(adaptor, length, secure).await
}
}