mmap_unix.go 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. //go:build !windows && !darwin && !plan9 && !linux && !wasip1 && !js
  2. // +build !windows,!darwin,!plan9,!linux,!wasip1,!js
  3. /*
  4. * Copyright 2019 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. package z
  19. import (
  20. "os"
  21. "golang.org/x/sys/unix"
  22. )
  23. // Mmap uses the mmap system call to memory-map a file. If writable is true,
  24. // memory protection of the pages is set so that they may be written to as well.
  25. func mmap(fd *os.File, writable bool, size int64) ([]byte, error) {
  26. mtype := unix.PROT_READ
  27. if writable {
  28. mtype |= unix.PROT_WRITE
  29. }
  30. return unix.Mmap(int(fd.Fd()), 0, int(size), mtype, unix.MAP_SHARED)
  31. }
  32. // Munmap unmaps a previously mapped slice.
  33. func munmap(b []byte) error {
  34. return unix.Munmap(b)
  35. }
  36. // Madvise uses the madvise system call to give advise about the use of memory
  37. // when using a slice that is memory-mapped to a file. Set the readahead flag to
  38. // false if page references are expected in random order.
  39. func madvise(b []byte, readahead bool) error {
  40. flags := unix.MADV_NORMAL
  41. if !readahead {
  42. flags = unix.MADV_RANDOM
  43. }
  44. return unix.Madvise(b, flags)
  45. }
  46. func msync(b []byte) error {
  47. return unix.Msync(b, unix.MS_SYNC)
  48. }