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
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
|
use super::{DirEntry, FileSystem, Inode, InodeKind};
use crate::block::{BlockDevice, SECTOR_SIZE};
use crate::errno::Errno;
use alloc::{collections::BTreeMap, format, string::String, sync::Arc, vec, vec::Vec};
use spin::Mutex;
const SUPER_OFFSET: u64 = 0x10000; const SUPER_SIZE: usize = 4096;
const MAGIC: &[u8; 8] = b"_BHRfS_M";
const SB_FSID: usize = 0x20;
const SB_MAGIC: usize = 0x40;
const SB_GENERATION: usize = 0x48;
const SB_ROOT: usize = 0x50; const SB_CHUNK_ROOT: usize = 0x58;
const SB_TOTAL_BYTES: usize = 0x70;
const SB_BYTES_USED: usize = 0x78;
const SB_NUM_DEVICES: usize = 0x88;
const SB_SECTORSIZE: usize = 0x90;
const SB_NODESIZE: usize = 0x94;
const SB_SYS_CHUNK_ARRAY_SIZE: usize = 0xa0;
const SB_INCOMPAT: usize = 0xbc;
const SB_CSUM_TYPE: usize = 0xc4;
const SB_ROOT_LEVEL: usize = 0xc6;
const SB_CHUNK_ROOT_LEVEL: usize = 0xc7;
const SB_DEV_ITEM: usize = 0xc9; const SB_LABEL: usize = 0x12b; const SB_METADATA_UUID: usize = 0x23b;
const SB_SYS_CHUNK_ARRAY: usize = 0x32b;
const INCOMPAT_METADATA_UUID: u64 = 0x400;
const INCOMPAT_OK: u64 = 0x1 | 0x2 | 0x4 | 0x8 | 0x10 | 0x20 | 0x40 | 0x100 | 0x200 | INCOMPAT_METADATA_UUID
| 0x800 | 0x10000;
const HDR_FSID: usize = 0x20;
const HDR_BYTENR: usize = 0x30;
const HDR_NRITEMS: usize = 0x60;
const HDR_LEVEL: usize = 0x64;
const HEADER_SIZE: usize = 0x65;
const ITEM_SIZE: usize = 25; const KEY_PTR_SIZE: usize = 33;
const INODE_ITEM: u8 = 1;
const INODE_REF: u8 = 12;
const DIR_ITEM: u8 = 84;
const DIR_INDEX: u8 = 96;
const EXTENT_DATA: u8 = 108;
const EXTENT_CSUM: u8 = 128;
const ROOT_ITEM: u8 = 132;
const ROOT_REF: u8 = 156;
const CHUNK_ITEM: u8 = 228;
const FS_TREE: u64 = 5; const ROOT_TREE_DIR: u64 = 6; const CSUM_TREE: u64 = 7;
const FIRST_CHUNK_TREE: u64 = 256;
const CSUM_OBJECTID: u64 = -10i64 as u64;
const BG_DATA: u64 = 1;
const BG_SYSTEM: u64 = 2;
const BG_METADATA: u64 = 4;
const BG_DUP: u64 = 0x20;
const BG_PROFILES: u64 = 0x8 | 0x10 | 0x20 | 0x40 | 0x80 | 0x100 | 0x200 | 0x400;
const INODE_SIZE: usize = 16;
const INODE_MODE: usize = 52;
const INODE_FLAGS: usize = 64;
const INODE_NODATASUM: u64 = 1;
const S_IFMT: u32 = 0o170000;
const S_IFDIR: u32 = 0o040000;
const S_IFLNK: u32 = 0o120000;
const ROOT_DIRID: usize = 168; const ROOT_BYTENR: usize = 176;
const ROOT_FLAGS: usize = 208;
const ROOT_LEVEL: usize = 238;
const ROOT_RDONLY: u64 = 1;
const EXT_RAM_BYTES: usize = 8; const EXT_COMPRESSION: usize = 16;
const EXT_ENCRYPTION: usize = 17;
const EXT_OTHER_ENCODING: usize = 18;
const EXT_TYPE: usize = 20; const EXT_INLINE_DATA: usize = 21;
const EXT_DISK_BYTENR: usize = 21;
const EXT_DISK_NUM_BYTES: usize = 29;
const EXT_OFFSET: usize = 37;
const EXT_NUM_BYTES: usize = 45;
const EXT_REGULAR_SIZE: usize = 53;
const NODE_CACHE_BYTES: usize = 256 * 1024;
fn get16(b: &[u8], at: usize) -> u16 {
u16::from_le_bytes([b[at], b[at + 1]])
}
fn get32(b: &[u8], at: usize) -> u32 {
u32::from_le_bytes(b[at..at + 4].try_into().unwrap())
}
fn get64(b: &[u8], at: usize) -> u64 {
u64::from_le_bytes(b[at..at + 8].try_into().unwrap())
}
const CRC32C_TABLE: [u32; 256] = {
let mut table = [0u32; 256];
let mut i = 0;
while i < 256 {
let mut c = i as u32;
let mut bit = 0;
while bit < 8 {
c = if c & 1 != 0 { (c >> 1) ^ 0x82F6_3B78 } else { c >> 1 };
bit += 1;
}
table[i] = c;
i += 1;
}
table
};
fn crc32c_update(mut crc: u32, data: &[u8]) -> u32 {
for &b in data {
crc = CRC32C_TABLE[((crc ^ b as u32) & 0xff) as usize] ^ (crc >> 8);
}
crc
}
pub fn crc32c(data: &[u8]) -> u32 {
!crc32c_update(!0, data)
}
pub fn name_hash(name: &[u8]) -> u64 {
crc32c_update(!1, name) as u64
}
pub fn probe(dev: &dyn BlockDevice) -> bool {
let mut sector = [0u8; SECTOR_SIZE];
if dev.sector_count() < (SUPER_OFFSET + SUPER_SIZE as u64) / SECTOR_SIZE as u64 {
return false;
}
dev.read_sectors(SUPER_OFFSET / SECTOR_SIZE as u64, &mut sector).is_ok() && §or[SB_MAGIC..SB_MAGIC + 8] == MAGIC
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub struct Key {
pub objectid: u64,
pub kind: u8,
pub offset: u64,
}
impl Key {
const fn new(objectid: u64, kind: u8, offset: u64) -> Key {
Key { objectid, kind, offset }
}
fn parse(b: &[u8], at: usize) -> Key {
Key { objectid: get64(b, at), kind: b[at + 8], offset: get64(b, at + 9) }
}
}
#[derive(Debug, Clone, Copy)]
struct Tree {
bytenr: u64,
level: u8,
}
struct Chunk {
logical: u64,
length: u64,
kind: u64,
copies: Vec<u64>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct Loc {
root: u64,
ino: u64,
}
struct InodeItem {
size: u64,
mode: u32,
flags: u64,
}
struct DirItem {
location: Key, name: Vec<u8>,
file_type: u8, }
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Subvolume {
pub id: u64,
pub path: String, pub read_only: bool,
}
enum Extent<'a> {
Inline { compression: u8, data: &'a [u8], ram_bytes: u64 },
Regular { compression: u8, disk_bytenr: u64, disk_num_bytes: u64, offset: u64, num_bytes: u64, ram_bytes: u64 },
Prealloc { num_bytes: u64 },
}
impl<'a> Extent<'a> {
fn parse(d: &'a [u8]) -> Result<Extent<'a>, Errno> {
if d.len() < EXT_INLINE_DATA {
return Err(Errno::EIO);
}
if d[EXT_ENCRYPTION] != 0 || get16(d, EXT_OTHER_ENCODING) != 0 {
crate::kprintln!("[btrfs] encrypted extents are not supported");
return Err(Errno::EIO);
}
let compression = d[EXT_COMPRESSION];
let ram_bytes = get64(d, EXT_RAM_BYTES);
match d[EXT_TYPE] {
0 => Ok(Extent::Inline { compression, data: &d[EXT_INLINE_DATA..], ram_bytes }),
t @ (1 | 2) if d.len() >= EXT_REGULAR_SIZE => {
let num_bytes = get64(d, EXT_NUM_BYTES);
if t == 2 {
return Ok(Extent::Prealloc { num_bytes });
}
Ok(Extent::Regular {
compression,
disk_bytenr: get64(d, EXT_DISK_BYTENR),
disk_num_bytes: get64(d, EXT_DISK_NUM_BYTES),
offset: get64(d, EXT_OFFSET),
num_bytes,
ram_bytes,
})
}
_ => Err(Errno::EIO),
}
}
fn len(&self) -> u64 {
match self {
Extent::Inline { ram_bytes, .. } => *ram_bytes,
Extent::Regular { num_bytes, .. } | Extent::Prealloc { num_bytes } => *num_bytes,
}
}
}
fn decompress(compression: u8, src: &[u8], ram_bytes: usize, sectorsize: usize) -> Result<Vec<u8>, Errno> {
let fail = |what: &str| {
crate::kprintln!("[btrfs] {}", what);
Errno::EIO
};
let mut out = match compression {
1 => miniz_oxide::inflate::decompress_to_vec_zlib_with_limit(src, ram_bytes).map_err(|_| fail("bad zlib data"))?,
2 => {
if src.len() < 4 {
return Err(fail("bad lzo data"));
}
let total = (get32(src, 0) as usize).min(src.len());
let (mut pos, mut out) = (4, Vec::with_capacity(ram_bytes));
while pos < total && out.len() < ram_bytes {
if sectorsize - pos % sectorsize < 4 {
pos = pos.next_multiple_of(sectorsize);
}
if pos + 4 > total {
break;
}
let len = get32(src, pos) as usize;
let seg = src.get(pos + 4..pos + 4 + len).ok_or_else(|| fail("bad lzo segment"))?;
super::lzo::decompress(seg, &mut out, sectorsize).map_err(|e| fail(e))?;
pos += 4 + len;
}
out
}
3 => {
let mut decoder = ruzstd::decoding::FrameDecoder::new();
let mut input = src;
decoder.init(&mut input).map_err(|_| fail("bad zstd frame header"))?;
decoder
.decode_blocks(&mut input, ruzstd::decoding::BlockDecodingStrategy::All)
.map_err(|_| fail("bad zstd data"))?;
decoder.collect().unwrap_or_default()
}
n => return Err(fail(&format!("unknown compression type {}", n))),
};
out.resize(ram_bytes, 0);
Ok(out)
}
struct Volume {
dev: Arc<dyn BlockDevice>,
sectorsize: usize,
nodesize: usize,
metadata_fsid: [u8; 16], label: String,
generation: u64,
total_bytes: u64,
bytes_used: u64,
chunks: Vec<Chunk>,
root_tree: Tree,
csum_tree: Option<Tree>,
default_subvol: u64,
fs_trees: BTreeMap<u64, (Tree, u64)>, node_cache: Vec<(u64, Arc<Vec<u8>>)>, extent_cache: Option<(u64, Arc<Vec<u8>>)>, }
impl Volume {
fn open(dev: Arc<dyn BlockDevice>) -> Result<Volume, String> {
let mut sb = vec![0u8; SUPER_SIZE];
dev.read_sectors(SUPER_OFFSET / SECTOR_SIZE as u64, &mut sb).map_err(|e| format!("can't read the superblock: {:?}", e))?;
if &sb[SB_MAGIC..SB_MAGIC + 8] != MAGIC {
return Err(String::from("no btrfs magic"));
}
let csum_type = get16(&sb, SB_CSUM_TYPE);
if csum_type != 0 {
let name = ["crc32c", "xxhash64", "sha256", "blake2b"].get(csum_type as usize).copied().unwrap_or("unknown");
return Err(format!("checksum type {} ({}) is not supported, only crc32c", csum_type, name));
}
let (stored, computed) = (get32(&sb, 0), crc32c(&sb[0x20..]));
if stored != computed {
return Err(format!("bad superblock checksum ({:#010x}, should be {:#010x})", stored, computed));
}
let incompat = get64(&sb, SB_INCOMPAT);
if incompat & !INCOMPAT_OK != 0 {
return Err(format!("unsupported feature flags {:#x}", incompat & !INCOMPAT_OK));
}
if get64(&sb, SB_NUM_DEVICES) != 1 {
return Err(String::from("multi-device file systems are not supported"));
}
let sectorsize = get32(&sb, SB_SECTORSIZE) as usize;
let nodesize = get32(&sb, SB_NODESIZE) as usize;
if !sectorsize.is_power_of_two() || sectorsize < SECTOR_SIZE || !nodesize.is_power_of_two() || nodesize < sectorsize {
return Err(format!("odd sizes: sector {} node {}", sectorsize, nodesize));
}
let fsid_at = if incompat & INCOMPAT_METADATA_UUID != 0 { SB_METADATA_UUID } else { SB_FSID };
let label_bytes = &sb[SB_LABEL..SB_LABEL + 256];
let label_len = label_bytes.iter().position(|&b| b == 0).unwrap_or(256);
let mut vol = Volume {
dev,
sectorsize,
nodesize,
metadata_fsid: sb[fsid_at..fsid_at + 16].try_into().unwrap(),
label: String::from_utf8_lossy(&label_bytes[..label_len]).into_owned(),
generation: get64(&sb, SB_GENERATION),
total_bytes: get64(&sb, SB_TOTAL_BYTES),
bytes_used: get64(&sb, SB_BYTES_USED),
chunks: Vec::new(),
root_tree: Tree { bytenr: get64(&sb, SB_ROOT), level: sb[SB_ROOT_LEVEL] },
csum_tree: None,
default_subvol: FS_TREE,
fs_trees: BTreeMap::new(),
node_cache: Vec::new(),
extent_cache: None,
};
let devid = get64(&sb, SB_DEV_ITEM);
let array_len = (get32(&sb, SB_SYS_CHUNK_ARRAY_SIZE) as usize).min(2048);
let array = &sb[SB_SYS_CHUNK_ARRAY..SB_SYS_CHUNK_ARRAY + array_len];
let mut at = 0;
while at + 17 + 48 <= array.len() {
let key = Key::parse(array, at);
let size = 48 + 32 * get16(array, at + 17 + 44) as usize;
if key.kind != CHUNK_ITEM || at + 17 + size > array.len() {
return Err(String::from("bad sys_chunk_array"));
}
vol.add_chunk(key.offset, &array[at + 17..at + 17 + size], devid)?;
at += 17 + size;
}
let chunk_tree = Tree { bytenr: get64(&sb, SB_CHUNK_ROOT), level: sb[SB_CHUNK_ROOT_LEVEL] };
let all = Key::new(FIRST_CHUNK_TREE, CHUNK_ITEM, 0)..=Key::new(FIRST_CHUNK_TREE, CHUNK_ITEM, u64::MAX);
let items = vol.range(chunk_tree, *all.start(), *all.end()).map_err(|e| format!("can't read the chunk tree: {:?}", e))?;
vol.chunks.clear();
for (key, data) in items {
vol.add_chunk(key.offset, &data, devid)?;
}
vol.csum_tree = vol.root_of(CSUM_TREE).ok().map(|(tree, _)| tree);
let default = Key::new(ROOT_TREE_DIR, DIR_ITEM, name_hash(b"default"));
if let Ok(Some(data)) = vol.get(vol.root_tree, default) {
if let Some(entry) = parse_dir_items(&data).into_iter().find(|e| e.name == b"default") {
vol.default_subvol = entry.location.objectid;
}
}
vol.fs_tree(vol.default_subvol).map_err(|e| format!("can't find the default subvolume: {:?}", e))?;
Ok(vol)
}
fn add_chunk(&mut self, logical: u64, data: &[u8], devid: u64) -> Result<(), String> {
let kind = get64(data, 24);
let profile = kind & BG_PROFILES;
if profile != 0 && profile != BG_DUP {
return Err(format!("chunk at {} uses a RAID profile ({:#x}); only single and DUP are supported", logical, profile));
}
let stripes = get16(data, 44) as usize;
let mut copies = Vec::new();
for s in 0..stripes {
let at = 48 + 32 * s;
if get64(data, at) != devid {
return Err(format!("chunk at {} is on another device", logical));
}
copies.push(get64(data, at + 8));
}
self.chunks.push(Chunk { logical, length: get64(data, 0), kind, copies });
Ok(())
}
fn chunk(&self, logical: u64) -> Result<(&Chunk, u64), Errno> {
self.chunks
.iter()
.find(|c| logical >= c.logical && logical - c.logical < c.length)
.map(|c| (c, logical - c.logical))
.ok_or(Errno::EIO)
}
fn read_logical(&self, logical: u64, len: usize, copy: usize) -> Result<Vec<u8>, Errno> {
let (chunk, into) = self.chunk(logical)?;
if into + len as u64 > chunk.length {
return Err(Errno::EIO);
}
let physical = chunk.copies.get(copy).ok_or(Errno::EIO)? + into;
let skip = (physical % SECTOR_SIZE as u64) as usize;
let mut buf = vec![0u8; (skip + len).next_multiple_of(SECTOR_SIZE)];
self.dev.read_sectors(physical / SECTOR_SIZE as u64, &mut buf)?;
if skip != 0 || buf.len() != len {
buf = buf[skip..skip + len].to_vec();
}
Ok(buf)
}
fn copies(&self, logical: u64) -> usize {
self.chunk(logical).map(|(c, _)| c.copies.len()).unwrap_or(1)
}
fn read_node(&mut self, bytenr: u64) -> Result<Arc<Vec<u8>>, Errno> {
if let Some(i) = self.node_cache.iter().position(|(b, _)| *b == bytenr) {
let entry = self.node_cache.remove(i);
let node = entry.1.clone();
self.node_cache.push(entry);
return Ok(node);
}
for copy in 0..self.copies(bytenr) {
let node = self.read_logical(bytenr, self.nodesize, copy)?;
let (stored, computed) = (get32(&node, 0), crc32c(&node[0x20..]));
let problem = if stored != computed {
format!("bad checksum {:#010x}, should be {:#010x}", stored, computed)
} else if get64(&node, HDR_BYTENR) != bytenr {
format!("header says it's node {}", get64(&node, HDR_BYTENR))
} else if node[HDR_FSID..HDR_FSID + 16] != self.metadata_fsid {
String::from("it belongs to another file system")
} else {
if copy > 0 {
crate::kprintln!("[btrfs] node {}: copy 0 was bad, copy {} is good", bytenr, copy);
}
let node = Arc::new(node);
if self.node_cache.len() >= (NODE_CACHE_BYTES / self.nodesize).max(2) {
self.node_cache.remove(0);
}
self.node_cache.push((bytenr, node.clone()));
return Ok(node);
};
crate::kprintln!("[btrfs] node {} copy {}: {}", bytenr, copy, problem);
}
Err(Errno::EIO)
}
fn range(&mut self, tree: Tree, min: Key, max: Key) -> Result<Vec<(Key, Vec<u8>)>, Errno> {
let mut out = Vec::new();
self.walk(tree.bytenr, tree.level, min, max, &mut out)?;
Ok(out)
}
fn walk(&mut self, bytenr: u64, level: u8, min: Key, max: Key, out: &mut Vec<(Key, Vec<u8>)>) -> Result<(), Errno> {
let node = self.read_node(bytenr)?;
if node[HDR_LEVEL] != level {
crate::kprintln!("[btrfs] node {} has level {}, expected {}", bytenr, node[HDR_LEVEL], level);
return Err(Errno::EIO);
}
let n = get32(&node, HDR_NRITEMS) as usize;
if level == 0 {
for i in 0..n.min((self.nodesize - HEADER_SIZE) / ITEM_SIZE) {
let at = HEADER_SIZE + i * ITEM_SIZE;
let key = Key::parse(&node, at);
if key > max {
break;
}
if key >= min {
let (off, size) = (get32(&node, at + 17) as usize, get32(&node, at + 21) as usize);
let data = node.get(HEADER_SIZE + off..HEADER_SIZE + off + size).ok_or(Errno::EIO)?;
out.push((key, data.to_vec()));
}
}
return Ok(());
}
let n = n.min((self.nodesize - HEADER_SIZE) / KEY_PTR_SIZE);
for i in 0..n {
let at = HEADER_SIZE + i * KEY_PTR_SIZE;
if Key::parse(&node, at) > max {
break;
}
if i + 1 < n && Key::parse(&node, at + KEY_PTR_SIZE) <= min {
continue; }
self.walk(get64(&node, at + 17), level - 1, min, max, out)?;
}
Ok(())
}
fn search_le(&mut self, tree: Tree, key: Key) -> Result<Option<(Key, Vec<u8>)>, Errno> {
let (mut bytenr, mut level) = (tree.bytenr, tree.level);
loop {
let node = self.read_node(bytenr)?;
if node[HDR_LEVEL] != level {
return Err(Errno::EIO);
}
let n = get32(&node, HDR_NRITEMS) as usize;
let size = if level == 0 { ITEM_SIZE } else { KEY_PTR_SIZE };
let Some(i) = (0..n.min((self.nodesize - HEADER_SIZE) / size))
.take_while(|&i| Key::parse(&node, HEADER_SIZE + i * size) <= key)
.last()
else {
return Ok(None);
};
let at = HEADER_SIZE + i * size;
if level == 0 {
let (off, len) = (get32(&node, at + 17) as usize, get32(&node, at + 21) as usize);
let data = node.get(HEADER_SIZE + off..HEADER_SIZE + off + len).ok_or(Errno::EIO)?;
return Ok(Some((Key::parse(&node, at), data.to_vec())));
}
bytenr = get64(&node, at + 17);
level -= 1;
}
}
fn get(&mut self, tree: Tree, key: Key) -> Result<Option<Vec<u8>>, Errno> {
Ok(self.search_le(tree, key)?.filter(|(k, _)| *k == key).map(|(_, d)| d))
}
fn root_of(&mut self, id: u64) -> Result<(Tree, u64), Errno> {
let (key, item) = self.search_le(self.root_tree, Key::new(id, ROOT_ITEM, u64::MAX))?.ok_or(Errno::ENOENT)?;
if key.objectid != id || key.kind != ROOT_ITEM || item.len() <= ROOT_LEVEL {
return Err(Errno::ENOENT);
}
Ok((Tree { bytenr: get64(&item, ROOT_BYTENR), level: item[ROOT_LEVEL] }, get64(&item, ROOT_DIRID)))
}
fn fs_tree(&mut self, subvol: u64) -> Result<(Tree, u64), Errno> {
if let Some(t) = self.fs_trees.get(&subvol) {
return Ok(*t);
}
let t = self.root_of(subvol)?;
self.fs_trees.insert(subvol, t);
Ok(t)
}
fn inode(&mut self, loc: Loc) -> Result<InodeItem, Errno> {
let (tree, _) = self.fs_tree(loc.root)?;
let d = self.get(tree, Key::new(loc.ino, INODE_ITEM, 0))?.ok_or(Errno::ENOENT)?;
if d.len() < 160 {
return Err(Errno::EIO);
}
Ok(InodeItem { size: get64(&d, INODE_SIZE), mode: get32(&d, INODE_MODE), flags: get64(&d, INODE_FLAGS) })
}
fn follow(&mut self, dir: Loc, entry: &DirItem) -> Result<Loc, Errno> {
if entry.location.kind == ROOT_ITEM {
let (_, top) = self.fs_tree(entry.location.objectid)?;
Ok(Loc { root: entry.location.objectid, ino: top })
} else {
Ok(Loc { root: dir.root, ino: entry.location.objectid })
}
}
fn lookup(&mut self, dir: Loc, name: &str) -> Result<Loc, Errno> {
let (tree, _) = self.fs_tree(dir.root)?;
let data = self.get(tree, Key::new(dir.ino, DIR_ITEM, name_hash(name.as_bytes())))?.ok_or(Errno::ENOENT)?;
let entry = parse_dir_items(&data).into_iter().find(|e| e.name == name.as_bytes()).ok_or(Errno::ENOENT)?;
self.follow(dir, &entry)
}
fn list(&mut self, dir: Loc) -> Result<Vec<DirItem>, Errno> {
let (tree, _) = self.fs_tree(dir.root)?;
let items = self.range(tree, Key::new(dir.ino, DIR_INDEX, 0), Key::new(dir.ino, DIR_INDEX, u64::MAX))?;
Ok(items.iter().flat_map(|(_, d)| parse_dir_items(d)).collect())
}
fn read_file(&mut self, loc: Loc, pos: u64, buf: &mut [u8]) -> Result<usize, Errno> {
let inode = self.inode(loc)?;
if pos >= inode.size {
return Ok(0);
}
let n = (buf.len() as u64).min(inode.size - pos) as usize;
let buf = &mut buf[..n];
buf.fill(0); let verify = inode.flags & INODE_NODATASUM == 0;
let (tree, _) = self.fs_tree(loc.root)?;
let first = match self.search_le(tree, Key::new(loc.ino, EXTENT_DATA, pos))? {
Some((k, _)) if k.objectid == loc.ino && k.kind == EXTENT_DATA => k.offset,
_ => 0,
};
let end = pos + n as u64;
for (key, data) in self.range(tree, Key::new(loc.ino, EXTENT_DATA, first), Key::new(loc.ino, EXTENT_DATA, end - 1))? {
let ext = Extent::parse(&data)?;
let (from, to) = (key.offset.max(pos), (key.offset + ext.len()).min(end));
if from >= to {
continue;
}
let dst = &mut buf[(from - pos) as usize..(to - pos) as usize];
let skip = (from - key.offset) as usize; match ext {
Extent::Prealloc { .. } => {} Extent::Inline { compression: 0, data, .. } => {
let src = data.get(skip..skip + dst.len()).ok_or(Errno::EIO)?;
dst.copy_from_slice(src);
}
Extent::Inline { compression, data, ram_bytes } => {
let plain = decompress(compression, data, ram_bytes as usize, self.sectorsize)?;
dst.copy_from_slice(&plain[skip..skip + dst.len()]);
}
Extent::Regular { disk_bytenr: 0, .. } => {} Extent::Regular { compression: 0, disk_bytenr, offset, .. } => {
self.read_data(disk_bytenr + offset + skip as u64, dst, verify)?;
}
Extent::Regular { compression, disk_bytenr, disk_num_bytes, offset, ram_bytes, .. } => {
let plain = self.decompressed(compression, disk_bytenr, disk_num_bytes, ram_bytes, verify)?;
let at = offset as usize + skip;
dst.copy_from_slice(plain.get(at..at + dst.len()).ok_or(Errno::EIO)?);
}
}
}
Ok(n)
}
fn decompressed(&mut self, compression: u8, bytenr: u64, disk_len: u64, ram: u64, verify: bool) -> Result<Arc<Vec<u8>>, Errno> {
if let Some((b, data)) = &self.extent_cache {
if *b == bytenr {
return Ok(data.clone());
}
}
let mut raw = vec![0u8; disk_len as usize];
self.read_data(bytenr, &mut raw, verify)?;
let plain = Arc::new(decompress(compression, &raw, ram as usize, self.sectorsize)?);
self.extent_cache = Some((bytenr, plain.clone()));
Ok(plain)
}
fn read_data(&mut self, logical: u64, out: &mut [u8], verify: bool) -> Result<(), Errno> {
let ss = self.sectorsize as u64;
let start = logical / ss * ss;
let len = (logical + out.len() as u64).next_multiple_of(ss) - start;
let mut last_err = Errno::EIO;
for copy in 0..self.copies(start) {
let data = self.read_logical(start, len as usize, copy)?;
match if verify { self.verify_data(start, &data) } else { Ok(()) } {
Ok(()) => {
let skip = (logical - start) as usize;
out.copy_from_slice(&data[skip..skip + out.len()]);
return Ok(());
}
Err(e) => last_err = e,
}
}
Err(last_err)
}
fn verify_data(&mut self, start: u64, data: &[u8]) -> Result<(), Errno> {
let Some(tree) = self.csum_tree else { return Ok(()) };
let ss = self.sectorsize;
let mut item: Option<(u64, Vec<u8>)> = None;
for (i, sector) in data.chunks(ss).enumerate() {
let at = start + (i * ss) as u64;
let covers = |it: &Option<(u64, Vec<u8>)>| matches!(it, Some((s, d)) if at >= *s && at < s + (d.len() / 4 * ss) as u64);
if !covers(&item) {
item = match self.search_le(tree, Key::new(CSUM_OBJECTID, EXTENT_CSUM, at))? {
Some((k, d)) if k.objectid == CSUM_OBJECTID && k.kind == EXTENT_CSUM => Some((k.offset, d)),
_ => None,
};
if !covers(&item) {
continue; }
}
let (s, d) = item.as_ref().unwrap();
let want = get32(d, ((at - s) / ss as u64) as usize * 4);
let got = crc32c(sector);
if got != want {
crate::kprintln!("[btrfs] data at {}: checksum {:#010x}, should be {:#010x}", at, got, want);
return Err(Errno::EIO);
}
}
Ok(())
}
fn path_in(&mut self, root: u64, mut ino: u64) -> Result<String, Errno> {
let (tree, top) = self.fs_tree(root)?;
let mut parts = Vec::new();
while ino != top {
let refs = self.range(tree, Key::new(ino, INODE_REF, 0), Key::new(ino, INODE_REF, u64::MAX))?;
let (key, d) = refs.first().ok_or(Errno::EIO)?;
let len = get16(d, 8) as usize;
parts.push(String::from_utf8_lossy(d.get(10..10 + len).ok_or(Errno::EIO)?).into_owned());
ino = key.offset; }
parts.reverse();
Ok(parts.join("/"))
}
fn subvolumes(&mut self) -> Result<Vec<Subvolume>, Errno> {
let all = self.range(self.root_tree, Key::new(0, 0, 0), Key::new(u64::MAX, u8::MAX, u64::MAX))?;
let refs: Vec<(u64, u64, u64, String)> = all
.iter()
.filter(|(k, d)| k.kind == ROOT_REF && d.len() >= 18)
.map(|(k, d)| {
let len = get16(d, 16) as usize;
(k.objectid, k.offset, get64(d, 0), String::from_utf8_lossy(&d[18..(18 + len).min(d.len())]).into_owned())
})
.collect();
let mut out = Vec::new();
for (parent, child, dirid, name) in &refs {
let mut path = self.path_in(*parent, *dirid)?;
let mut p = *parent;
while let Some((pp, _, pdir, pname)) = refs.iter().find(|r| r.1 == p) {
let above = self.path_in(*pp, *pdir)?;
path = [above, pname.clone(), path].iter().filter(|s| !s.is_empty()).cloned().collect::<Vec<_>>().join("/");
p = *pp;
}
let full = if path.is_empty() { name.clone() } else { format!("{}/{}", path, name) };
let read_only = all
.iter()
.rev()
.find(|(k, _)| k.objectid == *child && k.kind == ROOT_ITEM)
.map(|(_, d)| d.len() > ROOT_FLAGS && get64(d, ROOT_FLAGS) & ROOT_RDONLY != 0)
.unwrap_or(false);
out.push(Subvolume { id: *child, path: full, read_only });
}
Ok(out)
}
fn profile(&self, what: u64) -> &'static str {
match self.chunks.iter().find(|c| c.kind & what != 0) {
Some(c) if c.kind & BG_DUP != 0 => "DUP",
Some(_) => "single",
None => "none",
}
}
}
fn parse_dir_items(mut d: &[u8]) -> Vec<DirItem> {
let mut out = Vec::new();
while d.len() >= 30 {
let (data_len, name_len) = (get16(d, 25) as usize, get16(d, 27) as usize);
let Some(name) = d.get(30..30 + name_len) else { break };
out.push(DirItem { location: Key::parse(d, 0), name: name.to_vec(), file_type: d[29] });
d = d.get(30 + name_len + data_len..).unwrap_or(&[]);
}
out
}
fn kind_of_mode(mode: u32) -> InodeKind {
match mode & S_IFMT {
S_IFDIR => InodeKind::Directory,
S_IFLNK => InodeKind::Symlink,
_ => InodeKind::File,
}
}
pub struct BtrfsFs {
vol: Arc<Mutex<Volume>>,
root: Loc,
}
impl BtrfsFs {
pub fn mount(dev: Arc<dyn BlockDevice>) -> Result<Arc<BtrfsFs>, String> {
let mut vol = Volume::open(dev)?;
let (_, top) = vol.fs_tree(vol.default_subvol).map_err(|e| format!("{:?}", e))?;
let root = Loc { root: vol.default_subvol, ino: top };
Ok(Arc::new(BtrfsFs { vol: Arc::new(Mutex::new(vol)), root }))
}
pub fn describe(&self) -> String {
let mut v = self.vol.lock();
let subvols = v.subvolumes().map(|s| s.len()).unwrap_or(0);
format!(
"btrfs volume \"{}\" ({} KiB nodes, metadata {}, data {}, {} subvolume{}, read-only)",
v.label,
v.nodesize / 1024,
v.profile(BG_METADATA | BG_SYSTEM),
v.profile(BG_DATA),
subvols,
if subvols == 1 { "" } else { "s" }
)
}
pub fn label(&self) -> String {
self.vol.lock().label.clone()
}
pub fn geometry(&self) -> (usize, usize, u64, u64, u64) {
let v = self.vol.lock();
(v.sectorsize, v.nodesize, v.generation, v.total_bytes, v.bytes_used)
}
pub fn subvolumes(&self) -> Result<Vec<Subvolume>, Errno> {
self.vol.lock().subvolumes()
}
pub fn physical(&self, logical: u64) -> Vec<u64> {
let v = self.vol.lock();
v.chunk(logical).map(|(c, into)| c.copies.iter().map(|p| p + into).collect()).unwrap_or_default()
}
pub fn fs_tree_root(&self) -> u64 {
let mut v = self.vol.lock();
let id = v.default_subvol;
v.fs_tree(id).map(|(t, _)| t.bytenr).unwrap_or(0)
}
pub fn first_extent(&self, path: &str) -> Result<u64, Errno> {
let mut v = self.vol.lock();
let mut loc = self.root;
for name in path.split('/').filter(|n| !n.is_empty()) {
loc = v.lookup(loc, name)?;
}
let (tree, _) = v.fs_tree(loc.root)?;
for (_, data) in v.range(tree, Key::new(loc.ino, EXTENT_DATA, 0), Key::new(loc.ino, EXTENT_DATA, u64::MAX))? {
if let Extent::Regular { disk_bytenr, .. } = Extent::parse(&data)? {
if disk_bytenr != 0 {
return Ok(disk_bytenr);
}
}
}
Err(Errno::ENOENT)
}
}
impl FileSystem for BtrfsFs {
fn name(&self) -> &'static str {
"btrfs"
}
fn root(&self) -> Arc<dyn Inode> {
Arc::new(BtrfsInode { vol: self.vol.clone(), loc: self.root, kind: InodeKind::Directory })
}
}
pub struct BtrfsInode {
vol: Arc<Mutex<Volume>>,
loc: Loc,
kind: InodeKind,
}
impl BtrfsInode {
fn dir_only(&self) -> Result<(), Errno> {
if self.kind == InodeKind::Directory { Ok(()) } else { Err(Errno::ENOTDIR) }
}
}
impl Inode for BtrfsInode {
fn kind(&self) -> InodeKind {
self.kind
}
fn size(&self) -> usize {
if self.kind == InodeKind::Directory {
return self.list().map(|l| l.len()).unwrap_or(0);
}
self.vol.lock().inode(self.loc).map(|i| i.size as usize).unwrap_or(0)
}
fn mode(&self) -> u32 {
self.vol.lock().inode(self.loc).map(|i| i.mode & 0o7777).unwrap_or(0)
}
fn readlink(&self) -> Result<String, Errno> {
if self.kind != InodeKind::Symlink {
return Err(Errno::EINVAL);
}
let mut vol = self.vol.lock();
let size = vol.inode(self.loc)?.size as usize;
let mut buf = vec![0u8; size];
let n = vol.read_file(self.loc, 0, &mut buf)?;
String::from_utf8(buf[..n].to_vec()).map_err(|_| Errno::EINVAL)
}
fn read_at(&self, offset: usize, buf: &mut [u8]) -> Result<usize, Errno> {
if self.kind == InodeKind::Directory {
return Err(Errno::EISDIR);
}
self.vol.lock().read_file(self.loc, offset as u64, buf)
}
fn lookup(&self, name: &str) -> Result<Arc<dyn Inode>, Errno> {
self.dir_only()?;
let mut vol = self.vol.lock();
let loc = vol.lookup(self.loc, name)?;
let kind = kind_of_mode(vol.inode(loc)?.mode);
Ok(Arc::new(BtrfsInode { vol: self.vol.clone(), loc, kind }))
}
fn list(&self) -> Result<Vec<DirEntry>, Errno> {
self.dir_only()?;
let entries = self.vol.lock().list(self.loc)?;
Ok(entries
.into_iter()
.map(|e| DirEntry {
name: String::from_utf8_lossy(&e.name).into_owned(),
kind: match e.file_type {
2 => InodeKind::Directory,
7 => InodeKind::Symlink,
_ => InodeKind::File,
},
})
.collect())
}
fn write_at(&self, _offset: usize, _buf: &[u8]) -> Result<usize, Errno> {
Err(Errno::EROFS)
}
fn truncate(&self) -> Result<(), Errno> {
Err(Errno::EROFS)
}
fn create(&self, _name: &str, _kind: InodeKind) -> Result<Arc<dyn Inode>, Errno> {
Err(Errno::EROFS)
}
fn remove(&self, _name: &str) -> Result<(), Errno> {
Err(Errno::EROFS)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test_case]
fn crc32c_known_answers() {
assert_eq!(crc32c(b"123456789"), 0xE306_9283); assert_eq!(name_hash(b"default"), 2378154706); }
#[test_case]
fn prealloc_and_hole_extents_read_as_nothing() {
let mut item = vec![0u8; EXT_REGULAR_SIZE];
item[EXT_TYPE] = 2;
item[EXT_NUM_BYTES..EXT_NUM_BYTES + 8].copy_from_slice(&8192u64.to_le_bytes());
assert!(matches!(Extent::parse(&item), Ok(Extent::Prealloc { num_bytes: 8192 })));
item[EXT_TYPE] = 1; assert!(matches!(Extent::parse(&item), Ok(Extent::Regular { disk_bytenr: 0, .. })));
item[EXT_ENCRYPTION] = 1;
assert!(Extent::parse(&item).is_err());
}
#[test_case]
fn lzo_literals_and_overlapping_match() {
let mut out = Vec::new();
super::super::lzo::decompress(&[20, b'a', b'b', b'c', 0xA8, 0, 0x11, 0, 0], &mut out, 100).unwrap();
assert_eq!(&out, b"abcabcabc");
}
}
|