-
Notifications
You must be signed in to change notification settings - Fork 14
/
blockdevice_linux.go
320 lines (255 loc) · 7.19 KB
/
blockdevice_linux.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
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
package blockdevice
import (
"errors"
"fmt"
"io"
"os"
"syscall"
"time"
"unsafe"
"github.com/siderolabs/go-retry/retry"
"golang.org/x/sys/unix"
"github.com/siderolabs/go-blockdevice/blockdevice/partition/gpt"
)
// Linux headers constants.
//
// Hardcoded here to avoid CGo dependency.
const (
BLKDISCARD = 4727
BLKDISCARDZEROES = 4732
BLKSECDISCARD = 4733
BLKZEROOUT = 4735
)
const (
// FastWipeRange fast wipe block.
FastWipeRange = 1024 * 1024
// ReadonlyMode readonly mode.
ReadonlyMode = unix.O_CLOEXEC | os.O_RDONLY
// DefaultMode read write.
DefaultMode = unix.O_CLOEXEC | os.O_RDWR
)
// BlockDevice represents a block device.
type BlockDevice struct {
g *gpt.GPT
f *os.File
}
// Open initializes and returns a block device.
// TODO(andrewrynhard): Use BLKGETSIZE ioctl to get the size.
func Open(devname string, setters ...Option) (_ *BlockDevice, rerr error) { //nolint:nonamedreturns
opts := NewDefaultOptions(setters...)
bd := &BlockDevice{}
var (
f *os.File
err error
)
if f, err = os.OpenFile(devname, opts.Mode, os.ModeDevice); err != nil {
return nil, err
}
bd.f = f
defer func() {
if rerr != nil {
//nolint: errcheck
f.Close()
}
}()
if opts.ExclusiveLock {
if err = syscall.Flock(int(f.Fd()), syscall.LOCK_EX); err != nil {
err = fmt.Errorf("error locking device %q: %w", devname, err)
return nil, err
}
}
if opts.CreateGPT {
var g *gpt.GPT
g, err = gpt.New(f)
if err != nil {
return nil, err
}
if err = g.Write(); err != nil {
return nil, err
}
bd.g = g
} else {
var g *gpt.GPT
if g, err = gpt.Open(f); err != nil {
if errors.Is(err, gpt.ErrPartitionTableDoesNotExist) {
return bd, nil
}
return nil, err
}
bd.g = g
}
return bd, nil
}
// Close closes the block devices's open file.
func (bd *BlockDevice) Close() error {
return bd.f.Close()
}
// PartitionTable returns the block device partition table.
func (bd *BlockDevice) PartitionTable() (*gpt.GPT, error) {
if bd.g == nil {
return nil, ErrMissingPartitionTable
}
return bd.g, bd.g.Read()
}
// RereadPartitionTable invokes the BLKRRPART ioctl to have the kernel read the
// partition table.
//
// NB: Rereading the partition table requires that all partitions be
// unmounted or it will fail with EBUSY.
func (bd *BlockDevice) RereadPartitionTable() error {
// Flush the file buffers.
// NOTE(andrewrynhard): I'm not entirely sure we need this, but
// figured it wouldn't hurt.
if err := bd.f.Sync(); err != nil {
return err
}
// Flush the block device buffers.
if _, _, ret := unix.Syscall(unix.SYS_IOCTL, bd.f.Fd(), unix.BLKFLSBUF, 0); ret != 0 {
return fmt.Errorf("flush block device buffers: %w", ret)
}
var (
err error
ret syscall.Errno
)
// Reread the partition table.
err = retry.Constant(5*time.Second, retry.WithUnits(50*time.Millisecond)).Retry(func() error {
if _, _, ret = unix.Syscall(unix.SYS_IOCTL, bd.f.Fd(), unix.BLKRRPART, 0); ret == 0 {
return nil
}
//nolint: exhaustive
switch ret {
case syscall.EBUSY:
return retry.ExpectedError(err)
default:
return err
}
})
if err != nil {
return fmt.Errorf("failed to re-read partition table: %w", err)
}
return nil
}
// Device returns the backing file for the block device.
func (bd *BlockDevice) Device() *os.File {
return bd.f
}
// Size returns the size of the block device in bytes.
func (bd *BlockDevice) Size() (uint64, error) {
var devsize uint64
if _, _, errno := unix.Syscall(unix.SYS_IOCTL, bd.f.Fd(), unix.BLKGETSIZE64, uintptr(unsafe.Pointer(&devsize))); errno != 0 {
return 0, errno
}
return devsize, nil
}
// Wipe the blockdevice contents.
//
// In order of availability this tries to perform the following:
// - secure discard (secure erase)
// - discard with zeros
// - zero out via ioctl
// - zero out from userland
func (bd *BlockDevice) Wipe() (string, error) {
size, err := bd.Size()
if err != nil {
return "", err
}
return bd.WipeRange(0, size)
}
// FastWipe the blockdevice contents.
//
// This method is much faster than Wipe(), but it doesn't guarantee
// that device will be zeroed out completely.
func (bd *BlockDevice) FastWipe() error {
size, err := bd.Size()
if err != nil {
return err
}
// BLKDISCARD is implemented via TRIM on SSDs, it might or might not zero out device contents.
r := [2]uint64{0, size}
// ignoring the error here as DISCARD might be not supported by the device
unix.Syscall(unix.SYS_IOCTL, bd.f.Fd(), BLKDISCARD, uintptr(unsafe.Pointer(&r[0]))) //nolint: errcheck
// zero out the first N bytes of the device to clear any partition table
wipeLength := uint64(FastWipeRange)
if wipeLength > size {
wipeLength = size
}
_, err = bd.WipeRange(0, wipeLength)
return err
}
// WipeRange the blockdevice [start, start+length).
func (bd *BlockDevice) WipeRange(start, length uint64) (string, error) {
var err error
r := [2]uint64{start, length}
if _, _, errno := unix.Syscall(unix.SYS_IOCTL, bd.f.Fd(), BLKSECDISCARD, uintptr(unsafe.Pointer(&r[0]))); errno == 0 {
return "blksecdiscard", nil
}
var zeroes int
if _, _, errno := unix.Syscall(unix.SYS_IOCTL, bd.f.Fd(), BLKDISCARDZEROES, uintptr(unsafe.Pointer(&zeroes))); errno == 0 && zeroes != 0 {
if _, _, errno = unix.Syscall(unix.SYS_IOCTL, bd.f.Fd(), BLKDISCARD, uintptr(unsafe.Pointer(&r[0]))); errno == 0 {
return "blkdiscardzeros", nil
}
}
if _, _, errno := unix.Syscall(unix.SYS_IOCTL, bd.f.Fd(), BLKZEROOUT, uintptr(unsafe.Pointer(&r[0]))); errno == 0 {
return "blkzeroout", nil
}
var zero *os.File
if zero, err = os.Open("/dev/zero"); err != nil {
return "", err
}
defer zero.Close() //nolint: errcheck
_, err = io.CopyN(bd.f, zero, int64(r[1]))
return "writezeroes", err
}
// Reset will reset a block device given a device name.
// Simply deletes partition table on device.
func (bd *BlockDevice) Reset() error {
g, err := bd.PartitionTable()
if err != nil {
return err
}
for _, p := range g.Partitions().Items() {
if err = g.Delete(p); err != nil {
return fmt.Errorf("failed to delete partition: %w", err)
}
}
return g.Write()
}
// OpenPartition opens another blockdevice using a partition of this block device.
func (bd *BlockDevice) OpenPartition(label string, setters ...Option) (*BlockDevice, error) {
g, err := bd.PartitionTable()
if err != nil {
return nil, err
}
part := g.Partitions().FindByName(label)
if part == nil {
return nil, os.ErrNotExist
}
path, err := part.Path()
if err != nil {
return nil, err
}
return Open(path, setters...)
}
// GetPartition returns partition by label if found.
func (bd *BlockDevice) GetPartition(label string) (*gpt.Partition, error) {
g, err := bd.PartitionTable()
if err != nil {
return nil, err
}
part := g.Partitions().FindByName(label)
if part == nil {
return nil, os.ErrNotExist
}
return part, nil
}
// PartPath returns partition path by label, verifies that partition exists.
func (bd *BlockDevice) PartPath(label string) (string, error) {
part, err := bd.GetPartition(label)
if err != nil {
return "", err
}
return part.Path()
}