mmap_unix.go 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. // +build !windows,!darwin,!plan9,!linux
  2. /*
  3. * Copyright 2019 Dgraph Labs, Inc. and Contributors
  4. *
  5. * Licensed under the Apache License, Version 2.0 (the "License");
  6. * you may not use this file except in compliance with the License.
  7. * You may obtain a copy of the License at
  8. *
  9. * http://www.apache.org/licenses/LICENSE-2.0
  10. *
  11. * Unless required by applicable law or agreed to in writing, software
  12. * distributed under the License is distributed on an "AS IS" BASIS,
  13. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. * See the License for the specific language governing permissions and
  15. * limitations under the License.
  16. */
  17. package z
  18. import (
  19. "os"
  20. "golang.org/x/sys/unix"
  21. )
  22. // Mmap uses the mmap system call to memory-map a file. If writable is true,
  23. // memory protection of the pages is set so that they may be written to as well.
  24. func mmap(fd *os.File, writable bool, size int64) ([]byte, error) {
  25. mtype := unix.PROT_READ
  26. if writable {
  27. mtype |= unix.PROT_WRITE
  28. }
  29. return unix.Mmap(int(fd.Fd()), 0, int(size), mtype, unix.MAP_SHARED)
  30. }
  31. // Munmap unmaps a previously mapped slice.
  32. func munmap(b []byte) error {
  33. return unix.Munmap(b)
  34. }
  35. // Madvise uses the madvise system call to give advise about the use of memory
  36. // when using a slice that is memory-mapped to a file. Set the readahead flag to
  37. // false if page references are expected in random order.
  38. func madvise(b []byte, readahead bool) error {
  39. flags := unix.MADV_NORMAL
  40. if !readahead {
  41. flags = unix.MADV_RANDOM
  42. }
  43. return unix.Madvise(b, flags)
  44. }
  45. func msync(b []byte) error {
  46. return unix.Msync(b, unix.MS_SYNC)
  47. }