mirror of
https://github.com/schollz/cowyo.git
synced 2023-08-10 21:13:00 +03:00
e8a4d30139
Former-commit-id: 900e1a398fd82aa1cea4f319e89b8088dd81cf6c [formerly f172c22b12c49c0291e0d986dc4af94fcc91d192] [formerly 43c5da81442a5f0ca79a6eabb1dfdfbfb3f22680 [formerly 2694d0b183
]]
Former-commit-id: fa39d6a984adc4ca8f8c82c5df145c336885a53f [formerly 94543f8081bc18b1a39daf8500cfa7e0b1ba7393]
Former-commit-id: 809aae62e28a3f99a01854f71fcd5a85f89d2972
91 lines
2.0 KiB
Go
91 lines
2.0 KiB
Go
package bolt
|
|
|
|
import (
|
|
"fmt"
|
|
"os"
|
|
"syscall"
|
|
"time"
|
|
"unsafe"
|
|
|
|
"golang.org/x/sys/unix"
|
|
)
|
|
|
|
// flock acquires an advisory lock on a file descriptor.
|
|
func flock(db *DB, mode os.FileMode, exclusive bool, timeout time.Duration) error {
|
|
var t time.Time
|
|
for {
|
|
// If we're beyond our timeout then return an error.
|
|
// This can only occur after we've attempted a flock once.
|
|
if t.IsZero() {
|
|
t = time.Now()
|
|
} else if timeout > 0 && time.Since(t) > timeout {
|
|
return ErrTimeout
|
|
}
|
|
var lock syscall.Flock_t
|
|
lock.Start = 0
|
|
lock.Len = 0
|
|
lock.Pid = 0
|
|
lock.Whence = 0
|
|
lock.Pid = 0
|
|
if exclusive {
|
|
lock.Type = syscall.F_WRLCK
|
|
} else {
|
|
lock.Type = syscall.F_RDLCK
|
|
}
|
|
err := syscall.FcntlFlock(db.file.Fd(), syscall.F_SETLK, &lock)
|
|
if err == nil {
|
|
return nil
|
|
} else if err != syscall.EAGAIN {
|
|
return err
|
|
}
|
|
|
|
// Wait for a bit and try again.
|
|
time.Sleep(50 * time.Millisecond)
|
|
}
|
|
}
|
|
|
|
// funlock releases an advisory lock on a file descriptor.
|
|
func funlock(db *DB) error {
|
|
var lock syscall.Flock_t
|
|
lock.Start = 0
|
|
lock.Len = 0
|
|
lock.Type = syscall.F_UNLCK
|
|
lock.Whence = 0
|
|
return syscall.FcntlFlock(uintptr(db.file.Fd()), syscall.F_SETLK, &lock)
|
|
}
|
|
|
|
// mmap memory maps a DB's data file.
|
|
func mmap(db *DB, sz int) error {
|
|
// Map the data file to memory.
|
|
b, err := unix.Mmap(int(db.file.Fd()), 0, sz, syscall.PROT_READ, syscall.MAP_SHARED|db.MmapFlags)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
// Advise the kernel that the mmap is accessed randomly.
|
|
if err := unix.Madvise(b, syscall.MADV_RANDOM); err != nil {
|
|
return fmt.Errorf("madvise: %s", err)
|
|
}
|
|
|
|
// Save the original byte slice and convert to a byte array pointer.
|
|
db.dataref = b
|
|
db.data = (*[maxMapSize]byte)(unsafe.Pointer(&b[0]))
|
|
db.datasz = sz
|
|
return nil
|
|
}
|
|
|
|
// munmap unmaps a DB's data file from memory.
|
|
func munmap(db *DB) error {
|
|
// Ignore the unmap if we have no mapped data.
|
|
if db.dataref == nil {
|
|
return nil
|
|
}
|
|
|
|
// Unmap using the original byte slice.
|
|
err := unix.Munmap(db.dataref)
|
|
db.dataref = nil
|
|
db.data = nil
|
|
db.datasz = 0
|
|
return err
|
|
}
|