forked from tobert/pcstat
/
mincore.go
76 lines (66 loc) · 2.43 KB
/
mincore.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
package pcstat
/*
* Copyright 2014 Albert P. Tobey <atobey@datastax.com> @AlTobey
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import (
"fmt"
"os"
"unsafe"
"golang.org/x/sys/unix"
)
// mmap the given file, get the mincore vector, then
// return it as an []bool
func FileMincore(f *os.File, size int64) ([]bool, error) {
//skip could not mmap error when the file size is 0
if int(size) == 0 {
return nil, nil
}
// mmap is a []byte
mmap, err := unix.Mmap(int(f.Fd()), 0, int(size), unix.PROT_NONE, unix.MAP_SHARED)
if err != nil {
return nil, fmt.Errorf("could not mmap: %v", err)
}
// TODO: check for MAP_FAILED which is ((void *) -1)
// but maybe unnecessary since it looks like errno is always set when MAP_FAILED
// one byte per page, only LSB is used, remainder is reserved and clear
vecsz := (size + int64(os.Getpagesize()) - 1) / int64(os.Getpagesize())
vec := make([]byte, vecsz)
// get all of the arguments to the mincore syscall converted to uintptr
mmap_ptr := uintptr(unsafe.Pointer(&mmap[0]))
size_ptr := uintptr(size)
vec_ptr := uintptr(unsafe.Pointer(&vec[0]))
// use Go's ASM to submit directly to the kernel, no C wrapper needed
// mincore(2): int mincore(void *addr, size_t length, unsigned char *vec);
// 0 on success, takes the pointer to the mmap, a size, which is the
// size that came from f.Stat(), and the vector, which is a pointer
// to the memory behind an []byte
// this writes a snapshot of the data into vec which a list of 8-bit flags
// with the LSB set if the page in that position is currently in VFS cache
ret, _, err := unix.Syscall(unix.SYS_MINCORE, mmap_ptr, size_ptr, vec_ptr)
if ret != 0 {
return nil, fmt.Errorf("syscall SYS_MINCORE failed: %v", err)
}
defer unix.Munmap(mmap)
mc := make([]bool, vecsz)
// there is no bitshift only bool
for i, b := range vec {
if b%2 == 1 {
mc[i] = true
} else {
mc[i] = false
}
}
return mc, nil
}