Debian Codegraph @

bolt_unix.go

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