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
|
package btrfsmisc
import (
"fmt"
"lukeshu.com/btrfs-tools/pkg/binstruct"
"lukeshu.com/btrfs-tools/pkg/btrfs"
"lukeshu.com/btrfs-tools/pkg/util"
)
// ScanForNodes mimics btrfs-progs
// cmds/rescue-chunk-recover.c:scan_one_device(), except it doesn't do
// anything but log when it finds a node.
func ScanForNodes(dev *btrfs.Device, sb btrfs.Superblock, fn func(*util.Ref[btrfs.PhysicalAddr, btrfs.Node], error)) error {
devSize, err := dev.Size()
if err != nil {
return err
}
if sb.NodeSize < sb.SectorSize {
return fmt.Errorf("node_size(%d) < sector_size(%d)",
sb.NodeSize, sb.SectorSize)
}
nodeBuf := make([]byte, sb.NodeSize)
for pos := btrfs.PhysicalAddr(0); pos+btrfs.PhysicalAddr(sb.NodeSize) < devSize; pos += btrfs.PhysicalAddr(sb.SectorSize) {
if util.InSlice(pos, btrfs.SuperblockAddrs) {
//fmt.Printf("sector@%d is a superblock\n", pos)
continue
}
// read
if _, err := dev.ReadAt(nodeBuf, pos); err != nil {
fn(nil, fmt.Errorf("sector@%d: %w", pos, err))
continue
}
// parse (early)
nodeRef := &util.Ref[btrfs.PhysicalAddr, btrfs.Node]{
File: dev,
Addr: pos,
Data: btrfs.Node{
Size: sb.NodeSize,
},
}
var nodeHeader btrfs.NodeHeader
if _, err := binstruct.Unmarshal(nodeBuf, &nodeHeader); err != nil {
fn(nil, fmt.Errorf("sector@%d: %w", pos, err))
}
// sanity checking
if nodeHeader.MetadataUUID != sb.EffectiveMetadataUUID() {
//fmt.Printf("sector@%d does not look like a node\n", pos)
continue
}
stored := nodeRef.Data.Head.Checksum
calced := btrfs.CRC32c(nodeBuf[binstruct.StaticSize(btrfs.CSum{}):])
if stored != calced {
fn(nodeRef, fmt.Errorf("sector@%d: looks like a node but is corrupt: checksum doesn't match: stored=%s calculated=%s",
pos, stored, calced))
continue
}
// parse (main)
if _, err := nodeRef.Data.UnmarshalBinary(nodeBuf); err != nil {
fn(nil, fmt.Errorf("sector@%d: %w", pos, err))
continue
}
// finally, process the node
fn(nodeRef, nil)
pos += btrfs.PhysicalAddr(sb.NodeSize) - btrfs.PhysicalAddr(sb.SectorSize)
}
return nil
}
|