github.com/fiatjaf/generic-ristretto@v0.0.1/z/mmap_linux.go (about) 1 /* 2 * Copyright 2020 Dgraph Labs, Inc. and Contributors 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 package z 18 19 import ( 20 "os" 21 "unsafe" 22 23 "golang.org/x/sys/unix" 24 ) 25 26 // mmap uses the mmap system call to memory-map a file. If writable is true, 27 // memory protection of the pages is set so that they may be written to as well. 28 func mmap(fd *os.File, writable bool, size int64) ([]byte, error) { 29 mtype := unix.PROT_READ 30 if writable { 31 mtype |= unix.PROT_WRITE 32 } 33 return unix.Mmap(int(fd.Fd()), 0, int(size), mtype, unix.MAP_SHARED) 34 } 35 36 // munmap unmaps a previously mapped slice. 37 // 38 // unix.Munmap maintains an internal list of mmapped addresses, and only calls munmap 39 // if the address is present in that list. If we use mremap, this list is not updated. 40 // To bypass this, we call munmap ourselves. 41 func munmap(data []byte) error { 42 if len(data) == 0 || len(data) != cap(data) { 43 return unix.EINVAL 44 } 45 _, _, errno := unix.Syscall( 46 unix.SYS_MUNMAP, 47 uintptr(unsafe.Pointer(&data[0])), 48 uintptr(len(data)), 49 0, 50 ) 51 if errno != 0 { 52 return errno 53 } 54 return nil 55 } 56 57 // madvise uses the madvise system call to give advise about the use of memory 58 // when using a slice that is memory-mapped to a file. Set the readahead flag to 59 // false if page references are expected in random order. 60 func madvise(b []byte, readahead bool) error { 61 flags := unix.MADV_NORMAL 62 if !readahead { 63 flags = unix.MADV_RANDOM 64 } 65 return unix.Madvise(b, flags) 66 } 67 68 // msync writes any modified data to persistent storage. 69 func msync(b []byte) error { 70 return unix.Msync(b, unix.MS_SYNC) 71 }