Debian Codegraph @

preallocate_darwin.go

raw
1 //go:build darwin
2
3 package desync
4
5 import (
6 "errors"
7 "fmt"
8 "os"
9
10 "golang.org/x/sys/unix"
11 )
12
13 // preallocateFile physically allocates disk blocks and sets the file size.
14 // On APFS, a plain Truncate creates sparse holes. When concurrent workers
15 // call WriteAt on adjacent regions, copy-on-write of sparse blocks can
16 // cause non-deterministic data corruption. Pre-allocating real blocks
17 // avoids this.
18 func preallocateFile(name string, size int64) error {
19 f, err := os.OpenFile(name, os.O_WRONLY|os.O_CREATE, 0666)
20 if err != nil {
21 return err
22 }
23 defer f.Close()
24
25 info, err := f.Stat()
26 if err != nil {
27 return err
28 }
29
30 // F_PREALLOCATE with F_PEOFPOSMODE allocates relative to the current
31 // end of file, so only request the difference. Nothing to allocate if
32 // the file is already large enough or no growth is needed.
33 if extra := size - info.Size(); extra > 0 {
34 store := unix.Fstore_t{
35 Flags: unix.F_ALLOCATEALL,
36 Posmode: unix.F_PEOFPOSMODE,
37 Offset: 0,
38 Length: extra,
39 }
40 if err := unix.FcntlFstore(f.Fd(), unix.F_PREALLOCATE, &store); err != nil {
41 // Not all filesystems support F_PREALLOCATE (e.g. SMB or FUSE
42 // mounts). The sparse-hole issue is specific to APFS, so fall
43 // back to a plain truncate there.
44 if !errors.Is(err, unix.ENOTSUP) {
45 return fmt.Errorf("F_PREALLOCATE %s: %w", name, err)
46 }
47 }
48 }
49
50 return f.Truncate(size)
51 }