| 1 | // Copyright 2011 Evan Shaw. All rights reserved. |
| 2 | // Use of this source code is governed by a BSD-style |
| 3 | // license that can be found in the LICENSE-MMAP-GO file. |
| 4 | |
| 5 | //go:build unix |
| 6 | |
| 7 | // Modifications (c) 2017 The Memory Authors. |
| 8 | |
| 9 | package memory // import "modernc.org/memory" |
| 10 | |
| 11 | import ( |
| 12 | "golang.org/x/sys/unix" |
| 13 | "os" |
| 14 | "unsafe" |
| 15 | ) |
| 16 | |
| 17 | const pageSizeLog = 16 |
| 18 | |
| 19 | // canCarve reports that unmap can release any page-aligned sub-range |
| 20 | // of a mapping, so a large mapping can be carved into independently |
| 21 | // releasable pageSize regions. |
| 22 | const canCarve = true |
| 23 | |
| 24 | var ( |
| 25 | osPageMask = osPageSize - 1 |
| 26 | osPageSize = os.Getpagesize() |
| 27 | |
| 28 | // mmapGranularity is the granularity mmap in this file actually maps |
| 29 | // at: exactly what was asked, rounded to OS pages. |
| 30 | mmapGranularity = osPageSize |
| 31 | ) |
| 32 | |
| 33 | func unmap(addr uintptr, size int) error { |
| 34 | return unix.MunmapPtr(unsafe.Pointer(addr), uintptr(size)) |
| 35 | } |
| 36 | |
| 37 | // pageSize aligned. |
| 38 | func mmap(size int) (uintptr, int, error) { |
| 39 | size = roundup(size, osPageSize) |
| 40 | // Ask for more so we can align the result at a pageSize boundary |
| 41 | n := size + pageSize |
| 42 | up, err := unix.MmapPtr(-1, 0, nil, uintptr(n), unix.PROT_READ|unix.PROT_WRITE, unix.MAP_PRIVATE|unix.MAP_ANON) |
| 43 | if err != nil { |
| 44 | return 0, 0, err |
| 45 | } |
| 46 | |
| 47 | p := uintptr(up) |
| 48 | if p&uintptr(osPageMask) != 0 { |
| 49 | panic("internal error") |
| 50 | } |
| 51 | |
| 52 | mod := int(p) & pageMask |
| 53 | if mod != 0 { // Return the extra part before pageSize aligned block |
| 54 | m := pageSize - mod |
| 55 | if err := unmap(p, m); err != nil { |
| 56 | unmap(p, n) // Do not leak the first mmap |
| 57 | return 0, 0, err |
| 58 | } |
| 59 | |
| 60 | n -= m |
| 61 | p += uintptr(m) |
| 62 | } |
| 63 | |
| 64 | if p&uintptr(pageMask) != 0 { |
| 65 | panic("internal error") |
| 66 | } |
| 67 | |
| 68 | if n > size { // Return the extra part after pageSize aligned block |
| 69 | if err := unmap(p+uintptr(size), n-size); err != nil { |
| 70 | // Do not error when the kernel rejects the extra part after, just return the |
| 71 | // unexpectedly enlarged size. |
| 72 | // |
| 73 | // Fixes the bigsort.test failures on linux/s390x, see: https://gitlab.com/cznic/sqlite/-/issues/207 |
| 74 | size = n |
| 75 | } |
| 76 | } |
| 77 | |
| 78 | return p, size, nil |
| 79 | } |