summaryrefslogtreecommitdiff
path: root/lib/btrfs/btrfstree/readnode.go
blob: bb80d20fc1641ed30e8ed2d4c7d6e84b5f198a16 (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
// Copyright (C) 2022  Luke Shumaker <lukeshu@lukeshu.com>
//
// SPDX-License-Identifier: GPL-2.0-or-later

package btrfstree

import (
	"fmt"

	"git.lukeshu.com/btrfs-progs-ng/lib/btrfs/btrfsprim"
	"git.lukeshu.com/btrfs-progs-ng/lib/btrfs/btrfsvol"
	"git.lukeshu.com/btrfs-progs-ng/lib/containers"
	"git.lukeshu.com/btrfs-progs-ng/lib/diskio"
)

// FSReadNode is a utility function to help with implementing the
// 'NodeSource' interface.
func FSReadNode(
	fs interface {
		diskio.File[btrfsvol.LogicalAddr]
		Superblock() (*Superblock, error)
		ParentTree(btrfsprim.ObjID) (btrfsprim.ObjID, bool)
	},
	path TreePath,
) (*diskio.Ref[btrfsvol.LogicalAddr, Node], error) {
	sb, err := fs.Superblock()
	if err != nil {
		return nil, fmt.Errorf("btrfs.FS.ReadNode: %w", err)
	}

	var treeParents []btrfsprim.ObjID
	checkOwner := func(owner btrfsprim.ObjID) error {
		exp := path.Node(-1).FromTree
		for {
			if owner == exp {
				return nil
			}
			treeParents = append(treeParents, exp)
			var ok bool
			exp, ok = fs.ParentTree(exp)
			if !ok {
				return fmt.Errorf("expected owner in %v but claims to have owner=%v",
					treeParents, owner)
			}
		}
	}

	return ReadNode[btrfsvol.LogicalAddr](fs, *sb, path.Node(-1).ToNodeAddr, NodeExpectations{
		LAddr:         containers.Optional[btrfsvol.LogicalAddr]{OK: true, Val: path.Node(-1).ToNodeAddr},
		Level:         containers.Optional[uint8]{OK: true, Val: path.Node(-1).ToNodeLevel},
		MaxGeneration: containers.Optional[btrfsprim.Generation]{OK: true, Val: path.Node(-1).FromGeneration},
		Owner:         checkOwner,
	})
}