-
Notifications
You must be signed in to change notification settings - Fork 32
Expand file tree
/
Copy pathmmap_linux.go
More file actions
302 lines (271 loc) · 7.56 KB
/
mmap_linux.go
File metadata and controls
302 lines (271 loc) · 7.56 KB
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
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
//go:build linux
package file
import (
"encoding/binary"
"fmt"
"io"
"os"
"path/filepath"
"github.com/feichai0017/NoKV/utils/mmap"
"github.com/feichai0017/NoKV/vfs"
"github.com/pkg/errors"
)
// MmapFile represents an mmapd file and includes both the buffer to the data and the file descriptor.
type MmapFile struct {
Data []byte
File vfs.File // for file ops
fs vfs.FS
path string
fd uintptr
hasFD bool
}
// openMmapFileHandle maps an already-open file handle using the fd capability exposed by vfs.File.
func openMmapFileHandle(fs vfs.FS, file vfs.File, sz int, writable bool) (*MmapFile, error) {
fs = vfs.Ensure(fs)
filename := file.Name()
fd, ok := vfs.FileFD(file)
if !ok {
return nil, errors.Errorf("unable to mmap file without fd capability: %s", filename)
}
fi, err := file.Stat()
if err != nil {
return nil, errors.Wrapf(err, "cannot stat file: %s", filename)
}
var rerr error
fileSize := fi.Size()
if sz > 0 && fileSize == 0 {
// If file is empty, truncate it to sz.
if err := file.Truncate(int64(sz)); err != nil {
return nil, errors.Wrapf(err, "error while truncation")
}
fileSize = int64(sz)
}
// fmt.Printf("Mmaping file: %s with writable: %v filesize: %d\n", fd.Name(), writable, fileSize)
buf, err := mmap.Mmap(fd, writable, fileSize) // Mmap up to file size.
if err != nil {
return nil, errors.Wrapf(err, "while mmapping %s with size: %d", file.Name(), fileSize)
}
if fileSize == 0 {
dir, _ := filepath.Split(filename)
go func() {
_ = vfs.SyncDir(fs, dir)
}()
}
return &MmapFile{
Data: buf,
File: file,
fs: fs,
path: filename,
fd: fd,
hasFD: true,
}, rerr
}
func (m *MmapFile) fileName() string {
if m == nil {
return ""
}
if m.path != "" {
return m.path
}
if m.File != nil {
return m.File.Name()
}
return ""
}
// SetFileName updates the logical file path associated with this mmap handle.
func (m *MmapFile) SetFileName(name string) {
if m == nil || name == "" {
return
}
m.path = name
}
// OpenMmapFile opens an existing file or creates a new file. If the file is
// created, it would truncate the file to maxSz. In both cases, it would mmap
// the file to maxSz and returned it. In case the file is created, z.NewFile is
// returned.
func OpenMmapFile(fs vfs.FS, filename string, flag int, maxSz int) (*MmapFile, error) {
// fmt.Printf("opening file %s with flag: %v\n", filename, flag)
fs = vfs.Ensure(fs)
handle, err := fs.OpenFileHandle(filename, flag, 0666)
if err != nil {
return nil, errors.Wrapf(err, "unable to open: %s", filename)
}
writable := flag != os.O_RDONLY
// if the sst file layer has been opened, use its original size
if fileInfo, err := handle.Stat(); err == nil && fileInfo != nil && fileInfo.Size() > 0 {
maxSz = int(fileInfo.Size())
}
omf, err := openMmapFileHandle(fs, handle, maxSz, writable)
if err != nil {
_ = handle.Close()
return nil, err
}
return omf, nil
}
type mmapReader struct {
Data []byte
offset int
}
func (mr *mmapReader) Read(buf []byte) (int, error) {
if mr.offset > len(mr.Data) {
return 0, io.EOF
}
n := copy(buf, mr.Data[mr.offset:])
mr.offset += n
if n < len(buf) {
return n, io.EOF
}
return n, nil
}
func (m *MmapFile) NewReader(offset int) io.Reader {
return &mmapReader{
Data: m.Data,
offset: offset,
}
}
// Bytes returns data starting from offset off of size sz. If there's not enough data, it would
// return nil slice and io.EOF.
func (m *MmapFile) Bytes(off, sz int) ([]byte, error) {
if m == nil || m.Data == nil || sz < 0 || off < 0 {
return nil, io.EOF
}
if len(m.Data[off:]) < sz {
return nil, io.EOF
}
return m.Data[off : off+sz], nil
}
// View returns a direct slice over the mmap'd region without copying.
// Use this only when the caller owns the file lifetime (e.g., building SSTables).
func (m *MmapFile) View(off, sz int) ([]byte, error) {
if m == nil || m.Data == nil || sz < 0 || off < 0 {
return nil, io.EOF
}
if len(m.Data[off:]) < sz {
return nil, io.EOF
}
return m.Data[off : off+sz], nil
}
// Slice returns the slice at the given offset.
func (m *MmapFile) Slice(offset int) []byte {
sz := binary.BigEndian.Uint32(m.Data[offset:])
start := offset + 4
next := start + int(sz)
if next > len(m.Data) {
return []byte{}
}
res := m.Data[start:next]
return res
}
// AllocateSlice allocates a slice of the given size at the given offset.
func (m *MmapFile) AllocateSlice(sz, offset int) ([]byte, int, error) {
start := offset + 4
// If the file is too small, double its size or increase it by 1GB, whichever is smaller.
if start+sz > len(m.Data) {
const oneGB = 1 << 30
growBy := max(min(len(m.Data), oneGB), sz+4)
if err := m.Truncate(int64(len(m.Data) + growBy)); err != nil {
return nil, 0, err
}
}
binary.BigEndian.PutUint32(m.Data[offset:], uint32(sz))
return m.Data[start : start+sz], start + sz, nil
}
const oneGB = 1 << 30
// AppendBuffer appends data into the mmap region, growing the mapping if needed.
func (m *MmapFile) AppendBuffer(offset uint32, buf []byte) error {
size := len(m.Data)
needSize := len(buf)
end := int(offset) + needSize
if end > size {
growBy := max(min(size, oneGB), needSize)
newSize := max(size+growBy, end)
if err := m.Truncate(int64(newSize)); err != nil {
return err
}
}
dLen := copy(m.Data[offset:end], buf)
if dLen != needSize {
return errors.Errorf("dLen != needSize AppendBuffer failed")
}
return nil
}
func (m *MmapFile) Sync() error {
if m == nil {
return nil
}
return mmap.Msync(m.Data)
}
// SyncAsync flushes dirty pages asynchronously.
func (m *MmapFile) SyncAsync() error {
if m == nil {
return nil
}
return mmap.MsyncAsync(m.Data)
}
// SyncAsyncRange flushes a range asynchronously.
func (m *MmapFile) SyncAsyncRange(off, n int64) error {
if m == nil {
return nil
}
return mmap.MsyncAsyncRange(m.Data, off, n)
}
// Remap remaps the file with the requested writability.
func (m *MmapFile) Remap(writable bool) error {
if m == nil || !m.hasFD || m.File == nil {
return fmt.Errorf("mmap file remap: nil receiver")
}
if err := mmap.Munmap(m.Data); err != nil {
return err
}
fi, err := m.File.Stat()
if err != nil {
return err
}
buf, err := mmap.Mmap(m.fd, writable, fi.Size())
if err != nil {
return err
}
m.Data = buf
return nil
}
func (m *MmapFile) Delete() error {
if m == nil || !m.hasFD || m.File == nil {
return nil
}
if err := mmap.Munmap(m.Data); err != nil {
return fmt.Errorf("while munmap file: %s, error: %v", m.fileName(), err)
}
m.Data = nil
if err := m.File.Truncate(0); err != nil {
return fmt.Errorf("while truncate file: %s, error: %v", m.fileName(), err)
}
if err := m.File.Close(); err != nil {
return fmt.Errorf("while close file: %s, error: %v", m.fileName(), err)
}
return vfs.Ensure(m.fs).Remove(m.fileName())
}
// Close would close the file. It would also truncate the file if maxSz >= 0.
func (m *MmapFile) Close() error {
if m == nil || !m.hasFD || m.File == nil {
return nil
}
if err := m.Sync(); err != nil {
return fmt.Errorf("while sync file: %s, error: %v", m.fileName(), err)
}
if err := mmap.Munmap(m.Data); err != nil {
return fmt.Errorf("while munmap file: %s, error: %v", m.fileName(), err)
}
return m.File.Close()
}
// Truncate resizes and remaps the file to the provided size.
func (m *MmapFile) Truncate(maxSz int64) error {
if maxSz <= 0 {
return fmt.Errorf("invalid truncate size: %d for file: %s", maxSz, m.fileName())
}
if err := m.File.Truncate(maxSz); err != nil {
return fmt.Errorf("while truncate file: %s, error: %v", m.fileName(), err)
}
var err error
m.Data, err = mmap.Mremap(m.Data, int(maxSz)) // Mmap up to max size.
return err
}