summaryrefslogtreecommitdiff
path: root/pkg/btrfs/btrfsitem/item_chunk.go
blob: 8ffc83b2c68cbc32e1eba7d5415e963ceb9c1a45 (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
package btrfsitem

import (
	"fmt"

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

// Maps logical address to physical.
type Chunk struct { // CHUNK_ITEM=228
	Head    ChunkHeader
	Stripes []ChunkStripe
}

type ChunkHeader struct {
	Size           uint64          `bin:"off=0x0,  siz=0x8"` // size of chunk (bytes)
	Owner          internal.ObjID  `bin:"off=0x8,  siz=0x8"` // root referencing this chunk (2)
	StripeLen      uint64          `bin:"off=0x10, siz=0x8"` // stripe length
	Type           BlockGroupFlags `bin:"off=0x18, siz=0x8"` // type (same as flags for block group?)
	IOOptimalAlign uint32          `bin:"off=0x20, siz=0x4"` // optimal io alignment
	IOOptimalWidth uint32          `bin:"off=0x24, siz=0x4"` // optimal io width
	IOMinSize      uint32          `bin:"off=0x28, siz=0x4"` // minimal io size (sector size)
	NumStripes     uint16          `bin:"off=0x2c, siz=0x2"` // number of stripes
	SubStripes     uint16          `bin:"off=0x2e, siz=0x2"` // sub stripes
	binstruct.End  `bin:"off=0x30"`
}

type ChunkStripe struct {
	DeviceID      internal.ObjID        `bin:"off=0x0,  siz=0x8"`
	Offset        internal.PhysicalAddr `bin:"off=0x8,  siz=0x8"`
	DeviceUUID    internal.UUID         `bin:"off=0x10, siz=0x10"`
	binstruct.End `bin:"off=0x20"`
}

func (chunk *Chunk) UnmarshalBinary(dat []byte) (int, error) {
	n, err := binstruct.Unmarshal(dat, &chunk.Head)
	if err != nil {
		return n, err
	}
	chunk.Stripes = nil
	for i := 0; i < int(chunk.Head.NumStripes); i++ {
		var stripe ChunkStripe
		_n, err := binstruct.Unmarshal(dat[n:], &stripe)
		n += _n
		if err != nil {
			return n, fmt.Errorf("%T.UnmarshalBinary: %w", *chunk, err)
		}
		chunk.Stripes = append(chunk.Stripes, stripe)
	}
	return n, nil
}

func (chunk Chunk) MarshalBinary() ([]byte, error) {
	chunk.Head.NumStripes = uint16(len(chunk.Stripes))
	ret, err := binstruct.Marshal(chunk.Head)
	if err != nil {
		return ret, err
	}
	for _, stripe := range chunk.Stripes {
		_ret, err := binstruct.Marshal(stripe)
		ret = append(ret, _ret...)
		if err != nil {
			return ret, fmt.Errorf("%T.MarshalBinary: %w", chunk, err)
		}
	}
	return ret, nil
}