Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(mmap): pre-allocate temp file before mmapping #50

Merged
merged 2 commits into from
May 19, 2023
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ digest = "0.10.6"
either = "1.6.1"
futures = "0.3.17"
hex = "0.4.3"
libc = "0.2.144"
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

could you make this an optional dependency that goes along with memmap? Since we don't use libc unless the mmap feature is enabled.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

sure, done

memmap2 = { version = "0.5.8", optional = true }
miette = "5.7.0"
reflink = "0.1.3"
Expand Down
41 changes: 32 additions & 9 deletions src/content/write.rs
Original file line number Diff line number Diff line change
Expand Up @@ -413,21 +413,44 @@ impl AsyncWriter {
#[cfg(feature = "mmap")]
fn make_mmap(tmpfile: &mut NamedTempFile, size: Option<usize>) -> Result<Option<MmapMut>> {
if let Some(size @ 0..=MAX_MMAP_SIZE) = size {
tmpfile
.as_file_mut()
.set_len(size as u64)
.with_context(|| {
format!(
"Failed to configure file length for temp file at {}",
tmpfile.path().display()
)
})?;
allocate_file(tmpfile.as_file(), size).with_context(|| {
format!(
"Failed to configure file length for temp file at {}",
tmpfile.path().display()
)
})?;
Ok(unsafe { MmapMut::map_mut(tmpfile.as_file()).ok() })
} else {
Ok(None)
}
}

#[cfg(feature = "mmap")]
#[cfg(target_os = "linux")]
fn allocate_file(file: &std::fs::File, size: usize) -> std::io::Result<()> {
use std::io::{Error, ErrorKind};
use std::os::fd::AsRawFd;

let fd = file.as_raw_fd();
match unsafe { libc::posix_fallocate64(fd, 0, size as i64) } {
0 => Ok(()),
libc::ENOSPC => Err(Error::new(
ErrorKind::Other, // ErrorKind::StorageFull is unstable
"cannot allocate file: no space left on device",
)),
err => Err(Error::new(
ErrorKind::Other,
format!("posix_fallocate64 failed with code {err}"),
)),
}
}

#[cfg(feature = "mmap")]
#[cfg(not(target_os = "linux"))]
fn allocate_file(file: &std::fs::File, size: usize) -> std::io::Result<()> {
file.set_len(size as u64)
}

#[cfg(not(feature = "mmap"))]
fn make_mmap(_: &mut NamedTempFile, _: Option<usize>) -> Result<Option<MmapMut>> {
Ok(None)
Expand Down