-
Notifications
You must be signed in to change notification settings - Fork 0
/
mmap.go
79 lines (64 loc) · 2.07 KB
/
mmap.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
77
78
79
package gomap
import (
"fmt"
"log"
"os"
"golang.org/x/sys/unix"
"github.com/edsrzf/mmap-go"
"github.com/go-errors/errors"
)
func (h *Hashmap) openMmapHash(N uint64) (mmap.MMap, *os.File, error) {
bytes := NtoBytesHashmap(N)
h.createDirectory()
filename := h.Folder + "/hashkeys-" + fmt.Sprint(N)
if !doesFileExist(filename) {
h.createFile(filename, bytes)
}
mappedData, file, err := h.openMmapFile(filename)
if err != nil {
return nil, nil, err
}
//h.mlock(mappedData) // todo see if matters
return mappedData, file, err
}
func (h *Hashmap) openMmapFile(filename string) (mmap.MMap, *os.File, error) {
file, err := os.OpenFile(filename, os.O_RDWR, 0)
if err != nil {
return nil, nil, fmt.Errorf("failed to open file %s: %w", filename, err)
}
fi, err := file.Stat()
if err != nil {
return nil, nil, fmt.Errorf("failed to stat file %s: %w", filename, err)
}
// Advise the kernel that we intend to access the file randomly
// and we want to avoid page cache pollution.
if err := unix.Fadvise(int(file.Fd()), 0, int64(fi.Size()), unix.FADV_RANDOM|unix.FADV_DONTNEED); err != nil {
file.Close()
return nil, nil, fmt.Errorf("failed to advise kernel for file %s: %w", filename, err)
}
// mmap the whole file into memory with read-write permissions.
// This avoids copy-on-write overhead and ensures that the file is never modified.
data, err := unix.Mmap(int(file.Fd()), 0, int(fi.Size()), unix.PROT_READ|unix.PROT_WRITE, unix.MAP_SHARED)
if err != nil {
file.Close()
return nil, nil, fmt.Errorf("failed to mmap file %s: %w", filename, err)
}
// Advise the kernel to keep the whole file in memory and avoid swapping.
if err := unix.Madvise(data, unix.MADV_WILLNEED); err != nil {
unix.Munmap(data)
file.Close()
return nil, nil, fmt.Errorf("failed to advise kernel for file %s: %w", filename, err)
}
return data, file, nil
}
func (h *Hashmap) createFile(filename string, bytes int64) {
f, err := os.Create(filename)
if err != nil {
log.Fatal("2", errors.Wrap(err, 1))
}
f.Seek(bytes-1, 0)
f.Write([]byte("\x00"))
f.Seek(0, 0)
f.Sync()
f.Close()
}