preallocate_darwin.go 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. // Copyright 2016 The etcd Authors
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. // +build darwin
  15. package fileutil
  16. import (
  17. "os"
  18. "syscall"
  19. "unsafe"
  20. )
  21. func preallocExtend(f *os.File, sizeInBytes int64) error {
  22. if err := preallocFixed(f, sizeInBytes); err != nil {
  23. return err
  24. }
  25. return preallocExtendTrunc(f, sizeInBytes)
  26. }
  27. func preallocFixed(f *os.File, sizeInBytes int64) error {
  28. // allocate all requested space or no space at all
  29. // TODO: allocate contiguous space on disk with F_ALLOCATECONTIG flag
  30. fstore := &syscall.Fstore_t{
  31. Flags: syscall.F_ALLOCATEALL,
  32. Posmode: syscall.F_PEOFPOSMODE,
  33. Length: sizeInBytes}
  34. p := unsafe.Pointer(fstore)
  35. _, _, errno := syscall.Syscall(syscall.SYS_FCNTL, f.Fd(), uintptr(syscall.F_PREALLOCATE), uintptr(p))
  36. if errno == 0 || errno == syscall.ENOTSUP {
  37. return nil
  38. }
  39. // wrong argument to fallocate syscall
  40. if errno == syscall.EINVAL {
  41. // filesystem "st_blocks" are allocated in the units of
  42. // "Allocation Block Size" (run "diskutil info /" command)
  43. var stat syscall.Stat_t
  44. syscall.Fstat(int(f.Fd()), &stat)
  45. // syscall.Statfs_t.Bsize is "optimal transfer block size"
  46. // and contains matching 4096 value when latest OS X kernel
  47. // supports 4,096 KB filesystem block size
  48. var statfs syscall.Statfs_t
  49. syscall.Fstatfs(int(f.Fd()), &statfs)
  50. blockSize := int64(statfs.Bsize)
  51. if stat.Blocks*blockSize >= sizeInBytes {
  52. // enough blocks are already allocated
  53. return nil
  54. }
  55. }
  56. return errno
  57. }