You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

93 lines
2.1 KiB

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