github.com/zuoyebang/bitalosdb@v1.1.1-0.20240516111551-79a8c4d8ce20/bitree/bdb/bdb_unix.go (about) 1 // Copyright 2021 The Bitalosdb author(hustxrb@163.com) and other contributors. 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 //go:build !windows && !plan9 && !solaris && !aix 16 17 package bdb 18 19 import ( 20 "syscall" 21 "time" 22 "unsafe" 23 24 "github.com/cockroachdb/errors" 25 "golang.org/x/sys/unix" 26 ) 27 28 func flock(db *DB, exclusive bool, timeout time.Duration) error { 29 var t time.Time 30 if timeout != 0 { 31 t = time.Now() 32 } 33 fd := db.file.Fd() 34 flag := syscall.LOCK_NB 35 if exclusive { 36 flag |= syscall.LOCK_EX 37 } else { 38 flag |= syscall.LOCK_SH 39 } 40 for { 41 err := syscall.Flock(int(fd), flag) 42 if err == nil { 43 return nil 44 } else if err != syscall.EWOULDBLOCK { 45 return err 46 } 47 48 if timeout != 0 && time.Since(t) > timeout-flockRetryTimeout { 49 return ErrTimeout 50 } 51 52 time.Sleep(flockRetryTimeout) 53 } 54 } 55 56 func funlock(db *DB) error { 57 return syscall.Flock(int(db.file.Fd()), syscall.LOCK_UN) 58 } 59 60 func mmap(db *DB, sz int) error { 61 b, err := unix.Mmap(int(db.file.Fd()), 0, sz, syscall.PROT_READ, syscall.MAP_SHARED|db.MmapFlags) 62 if err != nil { 63 return err 64 } 65 66 err = unix.Madvise(b, syscall.MADV_RANDOM) 67 if err != nil && err != syscall.ENOSYS { 68 return errors.Wrap(err, "madvise err") 69 } 70 71 db.dataref = b 72 db.data = (*[maxMapSize]byte)(unsafe.Pointer(&b[0])) 73 db.datasz = sz 74 return nil 75 } 76 77 func munmap(db *DB) error { 78 if db.dataref == nil { 79 return nil 80 } 81 82 err := unix.Munmap(db.dataref) 83 db.dataref = nil 84 db.data = nil 85 db.datasz = 0 86 return err 87 }