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