summaryrefslogtreecommitdiff
path: root/pkg/btrfs/btrfsvol/lvm.go
blob: 2857762f39193d38773e5678e5eb009fb228f960 (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
package btrfsvol

import (
	"bytes"
	"fmt"
	"os"
	"reflect"

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

type LogicalVolume[PhysicalVolume util.File[PhysicalAddr]] struct {
	name string

	id2pv map[DeviceID]PhysicalVolume

	logical2physical *rbtree.Tree[LogicalAddr, chunkMapping]
	physical2logical map[DeviceID]*rbtree.Tree[PhysicalAddr, devextMapping]
}

var _ util.File[LogicalAddr] = (*LogicalVolume[util.File[PhysicalAddr]])(nil)

func (lv *LogicalVolume[PhysicalVolume]) init() {
	if lv.id2pv == nil {
		lv.id2pv = make(map[DeviceID]PhysicalVolume)
	}
	if lv.logical2physical == nil {
		lv.logical2physical = &rbtree.Tree[LogicalAddr, chunkMapping]{
			KeyFn: func(chunk chunkMapping) LogicalAddr {
				return chunk.LAddr
			},
		}
	}
	if lv.physical2logical == nil {
		lv.physical2logical = make(map[DeviceID]*rbtree.Tree[PhysicalAddr, devextMapping], len(lv.id2pv))
	}
	for devid := range lv.id2pv {
		if _, ok := lv.physical2logical[devid]; !ok {
			lv.physical2logical[devid] = &rbtree.Tree[PhysicalAddr, devextMapping]{
				KeyFn: func(ext devextMapping) PhysicalAddr {
					return ext.PAddr
				},
			}
		}
	}
}

func (lv *LogicalVolume[PhysicalVolume]) SetName(name string) {
	lv.name = name
}

func (lv *LogicalVolume[PhysicalVolume]) Name() string {
	return lv.name
}

func (lv *LogicalVolume[PhysicalVolume]) Size() (LogicalAddr, error) {
	lv.init()
	lastChunk := lv.logical2physical.Max()
	if lastChunk == nil {
		return 0, nil
	}
	return lastChunk.Value.LAddr.Add(lastChunk.Value.Size), nil
}

func (lv *LogicalVolume[PhysicalVolume]) AddPhysicalVolume(id DeviceID, dev PhysicalVolume) error {
	lv.init()
	if other, exists := lv.id2pv[id]; exists {
		return fmt.Errorf("(%p).AddPhysicalVolume: cannot add physical volume %q: already have physical volume %q with id=%v",
			lv, dev.Name(), other.Name(), id)
	}
	lv.id2pv[id] = dev
	lv.physical2logical[id] = &rbtree.Tree[PhysicalAddr, devextMapping]{
		KeyFn: func(ext devextMapping) PhysicalAddr {
			return ext.PAddr
		},
	}
	return nil
}

func (lv *LogicalVolume[PhysicalVolume]) PhysicalVolumes() map[DeviceID]PhysicalVolume {
	dup := make(map[DeviceID]PhysicalVolume, len(lv.id2pv))
	for k, v := range lv.id2pv {
		dup[k] = v
	}
	return dup
}

func (lv *LogicalVolume[PhysicalVolume]) ClearMappings() {
	lv.logical2physical = nil
	lv.physical2logical = nil
}

type Mapping struct {
	LAddr      LogicalAddr
	PAddr      QualifiedPhysicalAddr
	Size       AddrDelta
	SizeLocked bool
	Flags      *BlockGroupFlags
}

func (lv *LogicalVolume[PhysicalVolume]) AddMapping(m Mapping) error {
	lv.init()
	// sanity check
	if _, haveDev := lv.id2pv[m.PAddr.Dev]; !haveDev {
		return fmt.Errorf("(%p).AddMapping: do not have a physical volume with id=%v",
			lv, m.PAddr.Dev)
	}

	// logical2physical
	newChunk := chunkMapping{
		LAddr:      m.LAddr,
		PAddrs:     []QualifiedPhysicalAddr{m.PAddr},
		Size:       m.Size,
		SizeLocked: m.SizeLocked,
		Flags:      m.Flags,
	}
	logicalOverlaps := lv.logical2physical.SearchRange(newChunk.cmpRange)
	var err error
	newChunk, err = newChunk.union(logicalOverlaps...)
	if err != nil {
		return fmt.Errorf("(%p).AddMapping: %w", lv, err)
	}

	// physical2logical
	newExt := devextMapping{
		PAddr:      m.PAddr.Addr,
		LAddr:      m.LAddr,
		Size:       m.Size,
		SizeLocked: m.SizeLocked,
		Flags:      m.Flags,
	}
	physicalOverlaps := lv.physical2logical[m.PAddr.Dev].SearchRange(newExt.cmpRange)
	newExt, err = newExt.union(physicalOverlaps...)
	if err != nil {
		return fmt.Errorf("(%p).AddMapping: %w", lv, err)
	}

	// optimize
	if len(logicalOverlaps) == 1 && reflect.DeepEqual(newChunk, logicalOverlaps[0]) &&
		len(physicalOverlaps) == 1 && reflect.DeepEqual(newExt, physicalOverlaps[0]) {
		return nil
	}

	// logical2physical
	for _, chunk := range logicalOverlaps {
		lv.logical2physical.Delete(chunk.LAddr)
	}
	lv.logical2physical.Insert(newChunk)

	// physical2logical
	for _, ext := range physicalOverlaps {
		lv.physical2logical[m.PAddr.Dev].Delete(ext.PAddr)
	}
	lv.physical2logical[m.PAddr.Dev].Insert(newExt)

	// sanity check
	//
	// This is in-theory unnescessary, but that assumes that I
	// made no mistakes in my algorithm above.
	if os.Getenv("PARANOID") != "" {
		if err := lv.fsck(); err != nil {
			return err
		}
	}

	// done
	return nil
}

func (lv *LogicalVolume[PhysicalVolume]) fsck() error {
	physical2logical := make(map[DeviceID]*rbtree.Tree[PhysicalAddr, devextMapping])
	if err := lv.logical2physical.Walk(func(node *rbtree.Node[chunkMapping]) error {
		chunk := node.Value
		for _, stripe := range chunk.PAddrs {
			if _, devOK := lv.id2pv[stripe.Dev]; !devOK {
				return fmt.Errorf("(%p).fsck: chunk references physical volume %v which does not exist",
					lv, stripe.Dev)
			}
			if _, exists := physical2logical[stripe.Dev]; !exists {
				physical2logical[stripe.Dev] = &rbtree.Tree[PhysicalAddr, devextMapping]{
					KeyFn: func(ext devextMapping) PhysicalAddr {
						return ext.PAddr
					},
				}
			}
			physical2logical[stripe.Dev].Insert(devextMapping{
				PAddr: stripe.Addr,
				LAddr: chunk.LAddr,
				Size:  chunk.Size,
				Flags: chunk.Flags,
			})
		}
		return nil
	}); err != nil {
		return err
	}

	if len(lv.physical2logical) != len(physical2logical) {
		return fmt.Errorf("(%p).fsck: skew between chunk tree and devext tree",
			lv)
	}
	for devid := range lv.physical2logical {
		if !lv.physical2logical[devid].Equal(physical2logical[devid]) {
			return fmt.Errorf("(%p).fsck: skew between chunk tree and devext tree",
				lv)
		}
	}

	return nil
}

func (lv *LogicalVolume[PhysicalVolume]) Mappings() []Mapping {
	var ret []Mapping
	lv.logical2physical.Walk(func(node *rbtree.Node[chunkMapping]) error {
		chunk := node.Value
		var flags *BlockGroupFlags
		if chunk.Flags != nil {
			val := *chunk.Flags
			flags = &val
		}
		for _, slice := range chunk.PAddrs {
			ret = append(ret, Mapping{
				LAddr: chunk.LAddr,
				PAddr: slice,
				Size:  chunk.Size,
				Flags: flags,
			})
		}
		return nil
	})
	return ret
}

func (lv *LogicalVolume[PhysicalVolume]) Resolve(laddr LogicalAddr) (paddrs map[QualifiedPhysicalAddr]struct{}, maxlen AddrDelta) {
	node := lv.logical2physical.Search(func(chunk chunkMapping) int {
		return chunkMapping{LAddr: laddr, Size: 1}.cmpRange(chunk)
	})
	if node == nil {
		return nil, 0
	}

	chunk := node.Value

	offsetWithinChunk := laddr.Sub(chunk.LAddr)
	paddrs = make(map[QualifiedPhysicalAddr]struct{})
	maxlen = chunk.Size - offsetWithinChunk
	for _, stripe := range chunk.PAddrs {
		paddrs[QualifiedPhysicalAddr{
			Dev:  stripe.Dev,
			Addr: stripe.Addr.Add(offsetWithinChunk),
		}] = struct{}{}
	}

	return paddrs, maxlen
}

func (lv *LogicalVolume[PhysicalVolume]) ResolveAny(laddr LogicalAddr, size AddrDelta) (LogicalAddr, QualifiedPhysicalAddr) {
	node := lv.logical2physical.Search(func(chunk chunkMapping) int {
		return chunkMapping{LAddr: laddr, Size: size}.cmpRange(chunk)
	})
	if node == nil {
		return -1, QualifiedPhysicalAddr{0, -1}
	}
	return node.Value.LAddr, node.Value.PAddrs[0]
}

func (lv *LogicalVolume[PhysicalVolume]) UnResolve(paddr QualifiedPhysicalAddr) LogicalAddr {
	node := lv.physical2logical[paddr.Dev].Search(func(ext devextMapping) int {
		return devextMapping{PAddr: paddr.Addr, Size: 1}.cmpRange(ext)
	})
	if node == nil {
		return -1
	}

	ext := node.Value

	offsetWithinExt := paddr.Addr.Sub(ext.PAddr)
	return ext.LAddr.Add(offsetWithinExt)
}

func (lv *LogicalVolume[PhysicalVolume]) ReadAt(dat []byte, laddr LogicalAddr) (int, error) {
	done := 0
	for done < len(dat) {
		n, err := lv.maybeShortReadAt(dat[done:], laddr+LogicalAddr(done))
		done += n
		if err != nil {
			return done, err
		}
	}
	return done, nil
}

func (lv *LogicalVolume[PhysicalVolume]) maybeShortReadAt(dat []byte, laddr LogicalAddr) (int, error) {
	paddrs, maxlen := lv.Resolve(laddr)
	if len(paddrs) == 0 {
		return 0, fmt.Errorf("read: could not map logical address %v", laddr)
	}
	if AddrDelta(len(dat)) > maxlen {
		dat = dat[:maxlen]
	}

	buf := make([]byte, len(dat))
	first := true
	for paddr := range paddrs {
		dev, ok := lv.id2pv[paddr.Dev]
		if !ok {
			return 0, fmt.Errorf("device=%v does not exist", paddr.Dev)
		}
		if _, err := dev.ReadAt(buf, paddr.Addr); err != nil {
			return 0, fmt.Errorf("read device=%v paddr=%v: %w", paddr.Dev, paddr.Addr, err)
		}
		if first {
			copy(dat, buf)
		} else {
			if !bytes.Equal(dat, buf) {
				return 0, fmt.Errorf("inconsistent stripes at laddr=%v len=%v", laddr, len(dat))
			}
		}
	}
	return len(dat), nil
}

func (lv *LogicalVolume[PhysicalVolume]) WriteAt(dat []byte, laddr LogicalAddr) (int, error) {
	done := 0
	for done < len(dat) {
		n, err := lv.maybeShortWriteAt(dat[done:], laddr+LogicalAddr(done))
		done += n
		if err != nil {
			return done, err
		}
	}
	return done, nil
}

func (lv *LogicalVolume[PhysicalVolume]) maybeShortWriteAt(dat []byte, laddr LogicalAddr) (int, error) {
	paddrs, maxlen := lv.Resolve(laddr)
	if len(paddrs) == 0 {
		return 0, fmt.Errorf("write: could not map logical address %v", laddr)
	}
	if AddrDelta(len(dat)) > maxlen {
		dat = dat[:maxlen]
	}

	for paddr := range paddrs {
		dev, ok := lv.id2pv[paddr.Dev]
		if !ok {
			return 0, fmt.Errorf("device=%v does not exist", paddr.Dev)
		}
		if _, err := dev.WriteAt(dat, paddr.Addr); err != nil {
			return 0, fmt.Errorf("write device=%v paddr=%v: %w", paddr.Dev, paddr.Addr, err)
		}
	}
	return len(dat), nil
}