Debian Codegraph @

vendor/github.com/coreos/bbolt/bolt_unix.go

raw
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 if timeout != 0 {
17 t = time.Now()
18 }
19 fd := db.file.Fd()
20 flag := syscall.LOCK_NB
21 if exclusive {
22 flag |= syscall.LOCK_EX
23 } else {
24 flag |= syscall.LOCK_SH
25 }
26 for {
27 // Attempt to obtain an exclusive lock.
28 err := syscall.Flock(int(fd), flag)
29 if err == nil {
30 return nil
31 } else if err != syscall.EWOULDBLOCK {
32 return err
33 }
34
35 // If we timed out then return an error.
36 if timeout != 0 && time.Since(t) > timeout-flockRetryTimeout {
37 return ErrTimeout
38 }
39
40 // Wait for a bit and try again.
41 time.Sleep(flockRetryTimeout)
42 }
43 }
44
45 // funlock releases an advisory lock on a file descriptor.
46 func funlock(db *DB) error {
47 return syscall.Flock(int(db.file.Fd()), syscall.LOCK_UN)
48 }
49
50 // mmap memory maps a DB's data file.
51 func mmap(db *DB, sz int) error {
52 // Map the data file to memory.
53 b, err := syscall.Mmap(int(db.file.Fd()), 0, sz, syscall.PROT_READ, syscall.MAP_SHARED|db.MmapFlags)
54 if err != nil {
55 return err
56 }
57
58 // Advise the kernel that the mmap is accessed randomly.
59 if err := madvise(b, syscall.MADV_RANDOM); err != nil {
60 return fmt.Errorf("madvise: %s", err)
61 }
62
63 // Save the original byte slice and convert to a byte array pointer.
64 db.dataref = b
65 db.data = (*[maxMapSize]byte)(unsafe.Pointer(&b[0]))
66 db.datasz = sz
67 return nil
68 }
69
70 // munmap unmaps a DB's data file from memory.
71 func munmap(db *DB) error {
72 // Ignore the unmap if we have no mapped data.
73 if db.dataref == nil {
74 return nil
75 }
76
77 // Unmap using the original byte slice.
78 err := syscall.Munmap(db.dataref)
79 db.dataref = nil
80 db.data = nil
81 db.datasz = 0
82 return err
83 }
84
85 // NOTE: This function is copied from stdlib because it is not available on darwin.
86 func madvise(b []byte, advice int) (err error) {
87 _, _, e1 := syscall.Syscall(syscall.SYS_MADVISE, uintptr(unsafe.Pointer(&b[0])), uintptr(len(b)), uintptr(advice))
88 if e1 != 0 {
89 err = e1
90 }
91 return
92 }