-
Notifications
You must be signed in to change notification settings - Fork 2
/
nbd.go
363 lines (307 loc) · 7.84 KB
/
nbd.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
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
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
package nbd
import (
"bufio"
"context"
"errors"
"fmt"
"io"
"log"
"math/bits"
"os"
"sync"
"golang.org/x/sync/errgroup"
"golang.org/x/sys/unix"
)
const (
DefaultBlockSize = 512
DefaultConcurrentOps = 1
// Maximum number of concurrent operations
// (block device queue depth: https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/tree/drivers/block/nbd.c?h=v5.15#n1692)
MaxConcurrentOps = 128
readBufferSize = 1024 * 1024
)
var (
ErrUnsupported = errors.New("nbd: unsupported operation")
)
type BlockDevice interface {
io.ReaderAt
io.WriterAt
}
type BlockDeviceTrimer interface {
Trim(off int64, length uint32) error
}
type BlockDeviceFlusher interface {
Flush() error
}
type BlockDeviceOptions struct {
// BlockSize is the size of each block on the block device, in bytes.
// Must be between 512 and the system page size (usually 4096 on x86).
// If 0, the default value of DefaultBlockSize will be used.
BlockSize int
// ConcurrentOps is the number of operations (read, write, trim, flush)
// which can be performed concurrently. Must be between 1 and 128.
// If 0, the default value of DefaultConcurrentOps will be used.
ConcurrentOps int
// Readonly should be set to true if the block device is read-only.
Readonly bool
}
type NbdServer struct {
opts BlockDeviceOptions
size int64
devFd int
sockfd int
block BlockDevice
// Netlink stuff
nlConn *NetlinkConn
index int
doneCh chan bool
}
func validateOptions(opts *BlockDeviceOptions, size int64) error {
pageSize := os.Getpagesize()
if opts.BlockSize == 0 {
opts.BlockSize = DefaultBlockSize
} else if opts.BlockSize < 512 || opts.BlockSize > pageSize {
return fmt.Errorf("nbd: BlockSize must be between 512 and %d", pageSize)
} else if bits.OnesCount(uint(opts.BlockSize)) != 1 {
return errors.New("nbd: BlockSize must be a power-of-2")
}
if size <= 0 || size%int64(opts.BlockSize) != 0 {
return errors.New("nbd: size must be a positive multiple of BlockSize")
}
if opts.ConcurrentOps == 0 {
opts.ConcurrentOps = DefaultConcurrentOps
} else if opts.ConcurrentOps < 0 || opts.ConcurrentOps > MaxConcurrentOps {
return fmt.Errorf("nbd: ConcurrentOps must be between 1 and %d", MaxConcurrentOps)
}
return nil
}
func NewServer(dev string, block BlockDevice, size int64, opts BlockDeviceOptions) (*NbdServer, error) {
devFd, err := unix.Open(dev, unix.O_RDWR, 0)
if err != nil {
return nil, err
}
return NewServerFromFd(devFd, block, size, opts)
}
func NewServerFromFd(devFd int, block BlockDevice, size int64, opts BlockDeviceOptions) (*NbdServer, error) {
err := validateOptions(&opts, size)
if err != nil {
return nil, err
}
return &NbdServer{
opts: opts,
size: size,
devFd: devFd,
block: block,
doneCh: make(chan bool),
}, nil
}
func NewServerWithNetlink(index int, block BlockDevice, size int64, opts BlockDeviceOptions) (*NbdServer, error) {
if index < 0 {
return nil, errors.New("nbd: index must be non-negative")
}
err := validateOptions(&opts, size)
if err != nil {
return nil, err
}
nl, err := NewNetlinkConn(index)
if err != nil {
return nil, err
}
return &NbdServer{
opts: opts,
size: size,
block: block,
nlConn: nl,
index: index,
doneCh: make(chan bool),
}, nil
}
func (s *NbdServer) runNetlink(f *os.File, fd int) error {
s.nlConn.SetFd(fd)
s.nlConn.SetSize(uint64(s.size))
s.nlConn.SetBlockSize(uint64(s.opts.BlockSize))
if s.opts.Readonly {
s.nlConn.SetReadonly(true)
}
if _, ok := s.block.(BlockDeviceFlusher); ok {
s.nlConn.SetSupportsFlush(true)
}
if _, ok := s.block.(BlockDeviceTrimer); ok {
s.nlConn.SetSupportsTrim(true)
}
err := s.nlConn.Connect()
if err != nil {
f.Close()
log.Println("Error connecting to NBD: ", err)
return err
}
go s.do(f)
<-s.doneCh
return nil
}
func (s *NbdServer) Run() error {
fds, err := unix.Socketpair(unix.AF_UNIX, unix.SOCK_STREAM, 0)
if err != nil {
log.Println("Error creating socket pair: ", err)
return err
}
f := os.NewFile(uintptr(fds[1]), "nbd-sock")
if s.nlConn != nil {
return s.runNetlink(f, fds[0])
}
_, _, errno := unix.Syscall(unix.SYS_IOCTL, uintptr(s.devFd), nbdSetSock, uintptr(fds[0]))
if errno != 0 {
log.Println("Error setting NBD socket:", errno)
return errno
}
_, _, errno = unix.Syscall(unix.SYS_IOCTL, uintptr(s.devFd), nbdSetBlkSize, uintptr(s.opts.BlockSize))
if errno != 0 {
log.Println("Error setting NBD block size:", errno)
return errno
}
sizeBlocks := s.size / int64(s.opts.BlockSize)
if int64(uintptr(sizeBlocks)) != sizeBlocks {
return fmt.Errorf("File size %d too big for arch, bs=%d, blocks=%d", s.size, s.opts.BlockSize, sizeBlocks)
}
_, _, errno = unix.Syscall(unix.SYS_IOCTL, uintptr(s.devFd), nbdSetSizeBlocks, uintptr(sizeBlocks))
if errno != 0 {
log.Println("Error setting NBD size blocks:", errno)
return errno
}
var flags uint16
if s.opts.Readonly {
flags |= nbdFlagHasFlags | nbdFlagReadOnly
}
if _, ok := s.block.(BlockDeviceFlusher); ok {
flags |= nbdFlagHasFlags | nbdFlagSendFlush
}
if _, ok := s.block.(BlockDeviceTrimer); ok {
flags |= nbdFlagHasFlags | nbdFlagSendTrim
}
if flags != 0 {
_, _, errno = unix.Syscall(unix.SYS_IOCTL, uintptr(s.devFd), nbdSetFlags, uintptr(flags))
if errno != 0 {
log.Println("Error setting NBD flags:", errno)
return errno
}
}
go s.do(f)
_, _, errno = unix.Syscall(unix.SYS_IOCTL, uintptr(s.devFd), nbdDoIt, 0)
if errno != 0 {
return errno
}
return nil
}
func (s *NbdServer) Disconnect() error {
if s.nlConn != nil {
return s.nlConn.Disconnect()
}
_, _, errno := unix.Syscall(unix.SYS_IOCTL, uintptr(s.devFd), nbdDisconnect, 0)
if errno != 0 {
return errno
}
return nil
}
var (
reqPool RequestPool
replyPool ReplyPool
)
func (s *NbdServer) doRequest(req *Request) *Reply {
writeBufSize := 0
if req.cmd == nbdCmdRead {
writeBufSize = int(req.length)
}
reply := replyPool.Get(req.handle, writeBufSize)
var err error
switch req.cmd {
case nbdCmdRead:
var n int
n, err = s.block.ReadAt(reply.Buffer(), int64(req.offset))
if err == io.EOF && n == int(req.length) {
// io.ReaderAt is allowed to return EOF on a complete read, which should
// not be treated an an error.
err = nil
}
case nbdCmdWrite:
_, err = s.block.WriteAt(req.Buffer(), int64(req.offset))
case nbdCmdFlush:
err = s.block.(BlockDeviceFlusher).Flush()
case nbdCmdTrim:
err = s.block.(BlockDeviceTrimer).Trim(int64(req.offset), req.length)
case nbdCmdCache:
fallthrough
case nbdCmdWriteZeroes:
fallthrough
default:
log.Println("Unsupported operation", req.cmd)
err = ErrUnsupported
}
if err != nil {
log.Printf("NBD %v error: %v", req, err)
reply.SetError(nbdEio)
}
return reply
}
func (s *NbdServer) do(f *os.File) {
defer close(s.doneCh)
defer f.Close()
g, ctx := errgroup.WithContext(context.Background())
var replyLock sync.Mutex
workers := s.opts.ConcurrentOps
if workers <= 0 {
workers = DefaultConcurrentOps
}
reqCh := make(chan *Request, workers)
for i := 0; i < workers; i++ {
g.Go(func() error {
var req *Request
for {
select {
case <-ctx.Done():
return ctx.Err()
case req = <-reqCh:
if req == nil {
return nil
}
}
reply := s.doRequest(req)
reqPool.Put(req)
replyLock.Lock()
err := reply.Send(f)
replyLock.Unlock()
replyPool.Put(reply)
if err != nil {
log.Printf("Error writing NBD reply: %v", err)
return err
}
}
})
}
go func() {
err := g.Wait()
if err != nil {
s.Disconnect()
}
}()
var err error
bufr := bufio.NewReaderSize(f, readBufferSize)
for {
req, err := reqPool.Recv(bufr)
if err != nil {
break
}
if req.cmd == nbdCmdDisc {
break
}
reqCh <- req
}
close(reqCh)
if err != nil {
log.Println("Error in main server loop", err)
}
g.Wait()
if s.nlConn == nil {
unix.Syscall(unix.SYS_IOCTL, uintptr(s.devFd), nbdClearSock, 0)
unix.Close(s.devFd)
}
}