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
|
// Copyright (C) 2022 Luke Shumaker <lukeshu@lukeshu.com>
//
// SPDX-License-Identifier: GPL-2.0-or-later
package btrfs
import (
"fmt"
"os"
"git.lukeshu.com/btrfs-progs-ng/lib/binstruct"
"git.lukeshu.com/btrfs-progs-ng/lib/btrfs/btrfsvol"
"git.lukeshu.com/btrfs-progs-ng/lib/diskio"
)
type Device struct {
*os.File
cacheSuperblocks []*diskio.Ref[btrfsvol.PhysicalAddr, Superblock]
cacheSuperblock *Superblock
}
var _ diskio.File[btrfsvol.PhysicalAddr] = (*Device)(nil)
func (dev Device) Size() (btrfsvol.PhysicalAddr, error) {
fi, err := dev.Stat()
if err != nil {
return 0, err
}
return btrfsvol.PhysicalAddr(fi.Size()), nil
}
func (dev *Device) ReadAt(dat []byte, paddr btrfsvol.PhysicalAddr) (int, error) {
return dev.File.ReadAt(dat, int64(paddr))
}
func (dev *Device) WriteAt(dat []byte, paddr btrfsvol.PhysicalAddr) (int, error) {
return dev.File.WriteAt(dat, int64(paddr))
}
var SuperblockAddrs = []btrfsvol.PhysicalAddr{
0x00_0001_0000, // 64KiB
0x00_0400_0000, // 64MiB
0x40_0000_0000, // 256GiB
}
func (dev *Device) Superblocks() ([]*diskio.Ref[btrfsvol.PhysicalAddr, Superblock], error) {
if dev.cacheSuperblocks != nil {
return dev.cacheSuperblocks, nil
}
superblockSize := btrfsvol.PhysicalAddr(binstruct.StaticSize(Superblock{}))
sz, err := dev.Size()
if err != nil {
return nil, err
}
var ret []*diskio.Ref[btrfsvol.PhysicalAddr, Superblock]
for i, addr := range SuperblockAddrs {
if addr+superblockSize <= sz {
superblock := &diskio.Ref[btrfsvol.PhysicalAddr, Superblock]{
File: dev,
Addr: addr,
}
if err := superblock.Read(); err != nil {
return nil, fmt.Errorf("superblock %v: %w", i, err)
}
ret = append(ret, superblock)
}
}
if len(ret) == 0 {
return nil, fmt.Errorf("no superblocks")
}
dev.cacheSuperblocks = ret
return ret, nil
}
func (dev *Device) Superblock() (*Superblock, error) {
if dev.cacheSuperblock != nil {
return dev.cacheSuperblock, nil
}
sbs, err := dev.Superblocks()
if err != nil {
return nil, err
}
for i, sb := range sbs {
if err := sb.Data.ValidateChecksum(); err != nil {
return nil, fmt.Errorf("superblock %v: %w", i, err)
}
if i > 0 {
if !sb.Data.Equal(sbs[0].Data) {
return nil, fmt.Errorf("superblock %v and superblock %v disagree", 0, i)
}
}
}
dev.cacheSuperblock = &sbs[0].Data
return &sbs[0].Data, nil
}
|