summaryrefslogtreecommitdiff
path: root/lib/btrfsprogs/btrfsinspect/rebuildnodes/rebuild.go
blob: c5f51ca37fc60baf6173f7b2be1fa63b38148282 (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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
// Copyright (C) 2022  Luke Shumaker <lukeshu@lukeshu.com>
//
// SPDX-License-Identifier: GPL-2.0-or-later

package rebuildnodes

import (
	"context"
	"fmt"

	"github.com/datawire/dlib/dlog"

	"git.lukeshu.com/btrfs-progs-ng/lib/btrfs"
	"git.lukeshu.com/btrfs-progs-ng/lib/btrfs/btrfsitem"
	"git.lukeshu.com/btrfs-progs-ng/lib/btrfs/btrfsprim"
	"git.lukeshu.com/btrfs-progs-ng/lib/btrfs/btrfssum"
	"git.lukeshu.com/btrfs-progs-ng/lib/btrfs/btrfstree"
	"git.lukeshu.com/btrfs-progs-ng/lib/btrfs/btrfsvol"
	"git.lukeshu.com/btrfs-progs-ng/lib/btrfsprogs/btrfsinspect"
	"git.lukeshu.com/btrfs-progs-ng/lib/btrfsprogs/btrfsinspect/rebuildmappings"
	"git.lukeshu.com/btrfs-progs-ng/lib/btrfsprogs/btrfsinspect/rebuildnodes/graph"
	"git.lukeshu.com/btrfs-progs-ng/lib/btrfsprogs/btrfsinspect/rebuildnodes/uuidmap"
	"git.lukeshu.com/btrfs-progs-ng/lib/btrfsprogs/btrfsutil"
	"git.lukeshu.com/btrfs-progs-ng/lib/containers"
	"git.lukeshu.com/btrfs-progs-ng/lib/maps"
)

type Rebuilder struct {
	raw   *btrfs.FS
	inner interface {
		btrfstree.TreeOperator
		Augment(treeID btrfsprim.ObjID, nodeAddr btrfsvol.LogicalAddr) ([]btrfsprim.Key, error)
	}
	sb btrfstree.Superblock

	graph        graph.Graph
	uuidMap      uuidmap.UUIDMap
	csums        containers.RBTree[containers.NativeOrdered[btrfsvol.LogicalAddr], btrfsinspect.SysExtentCSum]
	orphans      containers.Set[btrfsvol.LogicalAddr]
	leaf2orphans map[btrfsvol.LogicalAddr]containers.Set[btrfsvol.LogicalAddr]
	key2leaf     containers.SortedMap[keyAndTree, btrfsvol.LogicalAddr]

	augments map[btrfsprim.ObjID]containers.Set[btrfsvol.LogicalAddr]

	pendingAugments map[btrfsprim.ObjID][]map[btrfsvol.LogicalAddr]int
}

func RebuildNodes(ctx context.Context, fs *btrfs.FS, nodeScanResults btrfsinspect.ScanDevicesResult) (map[btrfsprim.ObjID]containers.Set[btrfsvol.LogicalAddr], error) {
	scanData, err := ScanDevices(ctx, fs, nodeScanResults) // ScanDevices does its own logging
	if err != nil {
		return nil, err
	}

	dlog.Info(ctx, "Reading superblock...")
	sb, err := fs.Superblock()
	if err != nil {
		return nil, err
	}

	dlog.Info(ctx, "Indexing checksums...")
	csums, _ := rebuildmappings.ExtractLogicalSums(ctx, nodeScanResults)
	if csums == nil {
		csums = new(containers.RBTree[containers.NativeOrdered[btrfsvol.LogicalAddr], btrfsinspect.SysExtentCSum])
	}

	dlog.Info(ctx, "Indexing orphans...")
	orphans, leaf2orphans, key2leaf, err := indexOrphans(fs, *sb, *scanData.nodeGraph)
	if err != nil {
		return nil, err
	}

	dlog.Info(ctx, "Rebuilding node tree...")
	o := &Rebuilder{
		raw:   fs,
		inner: btrfsutil.NewBrokenTrees(ctx, fs),
		sb:    *sb,

		graph:        *scanData.nodeGraph,
		uuidMap:      *scanData.uuidMap,
		csums:        *csums,
		orphans:      orphans,
		leaf2orphans: leaf2orphans,
		key2leaf:     *key2leaf,

		augments: make(map[btrfsprim.ObjID]containers.Set[btrfsvol.LogicalAddr]),
	}
	if err := o.rebuild(ctx); err != nil {
		return nil, err
	}

	return o.augments, nil
}

func (o *Rebuilder) rebuild(ctx context.Context) error {
	o.pendingAugments = make(map[btrfsprim.ObjID][]map[btrfsvol.LogicalAddr]int)
	btrfsutil.WalkAllTrees(ctx, o.inner, btrfsutil.WalkAllTreesHandler{
		Err: func(*btrfsutil.WalkError) {},
		TreeWalkHandler: btrfstree.TreeWalkHandler{
			Item: func(path btrfstree.TreePath, item btrfstree.Item) error {
				handleItem(o, ctx, path[0].FromTree, item)
				return nil
			},
		},
	})
	for len(o.pendingAugments) > 0 {
		// Apply the augments, keeping track of what keys are added to what tree.
		newKeys := make(map[btrfsprim.ObjID][]btrfsprim.Key)
		for _, treeID := range maps.SortedKeys(o.pendingAugments) {
			treeAugments := o.resolveTreeAugments(ctx, o.pendingAugments[treeID])
			for _, nodeAddr := range maps.SortedKeys(treeAugments) {
				added, err := o.inner.Augment(treeID, nodeAddr)
				if err != nil {
					o.err(ctx, err)
					continue
				}
				newKeys[treeID] = append(newKeys[treeID], added...)

				set := o.augments[treeID]
				if set == nil {
					set = make(containers.Set[btrfsvol.LogicalAddr])
					o.augments[treeID] = set
				}
				set.Insert(nodeAddr)
			}
		}
		// Clear the list of pending augments.
		o.pendingAugments = make(map[btrfsprim.ObjID][]map[btrfsvol.LogicalAddr]int)
		// Call handleItem() for each of the added keys.
		for _, treeID := range maps.SortedKeys(newKeys) {
			for _, key := range newKeys[treeID] {
				item, err := o.inner.TreeLookup(treeID, key)
				if err != nil {
					o.err(ctx, err)
					continue
				}
				handleItem(o, ctx, treeID, item)
			}
		}
	}
	return nil
}

func (o *Rebuilder) resolveTreeAugments(ctx context.Context, listsWithDistances []map[btrfsvol.LogicalAddr]int) containers.Set[btrfsvol.LogicalAddr] {
	// TODO
	return nil
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

// _NodeFile is a subset of btrfstree.NodeFile.
type _NodeFile interface {
	ParentTree(btrfsprim.ObjID) (btrfsprim.ObjID, bool)
}

func treeDistance(fs _NodeFile, tree, leaf btrfsprim.ObjID) (int, bool) {
	dist := 0
	for {
		if tree == leaf {
			return dist, true
		}

		parentTree, ok := fs.ParentTree(tree)
		if !ok {
			// Failed to look up parent info.
			return 0, false
		}
		if parentTree == 0 {
			// End of the line.
			return 0, false
		}

		tree = parentTree
		dist++
	}
}

func (o *Rebuilder) wantAugment(ctx context.Context, treeID btrfsprim.ObjID, choices containers.Set[btrfsvol.LogicalAddr]) {
	choicesWithDist := make(map[btrfsvol.LogicalAddr]int)
	for choice := range choices {
		if dist, ok := treeDistance(o.uuidMap, treeID, o.graph.Nodes[choice].Owner); ok {
			choicesWithDist[choice] = dist
		}
	}
	if len(choicesWithDist) > 0 {
		o.pendingAugments[treeID] = append(o.pendingAugments[treeID], choicesWithDist)
	}
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

// err implements rebuildCallbacks.
func (o *Rebuilder) err(ctx context.Context, e error) {
	dlog.Errorf(ctx, "rebuild error: %v", e)
}

// want implements rebuildCallbacks.
func (o *Rebuilder) want(ctx context.Context, treeID btrfsprim.ObjID, objID btrfsprim.ObjID, typ btrfsprim.ItemType) {
	// check if we already have it

	tgt := btrfsprim.Key{
		ObjectID: objID,
		ItemType: typ,
	}
	if _, err := o.inner.TreeSearch(treeID, func(key btrfsprim.Key, _ uint32) int {
		key.Offset = 0
		return tgt.Cmp(key)
	}); err == nil {
		return
	}

	// OK, we need to insert it

	wants := make(containers.Set[btrfsvol.LogicalAddr])
	o.key2leaf.Subrange(
		func(k keyAndTree, _ btrfsvol.LogicalAddr) int { k.Key.Offset = 0; return tgt.Cmp(k.Key) },
		func(_ keyAndTree, v btrfsvol.LogicalAddr) bool {
			wants.InsertFrom(o.leaf2orphans[v])
			return true
		})
	o.wantAugment(ctx, treeID, wants)
}

// wantOff implements rebuildCallbacks.
func (o *Rebuilder) wantOff(ctx context.Context, treeID btrfsprim.ObjID, objID btrfsprim.ObjID, typ btrfsprim.ItemType, off uint64) {
	// check if we already have it

	tgt := btrfsprim.Key{
		ObjectID: objID,
		ItemType: typ,
		Offset:   off,
	}
	if _, err := o.inner.TreeLookup(treeID, tgt); err == nil {
		return
	}

	// OK, we need to insert it

	wants := make(containers.Set[btrfsvol.LogicalAddr])
	o.key2leaf.Subrange(
		func(k keyAndTree, _ btrfsvol.LogicalAddr) int { return tgt.Cmp(k.Key) },
		func(_ keyAndTree, v btrfsvol.LogicalAddr) bool {
			wants.InsertFrom(o.leaf2orphans[v])
			return true
		})
	o.wantAugment(ctx, treeID, wants)
}

// wantFunc implements rebuildCallbacks.
func (o *Rebuilder) wantFunc(ctx context.Context, treeID btrfsprim.ObjID, objID btrfsprim.ObjID, typ btrfsprim.ItemType, fn func(btrfsitem.Item) bool) {
	// check if we already have it

	tgt := btrfsprim.Key{
		ObjectID: objID,
		ItemType: typ,
	}
	items, _ := o.inner.TreeSearchAll(treeID, func(key btrfsprim.Key, _ uint32) int {
		key.Offset = 0
		return tgt.Cmp(key)
	})
	for _, item := range items {
		if fn(item.Body) {
			return
		}
	}

	// OK, we need to insert it

	wants := make(containers.Set[btrfsvol.LogicalAddr])
	o.key2leaf.Subrange(
		func(k keyAndTree, _ btrfsvol.LogicalAddr) int { k.Key.Offset = 0; return tgt.Cmp(k.Key) },
		func(k keyAndTree, v btrfsvol.LogicalAddr) bool {
			nodeRef, err := btrfstree.ReadNode[btrfsvol.LogicalAddr](o.raw, o.sb, v, btrfstree.NodeExpectations{
				LAddr:      containers.Optional[btrfsvol.LogicalAddr]{OK: true, Val: v},
				Generation: containers.Optional[btrfsprim.Generation]{OK: true, Val: o.graph.Nodes[v].Generation},
			})
			if err != nil {
				o.err(ctx, err)
				return true
			}
			for _, item := range nodeRef.Data.BodyLeaf {
				if k.Key == item.Key && fn(item.Body) {
					wants.InsertFrom(o.leaf2orphans[v])
				}
			}
			return true
		})
	o.wantAugment(ctx, treeID, wants)
}

// func implements rebuildCallbacks.
//
// interval is [beg, end)
func (o *Rebuilder) wantCSum(ctx context.Context, beg, end btrfsvol.LogicalAddr) {
	for beg < end {
		// check if we already have it
		if run, err := btrfs.LookupCSum(o.inner, o.sb.ChecksumType, beg); err == nil {
			// we already have it
			beg = run.Addr.Add(run.Size())
		} else {
			// we need to insert it
			rbNode := o.csums.Search(func(item btrfsinspect.SysExtentCSum) int {
				switch {
				case item.Sums.Addr > beg:
					return -1
				case item.Sums.Addr.Add(item.Sums.Size()) <= beg:
					return 1
				default:
					return 0
				}

			})
			if rbNode == nil {
				o.err(ctx, fmt.Errorf("could not find csum for laddr=%v", beg))
				beg += btrfssum.BlockSize
				continue
			}
			run := rbNode.Value.Sums
			key := keyAndTree{
				Key:    rbNode.Value.Key,
				TreeID: btrfsprim.CSUM_TREE_OBJECTID,
			}
			leaf, ok := o.key2leaf.Load(key)
			if !ok {
				panic(fmt.Errorf("no orphan contains %v", key.Key))
			}
			o.wantAugment(ctx, key.TreeID, o.leaf2orphans[leaf])

			beg = run.Addr.Add(run.Size())
		}
	}
}

// wantFileExt implements rebuildCallbacks.
func (o *Rebuilder) wantFileExt(ctx context.Context, treeID btrfsprim.ObjID, ino btrfsprim.ObjID, size int64) {
	min := btrfsprim.Key{
		ObjectID: ino,
		ItemType: btrfsitem.EXTENT_DATA_KEY,
		Offset:   0,
	}
	max := btrfsprim.Key{
		ObjectID: ino,
		ItemType: btrfsitem.EXTENT_DATA_KEY,
		Offset:   uint64(size - 1),
	}
	exts, err := o.inner.TreeSearchAll(treeID, func(key btrfsprim.Key, _ uint32) int {
		switch {
		case min.Cmp(key) < 0:
			return 1
		case max.Cmp(key) > 0:
			return -1
		default:
			return 0
		}
	})
	if err != nil {
		o.err(ctx, err)
		return
	}

	type gap struct {
		// range is [Beg,End)
		Beg, End int64
	}
	gaps := &containers.RBTree[containers.NativeOrdered[int64], gap]{
		KeyFn: func(gap gap) containers.NativeOrdered[int64] {
			return containers.NativeOrdered[int64]{Val: gap.Beg}
		},
	}
	gaps.Insert(gap{
		Beg: 0,
		End: size,
	})
	for _, ext := range exts {
		extBody, ok := ext.Body.(btrfsitem.FileExtent)
		if !ok {
			o.err(ctx, fmt.Errorf("EXTENT_DATA is %T", ext.Body))
			continue
		}
		extBeg := int64(ext.Key.Offset)
		extSize, err := extBody.Size()
		if err != nil {
			o.err(ctx, err)
			continue
		}
		extEnd := extBeg + extSize
		overlappingGaps := gaps.SearchRange(func(gap gap) int {
			switch {
			case gap.End <= extBeg:
				return 1
			case extEnd <= gap.Beg:
				return -1
			default:
				return 0
			}
		})
		if len(overlappingGaps) == 0 {
			continue
		}
		beg := overlappingGaps[0].Beg
		end := overlappingGaps[len(overlappingGaps)-1].End
		for _, gap := range overlappingGaps {
			gaps.Delete(containers.NativeOrdered[int64]{Val: gap.Beg})
		}
		if beg < extBeg {
			gaps.Insert(gap{
				Beg: beg,
				End: extBeg,
			})
		}
		if end > extEnd {
			gaps.Insert(gap{
				Beg: extEnd,
				End: end,
			})
		}
	}
	if err := gaps.Walk(func(rbNode *containers.RBNode[gap]) error {
		gap := rbNode.Value
		min := btrfsprim.Key{
			ObjectID: ino,
			ItemType: btrfsitem.EXTENT_DATA_KEY,
			Offset:   0,
		}
		max := btrfsprim.Key{
			ObjectID: ino,
			ItemType: btrfsitem.EXTENT_DATA_KEY,
			Offset:   uint64(gap.End - 1),
		}
		wants := make(containers.Set[btrfsvol.LogicalAddr])
		o.key2leaf.Subrange(
			func(k keyAndTree, _ btrfsvol.LogicalAddr) int {
				switch {
				case min.Cmp(k.Key) < 0:
					return 1
				case max.Cmp(k.Key) > 0:
					return -1
				default:
					return 0
				}
			},
			func(k keyAndTree, v btrfsvol.LogicalAddr) bool {
				nodeRef, err := btrfstree.ReadNode[btrfsvol.LogicalAddr](o.raw, o.sb, v, btrfstree.NodeExpectations{
					LAddr:      containers.Optional[btrfsvol.LogicalAddr]{OK: true, Val: v},
					Generation: containers.Optional[btrfsprim.Generation]{OK: true, Val: o.graph.Nodes[v].Generation},
				})
				if err != nil {
					o.err(ctx, err)
					return true
				}
				for _, item := range nodeRef.Data.BodyLeaf {
					if k.Key == item.Key {
						itemBeg := int64(item.Key.Offset)
						itemBody, ok := item.Body.(btrfsitem.FileExtent)
						if !ok {
							o.err(ctx, fmt.Errorf("EXTENT_DATA is %T", item.Body))
							continue
						}
						itemSize, err := itemBody.Size()
						if err != nil {
							o.err(ctx, err)
							continue
						}
						itemEnd := itemBeg + itemSize
						// We're being and "wanting" any extent that has any overlap with the
						// gap.  But maybe instead we sould only want extents that are
						// *entirely* within the gap.  I'll have to run it on real filesystems
						// to see what works better.
						//
						// TODO(lukeshu): Re-evaluate whether being greedy here is the right
						// thing.
						if itemEnd > gap.Beg && itemBeg < gap.End {
							wants.InsertFrom(o.leaf2orphans[v])
						}
					}
				}
				return true
			})
		o.wantAugment(ctx, treeID, wants)
		return nil
	}); err != nil {
		o.err(ctx, err)
	}
}