Skip to content

Commit

Permalink
virtiofs: fallocate: should enlarge but not shrink the file
Browse files Browse the repository at this point in the history
Before this patch on virtiofs we had:
```
$ fallocate -o 0 -l 1024 f
$ ls -l f
-rw-r--r--    1 root     root          1024 Jun 24 13:00 f
$ fallocate -o 0 -l 512 f
$ ls -l f
-rw-r--r--    1 root     root           512 Jun 24 13:00 f
```

Unfortunately the second `fallocate` call caused the file to shrink, due to
the call to `ftruncate`.

On a tmpfs for comparison the file doesn't shrink:
```
$ fallocate -o 0 -l 1024 f
$ ls -l f
-rw-r--r--    1 root     root          1024 Jun 24 12:55 f
$ fallocate -o 0 -l 512 f
$ ls -l f
-rw-r--r--    1 root     root          1024 Jun 24 12:56 f
```

This patch only calls ftuncate() if the proposed_length is larger
than the current length.

Signed-off-by: David Scott <[email protected]>
  • Loading branch information
djs55 authored and slp committed Jul 2, 2024
1 parent c4c4274 commit ddbd2fd
Showing 1 changed file with 8 additions and 2 deletions.
10 changes: 8 additions & 2 deletions src/devices/src/virtio/fs/macos/passthrough.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1731,11 +1731,12 @@ impl FileSystem for PassthroughFs {

let fd = data.file.write().unwrap().as_raw_fd();

let proposed_length = (offset + length) as i64;
let mut fs = libc::fstore_t {
fst_flags: libc::F_ALLOCATECONTIG,
fst_posmode: libc::F_PEOFPOSMODE,
fst_offset: 0,
fst_length: (offset + length) as i64,
fst_length: proposed_length,
fst_bytesalloc: 0,
};

Expand All @@ -1748,7 +1749,12 @@ impl FileSystem for PassthroughFs {
}
}

let res = unsafe { libc::ftruncate(fd, (offset + length) as i64) };
let st = fstat(fd, true)?;
if st.st_size >= proposed_length {
// fallocate should not shrink the file. The file is already larger than needed.
return Ok(());
}
let res = unsafe { libc::ftruncate(fd, proposed_length) };

if res == 0 {
Ok(())
Expand Down

0 comments on commit ddbd2fd

Please sign in to comment.