summaryrefslogtreecommitdiff
path: root/pkg/btrfs/io1_device.go
blob: 32070cdc66ee80f8f0aa44afa3500ffae9e8e048 (plain)
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
package btrfs

import (
	"fmt"
	"os"

	"lukeshu.com/btrfs-tools/pkg/binstruct"
	"lukeshu.com/btrfs-tools/pkg/util"
)

type Device struct {
	*os.File

	cacheSuperblocks []*util.Ref[PhysicalAddr, Superblock]
	cacheSuperblock  *util.Ref[PhysicalAddr, Superblock]
}

func (dev Device) Size() (PhysicalAddr, error) {
	fi, err := dev.Stat()
	if err != nil {
		return 0, err
	}
	return PhysicalAddr(fi.Size()), nil
}

var SuperblockAddrs = []PhysicalAddr{
	0x00_0001_0000, // 64KiB
	0x00_0400_0000, // 64MiB
	0x40_0000_0000, // 256GiB
}

func (dev *Device) ReadAt(dat []byte, paddr PhysicalAddr) (int, error) {
	return dev.File.ReadAt(dat, int64(paddr))
}

func (dev *Device) WriteAt(dat []byte, paddr PhysicalAddr) (int, error) {
	return dev.File.WriteAt(dat, int64(paddr))
}

func (dev *Device) Superblocks() ([]*util.Ref[PhysicalAddr, Superblock], error) {
	if dev.cacheSuperblocks != nil {
		return dev.cacheSuperblocks, nil
	}
	superblockSize := PhysicalAddr(binstruct.StaticSize(Superblock{}))

	sz, err := dev.Size()
	if err != nil {
		return nil, err
	}

	var ret []*util.Ref[PhysicalAddr, Superblock]
	for i, addr := range SuperblockAddrs {
		if addr+superblockSize <= sz {
			superblock := &util.Ref[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() (*util.Ref[PhysicalAddr, 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]
	return sbs[0], nil
}