forked from attic-labs/noms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
mmap_table_reader.go
107 lines (87 loc) · 2.24 KB
/
mmap_table_reader.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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
// Copyright 2016 Attic Labs, Inc. All rights reserved.
// Licensed under the Apache License, version 2.0:
// http://www.apache.org/licenses/LICENSE-2.0
package nbs
import (
"io"
"math"
"os"
"path/filepath"
"strconv"
"time"
"golang.org/x/sys/unix"
"github.com/attic-labs/noms/go/d"
)
type mmapTableReader struct {
tableReader
fc *fdCache
h addr
}
const (
fileBlockSize = 1 << 12
)
var (
pageSize = int64(os.Getpagesize())
maxInt = int64(math.MaxInt64)
)
func init() {
if strconv.IntSize == 32 {
maxInt = math.MaxInt32
}
}
func newMmapTableReader(dir string, h addr, chunkCount uint32, indexCache *indexCache, fc *fdCache) chunkSource {
path := filepath.Join(dir, h.String())
var index tableIndex
found := false
if indexCache != nil {
indexCache.lockEntry(h)
defer indexCache.unlockEntry(h)
index, found = indexCache.get(h)
}
if !found {
f, err := fc.RefFile(path)
d.PanicIfError(err)
defer fc.UnrefFile(path)
fi, err := f.Stat()
d.PanicIfError(err)
d.PanicIfTrue(fi.Size() < 0)
// index. Mmap won't take an offset that's not page-aligned, so find the nearest page boundary preceding the index.
indexOffset := fi.Size() - int64(footerSize) - int64(indexSize(chunkCount))
aligned := indexOffset / pageSize * pageSize // Thanks, integer arithmetic!
d.PanicIfTrue(fi.Size()-aligned > maxInt)
buff, err := unix.Mmap(int(f.Fd()), aligned, int(fi.Size()-aligned), unix.PROT_READ, unix.MAP_SHARED)
d.PanicIfError(err)
index = parseTableIndex(buff[indexOffset-aligned:])
if indexCache != nil {
indexCache.put(h, index)
}
err = unix.Munmap(buff)
d.PanicIfError(err)
}
d.PanicIfFalse(chunkCount == index.chunkCount)
return &mmapTableReader{
newTableReader(index, &cacheReaderAt{path, fc}, fileBlockSize),
fc,
h,
}
}
func (mmtr *mmapTableReader) hash() addr {
return mmtr.h
}
type cacheReaderAt struct {
path string
fc *fdCache
}
func (cra *cacheReaderAt) ReadAtWithStats(p []byte, off int64, stats *Stats) (n int, err error) {
var r io.ReaderAt
t1 := time.Now()
if r, err = cra.fc.RefFile(cra.path); err != nil {
return
}
defer func() {
stats.FileBytesPerRead.Sample(uint64(len(p)))
stats.FileReadLatency.SampleTimeSince(t1)
}()
defer cra.fc.UnrefFile(cra.path)
return r.ReadAt(p, off)
}