github.com/coocood/badger@v1.5.1-0.20200528065104-c02ac3616d04/y/mmap_unix.go (about) 1 // +build !windows 2 3 /* 4 * Copyright 2017 Dgraph Labs, Inc. and Contributors 5 * 6 * Licensed under the Apache License, Version 2.0 (the "License"); 7 * you may not use this file except in compliance with the License. 8 * You may obtain a copy of the License at 9 * 10 * http://www.apache.org/licenses/LICENSE-2.0 11 * 12 * Unless required by applicable law or agreed to in writing, software 13 * distributed under the License is distributed on an "AS IS" BASIS, 14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 * See the License for the specific language governing permissions and 16 * limitations under the License. 17 */ 18 19 package y 20 21 import ( 22 "os" 23 "syscall" 24 "unsafe" 25 26 "golang.org/x/sys/unix" 27 ) 28 29 // Mmap uses the mmap system call to memory-map a file. If writable is true, 30 // memory protection of the pages is set so that they may be written to as well. 31 func Mmap(fd *os.File, writable bool, size int64) ([]byte, error) { 32 mtype := unix.PROT_READ 33 if writable { 34 mtype |= unix.PROT_WRITE 35 } 36 return unix.Mmap(int(fd.Fd()), 0, int(size), mtype, unix.MAP_SHARED) 37 } 38 39 // Munmap unmaps a previously mapped slice. 40 func Munmap(b []byte) error { 41 return unix.Munmap(b) 42 } 43 44 // Madvise uses the madvise system call to give advise about the use of memory 45 // when using a slice that is memory-mapped to a file. Set the readahead flag to 46 // false if page references are expected in random order. 47 func Madvise(b []byte, readahead bool) error { 48 flags := unix.MADV_NORMAL 49 if !readahead { 50 flags = unix.MADV_RANDOM 51 } 52 return madvise(b, flags) 53 } 54 55 // This is required because the unix package does not support the madvise system call on OS X. 56 func madvise(b []byte, advice int) (err error) { 57 _, _, e1 := syscall.Syscall(syscall.SYS_MADVISE, uintptr(unsafe.Pointer(&b[0])), 58 uintptr(len(b)), uintptr(advice)) 59 if e1 != 0 { 60 err = e1 61 } 62 return 63 }