bolt_unix.go 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. // +build !windows,!plan9,!solaris
  2. package bolt
  3. import (
  4. "fmt"
  5. "os"
  6. "syscall"
  7. "time"
  8. "unsafe"
  9. )
  10. // flock acquires an advisory lock on a file descriptor.
  11. func flock(db *DB, mode os.FileMode, exclusive bool, timeout time.Duration) error {
  12. var t time.Time
  13. if timeout != 0 {
  14. t = time.Now()
  15. }
  16. fd := db.file.Fd()
  17. flag := syscall.LOCK_NB
  18. if exclusive {
  19. flag |= syscall.LOCK_EX
  20. } else {
  21. flag |= syscall.LOCK_SH
  22. }
  23. for {
  24. // Attempt to obtain an exclusive lock.
  25. err := syscall.Flock(int(fd), flag)
  26. if err == nil {
  27. return nil
  28. } else if err != syscall.EWOULDBLOCK {
  29. return err
  30. }
  31. // If we timed out then return an error.
  32. if timeout != 0 && time.Since(t) > timeout-flockRetryTimeout {
  33. return ErrTimeout
  34. }
  35. // Wait for a bit and try again.
  36. time.Sleep(flockRetryTimeout)
  37. }
  38. }
  39. // funlock releases an advisory lock on a file descriptor.
  40. func funlock(db *DB) error {
  41. return syscall.Flock(int(db.file.Fd()), syscall.LOCK_UN)
  42. }
  43. // mmap memory maps a DB's data file.
  44. func mmap(db *DB, sz int) error {
  45. // Map the data file to memory.
  46. b, err := syscall.Mmap(int(db.file.Fd()), 0, sz, syscall.PROT_READ, syscall.MAP_SHARED|db.MmapFlags)
  47. if err != nil {
  48. return err
  49. }
  50. // Advise the kernel that the mmap is accessed randomly.
  51. err = madvise(b, syscall.MADV_RANDOM)
  52. if err != nil && err != syscall.ENOSYS {
  53. // Ignore not implemented error in kernel because it still works.
  54. return fmt.Errorf("madvise: %s", err)
  55. }
  56. // Save the original byte slice and convert to a byte array pointer.
  57. db.dataref = b
  58. db.data = (*[maxMapSize]byte)(unsafe.Pointer(&b[0]))
  59. db.datasz = sz
  60. return nil
  61. }
  62. // munmap unmaps a DB's data file from memory.
  63. func munmap(db *DB) error {
  64. // Ignore the unmap if we have no mapped data.
  65. if db.dataref == nil {
  66. return nil
  67. }
  68. // Unmap using the original byte slice.
  69. err := syscall.Munmap(db.dataref)
  70. db.dataref = nil
  71. db.data = nil
  72. db.datasz = 0
  73. return err
  74. }
  75. // NOTE: This function is copied from stdlib because it is not available on darwin.
  76. func madvise(b []byte, advice int) (err error) {
  77. _, _, e1 := syscall.Syscall(syscall.SYS_MADVISE, uintptr(unsafe.Pointer(&b[0])), uintptr(len(b)), uintptr(advice))
  78. if e1 != 0 {
  79. err = e1
  80. }
  81. return
  82. }