nydus-rafs 0.2.1

The RAFS filesystem format for Nydus Image Service
Documentation
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
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
// Copyright 2020-2021 Ant Group. All rights reserved.
// Copyright (C) 2020-2021 Alibaba Cloud. All rights reserved.
//
// SPDX-License-Identifier: Apache-2.0

use std::convert::TryFrom;
use std::ffi::{OsStr, OsString};
use std::fmt::Debug;
use std::io::{Read, Result};
use std::mem::size_of;
use std::os::unix::ffi::OsStrExt;
use std::str::FromStr;
use std::sync::Arc;

use lazy_static::lazy_static;
use nydus_storage::device::{BlobFeatures, BlobInfo};
use nydus_storage::meta::{
    BlobChunkInfoV1Ondisk, BlobChunkInfoV2Ondisk, BlobCompressionContextHeader,
};
use nydus_storage::{RAFS_MAX_CHUNKS_PER_BLOB, RAFS_MAX_CHUNK_SIZE};
use nydus_utils::{compress, digest, round_up, ByteSize};

use crate::metadata::layout::v5::RafsV5ChunkInfo;
use crate::metadata::layout::MetaRange;
use crate::metadata::{layout::RafsXAttrs, RafsStore, RafsSuperFlags};
use crate::{impl_bootstrap_converter, impl_pub_getter_setter, RafsIoReader, RafsIoWrite};

/// EROFS metadata slot size.
pub const EROFS_INODE_SLOT_SIZE: usize = 1 << EROFS_INODE_SLOT_BITS;
/// EROFS logical block size.
pub const EROFS_BLOCK_SIZE: u64 = 1u64 << EROFS_BLOCK_BITS;
/// EROFS plain inode.
pub const EROFS_INODE_FLAT_PLAIN: u16 = 0;
/// EROFS inline inode.
pub const EROFS_INODE_FLAT_INLINE: u16 = 2;
/// EROFS chunked inode.
pub const EROFS_INODE_CHUNK_BASED: u16 = 4;
/// EROFS device table offset.
pub const EROFS_DEVTABLE_OFFSET: u16 =
    EROFS_SUPER_OFFSET + EROFS_SUPER_BLOCK_SIZE + EROFS_EXT_SUPER_BLOCK_SIZE;

pub const EROFS_I_VERSION_BIT: u16 = 0;
pub const EROFS_I_VERSION_BITS: u16 = 1;
pub const EROFS_I_DATALAYOUT_BITS: u16 = 3;

// Offset of EROFS super block.
pub const EROFS_SUPER_OFFSET: u16 = 1024;
// Size of EROFS super block.
pub const EROFS_SUPER_BLOCK_SIZE: u16 = 128;
// Size of extended super block, used for rafs v6 specific fields
const EROFS_EXT_SUPER_BLOCK_SIZE: u16 = 256;
// Magic number for EROFS super block.
const EROFS_SUPER_MAGIC_V1: u32 = 0xE0F5_E1E2;
// Bits of EROFS logical block size.
const EROFS_BLOCK_BITS: u8 = 12;
// Bits of EROFS metadata slot size.
const EROFS_INODE_SLOT_BITS: u8 = 5;
// 32-byte on-disk inode
const EROFS_INODE_LAYOUT_COMPACT: u16 = 0;
// 64-byte on-disk inode
const EROFS_INODE_LAYOUT_EXTENDED: u16 = 1;
// Bit flag indicating whether the inode is chunked or not.
const EROFS_CHUNK_FORMAT_INDEXES_FLAG: u16 = 0x0020;
// Encoded chunk size (log2(chunk_size) - EROFS_BLOCK_BITS).
const EROFS_CHUNK_FORMAT_SIZE_MASK: u16 = 0x001F;
/// Checksum of superblock, compatible with EROFS versions prior to Linux kernel 5.5.
#[allow(dead_code)]
const EROFS_FEATURE_COMPAT_SB_CHKSUM: u32 = 0x0000_0001;
/// Rafs v6 specific metadata, compatible with EROFS versions since Linux kernel 5.16.
const EROFS_FEATURE_COMPAT_RAFS_V6: u32 = 0x4000_0000;
/// Chunked inode, incompatible with EROFS versions prior to Linux kernel 5.15.
const EROFS_FEATURE_INCOMPAT_CHUNKED_FILE: u32 = 0x0000_0004;
/// Multi-devices, incompatible with EROFS versions prior to Linux kernel 5.16.
const EROFS_FEATURE_INCOMPAT_DEVICE_TABLE: u32 = 0x0000_0008;
/// Size of SHA256 digest string.
const BLOB_SHA256_LEN: usize = 64;
const BLOB_MAX_SIZE_UNCOMPRESSED: u64 = 1u64 << 44;
const BLOB_MAX_SIZE_COMPRESSED: u64 = 1u64 << 40;

/// RAFS v6 superblock on-disk format, 128 bytes.
///
/// The structure is designed to be compatible with EROFS superblock, so the in kernel EROFS file
/// system driver could be used to mount a RAFS v6 image.
#[repr(C)]
#[derive(Clone, Copy)]
pub struct RafsV6SuperBlock {
    /// File system magic number
    s_magic: u32,
    /// Crc32 checksum of the superblock, ignored by Rafs v6.
    s_checksum: u32,
    /// Compatible filesystem features.
    s_feature_compat: u32,
    /// Bits of block size. Only 12 is supported, thus block_size == PAGE_SIZE(4096).
    s_blkszbits: u8,
    /// Number of extended superblock slots, ignored by Rafs v6.
    /// `superblock size = 128(size of RafsV6SuperBlock) + s_extslots * 16`.
    s_extslots: u8,
    /// Nid of the root directory.
    /// `root inode offset = s_meta_blkaddr * 4096 + s_root_nid * 32`.
    pub s_root_nid: u16,
    /// Total valid ino #
    s_inos: u64,
    /// Timestamp of filesystem creation.
    s_build_time: u64,
    /// Timestamp of filesystem creation.
    s_build_time_nsec: u32,
    /// Total size of file system in blocks, used for statfs
    s_blocks: u32,
    /// Start block address of the metadata area.
    pub s_meta_blkaddr: u32,
    /// Start block address of the shared xattr area.
    s_xattr_blkaddr: u32,
    /// 128-bit uuid for volume
    s_uuid: [u8; 16],
    /// Volume name.
    s_volume_name: [u8; 16],
    /// Incompatible filesystem feature flags.
    s_feature_incompat: u32,
    /// A union of `u16` for miscellaneous usage.
    s_u: u16,
    /// # of devices besides the primary device.
    s_extra_devices: u16,
    /// Offset of the device table, `startoff = s_devt_slotoff * 128`.
    s_devt_slotoff: u16,
    /// Padding.
    s_reserved: [u8; 38],
}

impl_bootstrap_converter!(RafsV6SuperBlock);

impl RafsV6SuperBlock {
    /// Create a new instance of `RafsV6SuperBlock`.
    pub fn new() -> Self {
        Self::default()
    }

    /// Load a `RafsV6SuperBlock` from a reader.
    pub fn load(&mut self, r: &mut RafsIoReader) -> Result<()> {
        let mut buf1 = [0u8; EROFS_SUPER_OFFSET as usize];

        r.read_exact(&mut buf1)?;
        r.read_exact(self.as_mut())
    }

    /// Validate the Rafs v6 super block.
    pub fn validate(&self, meta_size: u64) -> Result<()> {
        if meta_size < EROFS_BLOCK_SIZE {
            return Err(einval!(format!(
                "invalid Rafs v6 metadata size: {}",
                meta_size
            )));
        }

        if meta_size & (EROFS_BLOCK_SIZE - 1) != 0 {
            return Err(einval!(format!(
                "invalid Rafs v6 metadata size: bootstrap size {} is not aligned",
                meta_size
            )));
        }

        if u32::from_le(self.s_magic) != EROFS_SUPER_MAGIC_V1 {
            return Err(einval!(format!(
                "invalid EROFS magic number 0x{:x} in Rafsv6 superblock",
                u32::from_le(self.s_magic)
            )));
        }

        if self.s_checksum != 0 {
            return Err(einval!(format!(
                "invalid checksum {} in Rafsv6 superblock",
                u32::from_le(self.s_checksum)
            )));
        }

        if self.s_blkszbits != EROFS_BLOCK_BITS {
            return Err(einval!(format!(
                "invalid block size bits {} in Rafsv6 superblock",
                self.s_blkszbits
            )));
        }

        if self.s_inos == 0 {
            return Err(einval!("invalid inode number in Rafsv6 superblock"));
        }

        if self.s_extslots != 0 {
            return Err(einval!("invalid extended slots in Rafsv6 superblock"));
        }

        if self.s_u != 0 {
            return Err(einval!("invalid union field in Rafsv6 superblock"));
        }

        if self.s_xattr_blkaddr != 0 {
            return Err(einval!(
                "unsupported shared extended attribute namespace in Rafsv6 superblock"
            ));
        }

        // There's a bug in old RAFS v6 images, which has set s_blocks to a fixed value 4096.
        if self.s_extra_devices == 0 && self.s_blocks != 0 && u32::from_le(self.s_blocks) != 4096 {
            warn!(
                "rafs v6 extra devices {}, blocks {}",
                self.s_extra_devices, self.s_blocks
            );
            return Err(einval!("invalid extra device count in Rafsv6 superblock"));
        }

        if u16::from_le(self.s_devt_slotoff)
            != (EROFS_DEVTABLE_OFFSET / size_of::<RafsV6Device>() as u16)
        {
            return Err(einval!(format!(
                "invalid device table slot offset {} in Rafsv6 superblock",
                u16::from_le(self.s_devt_slotoff)
            )));
        }

        // s_build_time may be used as compact_inode's timestamp in the future.
        // if u64::from_le(self.s_build_time) != 0 || u32::from_le(self.s_build_time_nsec) != 0 {
        //     return Err(einval!("invalid build time in Rafsv6 superblock"));
        // }

        if u32::from_le(self.s_feature_incompat)
            != EROFS_FEATURE_INCOMPAT_CHUNKED_FILE | EROFS_FEATURE_INCOMPAT_DEVICE_TABLE
        {
            return Err(einval!(
                "invalid incompatible feature bits in Rafsv6 superblock"
            ));
        }

        if u32::from_le(self.s_feature_compat) & EROFS_FEATURE_COMPAT_RAFS_V6
            != EROFS_FEATURE_COMPAT_RAFS_V6
        {
            return Err(einval!(
                "invalid compatible feature bits in Rafsv6 superblock"
            ));
        }

        Ok(())
    }

    /// Check whether it's super block for Rafs v6.
    pub fn is_rafs_v6(&self) -> bool {
        self.magic() == EROFS_SUPER_MAGIC_V1
    }

    /// Set number of inodes.
    pub fn set_inos(&mut self, inos: u64) {
        self.s_inos = inos.to_le();
    }

    /// Get total inodes count of this Rafs
    pub fn inodes_count(&self) -> u64 {
        u64::from_le(self.s_inos)
    }

    /// Set number of logical blocks.
    pub fn set_blocks(&mut self, blocks: u32) {
        self.s_blocks = blocks.to_le();
    }

    /// Set EROFS root nid.
    pub fn set_root_nid(&mut self, nid: u16) {
        self.s_root_nid = nid.to_le();
    }

    /// Set EROFS meta block address.
    pub fn set_meta_addr(&mut self, meta_addr: u64) {
        assert!((meta_addr / EROFS_BLOCK_SIZE) <= u32::MAX as u64);
        self.s_meta_blkaddr = u32::to_le((meta_addr / EROFS_BLOCK_SIZE) as u32);
    }

    /// Set number of extra devices.
    pub fn set_extra_devices(&mut self, count: u16) {
        self.s_extra_devices = count.to_le();
    }

    impl_pub_getter_setter!(magic, set_magic, s_magic, u32);
}

impl RafsStore for RafsV6SuperBlock {
    // This method must be called before RafsV6SuperBlockExt::store(), otherwise data written by
    // RafsV6SuperBlockExt::store() will be overwritten.
    fn store(&self, w: &mut dyn RafsIoWrite) -> Result<usize> {
        debug_assert!(((EROFS_SUPER_OFFSET + EROFS_SUPER_BLOCK_SIZE) as u64) < EROFS_BLOCK_SIZE);
        w.write_all(&[0u8; EROFS_SUPER_OFFSET as usize])?;
        w.write_all(self.as_ref())?;
        w.write_all(
            &[0u8; (EROFS_BLOCK_SIZE as usize
                - (EROFS_SUPER_OFFSET + EROFS_SUPER_BLOCK_SIZE) as usize)],
        )?;

        Ok(EROFS_BLOCK_SIZE as usize)
    }
}

impl Default for RafsV6SuperBlock {
    fn default() -> Self {
        debug_assert!(size_of::<RafsV6Device>() == 128);
        Self {
            s_magic: u32::to_le(EROFS_SUPER_MAGIC_V1),
            s_checksum: 0,
            s_feature_compat: u32::to_le(EROFS_FEATURE_COMPAT_RAFS_V6),
            s_blkszbits: EROFS_BLOCK_BITS,
            s_extslots: 0u8,
            s_root_nid: 0,
            s_inos: 0,
            s_build_time: 0,
            s_build_time_nsec: 0,
            s_blocks: u32::to_le(1),
            s_meta_blkaddr: 0,
            s_xattr_blkaddr: 0,
            s_uuid: [0u8; 16],
            s_volume_name: [0u8; 16],
            s_feature_incompat: u32::to_le(
                EROFS_FEATURE_INCOMPAT_CHUNKED_FILE | EROFS_FEATURE_INCOMPAT_DEVICE_TABLE,
            ),
            s_u: 0,
            s_extra_devices: 0,
            s_devt_slotoff: u16::to_le(EROFS_DEVTABLE_OFFSET / size_of::<RafsV6Device>() as u16),
            s_reserved: [0u8; 38],
        }
    }
}

/// Extended superblock for RAFS v6, 256 bytes
#[repr(C)]
#[derive(Clone, Copy)]
pub struct RafsV6SuperBlockExt {
    /// superblock flags
    s_flags: u64,
    /// offset of blob table
    s_blob_table_offset: u64,
    /// size of blob table
    s_blob_table_size: u32,
    /// chunk size
    s_chunk_size: u32,
    /// offset of chunk table
    s_chunk_table_offset: u64,
    /// size of chunk table
    s_chunk_table_size: u64,
    s_prefetch_table_offset: u64,
    s_prefetch_table_size: u32,
    s_padding: u32,
    /// Reserved
    s_reserved: [u8; 200],
}

impl_bootstrap_converter!(RafsV6SuperBlockExt);

impl RafsV6SuperBlockExt {
    /// Create a new instance `RafsV6SuperBlockExt`.
    pub fn new() -> Self {
        debug_assert!(size_of::<Self>() == 256);
        Self::default()
    }

    /// Load an `RafsV6SuperBlockExt` from a reader.
    pub fn load(&mut self, r: &mut RafsIoReader) -> Result<()> {
        r.seek_to_offset((EROFS_SUPER_OFFSET + EROFS_SUPER_BLOCK_SIZE) as u64)?;
        r.read_exact(self.as_mut())?;
        r.seek_to_offset(EROFS_BLOCK_SIZE as u64)?;

        Ok(())
    }

    /// Validate the Rafs v6 super block.
    pub fn validate(&self, meta_size: u64) -> Result<()> {
        let mut flags = self.flags();
        flags &= RafsSuperFlags::COMPRESSION_NONE.bits()
            | RafsSuperFlags::COMPRESSION_LZ4.bits()
            | RafsSuperFlags::COMPRESSION_GZIP.bits()
            | RafsSuperFlags::COMPRESSION_ZSTD.bits();
        if flags.count_ones() != 1 {
            return Err(einval!(format!(
                "invalid flags {:#x} related to compression algorithm in Rafs v6 extended superblock",
                flags
            )));
        }

        let mut flags = self.flags();
        flags &= RafsSuperFlags::HASH_BLAKE3.bits() | RafsSuperFlags::HASH_SHA256.bits();
        if flags.count_ones() != 1 {
            return Err(einval!(format!(
                "invalid flags {:#x} related to digest algorithm in Rafs v6 extended superblock",
                flags
            )));
        }

        let chunk_size = u32::from_le(self.s_chunk_size) as u64;
        if !chunk_size.is_power_of_two()
            || !(EROFS_BLOCK_SIZE..=RAFS_MAX_CHUNK_SIZE).contains(&chunk_size)
        {
            return Err(einval!("invalid chunk size in Rafs v6 extended superblock"));
        }

        let blob_offset = self.blob_table_offset();
        let blob_size = self.blob_table_size() as u64;
        if blob_offset & (EROFS_BLOCK_SIZE - 1) != 0
            || blob_offset < EROFS_BLOCK_SIZE
            || blob_size % size_of::<RafsV6Blob>() as u64 != 0
            || blob_offset.checked_add(blob_size).is_none()
            || blob_offset + blob_size > meta_size
        {
            return Err(einval!(format!(
                "invalid blob table offset 0x{:x}/size 0x{:x} in Rafs v6 extended superblock",
                blob_offset, blob_size
            )));
        }
        let blob_range = MetaRange::new(blob_offset, blob_size, true)?;

        if self.chunk_table_size() > 0 {
            let chunk_tbl_offset = self.chunk_table_offset();
            let chunk_tbl_size = self.chunk_table_size();
            if chunk_tbl_offset < EROFS_BLOCK_SIZE
                || chunk_tbl_offset % EROFS_BLOCK_SIZE != 0
                || chunk_tbl_size % size_of::<RafsV5ChunkInfo>() as u64 != 0
                || chunk_tbl_offset.checked_add(chunk_tbl_size).is_none()
                || chunk_tbl_offset + chunk_tbl_size > meta_size
            {
                return Err(einval!(format!(
                    "invalid chunk table offset 0x{:x}/size 0x{:x} in Rafs v6 extended superblock",
                    chunk_tbl_offset, chunk_tbl_size
                )));
            }
            let chunk_range = MetaRange::new(chunk_tbl_offset, chunk_tbl_size, true)?;
            if blob_range.intersect_with(&chunk_range) {
                return Err(einval!(format!(
                    "blob table intersects with chunk table in Rafs v6 extended superblock",
                )));
            }
        }

        // Legacy RAFS may have zero prefetch table offset but non-zero prefetch table size for
        // empty filesystems.
        if self.prefetch_table_size() > 0 && self.prefetch_table_offset() != 0 {
            let tbl_offset = self.prefetch_table_offset();
            let tbl_size = self.prefetch_table_size() as u64;
            if tbl_offset < EROFS_BLOCK_SIZE
                || tbl_size % size_of::<u32>() as u64 != 0
                || tbl_offset.checked_add(tbl_size).is_none()
                || tbl_offset + tbl_size > meta_size
            {
                return Err(einval!(format!(
                    "invalid prefetch table offset 0x{:x}/size 0x{:x} in Rafs v6 extended superblock",
                    tbl_offset, tbl_size
                )));
            }
            let prefetch_range = MetaRange::new(tbl_offset, tbl_size, false)?;
            if blob_range.intersect_with(&prefetch_range) {
                return Err(einval!(format!(
                    "blob table intersects with prefetch table in Rafs v6 extended superblock",
                )));
            }
        }

        Ok(())
    }

    /// Set compression algorithm to handle chunk of the Rafs filesystem.
    pub fn set_compressor(&mut self, compressor: compress::Algorithm) {
        let c: RafsSuperFlags = compressor.into();

        self.s_flags &= !RafsSuperFlags::COMPRESSION_NONE.bits();
        self.s_flags &= !RafsSuperFlags::COMPRESSION_LZ4.bits();
        self.s_flags &= !RafsSuperFlags::COMPRESSION_GZIP.bits();
        self.s_flags &= !RafsSuperFlags::COMPRESSION_ZSTD.bits();
        self.s_flags |= c.bits();
    }

    /// Set the `has_xattr` flag for the RAFS filesystem.
    pub fn set_has_xattr(&mut self) {
        self.s_flags |= RafsSuperFlags::HAS_XATTR.bits();
    }

    /// Enable explicit Uid/Gid feature.
    pub fn set_explicit_uidgid(&mut self) {
        self.s_flags |= RafsSuperFlags::EXPLICIT_UID_GID.bits();
    }

    /// Set flag indicating that chunk digest is inlined in the data blob.
    pub fn set_inlined_chunk_digest(&mut self) {
        self.s_flags |= RafsSuperFlags::INLINED_CHUNK_DIGEST.bits();
    }

    /// Set message digest algorithm to handle chunk of the Rafs filesystem.
    pub fn set_digester(&mut self, digester: digest::Algorithm) {
        let c: RafsSuperFlags = digester.into();

        self.s_flags &= !RafsSuperFlags::HASH_BLAKE3.bits();
        self.s_flags &= !RafsSuperFlags::HASH_SHA256.bits();
        self.s_flags |= c.bits();
    }

    /// Set offset and size of chunk information table.
    pub fn set_chunk_table(&mut self, offset: u64, size: u64) {
        self.set_chunk_table_offset(offset);
        self.set_chunk_table_size(size);
    }

    impl_pub_getter_setter!(
        chunk_table_offset,
        set_chunk_table_offset,
        s_chunk_table_offset,
        u64
    );
    impl_pub_getter_setter!(
        chunk_table_size,
        set_chunk_table_size,
        s_chunk_table_size,
        u64
    );
    impl_pub_getter_setter!(chunk_size, set_chunk_size, s_chunk_size, u32);
    impl_pub_getter_setter!(flags, set_flags, s_flags, u64);
    impl_pub_getter_setter!(
        blob_table_offset,
        set_blob_table_offset,
        s_blob_table_offset,
        u64
    );
    impl_pub_getter_setter!(blob_table_size, set_blob_table_size, s_blob_table_size, u32);
    impl_pub_getter_setter!(
        prefetch_table_size,
        set_prefetch_table_size,
        s_prefetch_table_size,
        u32
    );
    impl_pub_getter_setter!(
        prefetch_table_offset,
        set_prefetch_table_offset,
        s_prefetch_table_offset,
        u64
    );
}

impl RafsStore for RafsV6SuperBlockExt {
    fn store(&self, w: &mut dyn RafsIoWrite) -> Result<usize> {
        w.seek_offset((EROFS_SUPER_OFFSET + EROFS_SUPER_BLOCK_SIZE) as u64)?;
        w.write_all(self.as_ref())?;
        w.seek_offset(EROFS_BLOCK_SIZE as u64)?;

        Ok(EROFS_BLOCK_SIZE as usize - (EROFS_SUPER_OFFSET + EROFS_SUPER_BLOCK_SIZE) as usize)
    }
}

impl Default for RafsV6SuperBlockExt {
    fn default() -> Self {
        Self {
            s_flags: 0,
            s_blob_table_offset: 0,
            s_blob_table_size: 0,
            s_chunk_size: 0,
            s_chunk_table_offset: 0,
            s_chunk_table_size: 0,
            s_prefetch_table_offset: 0,
            s_prefetch_table_size: 0,
            s_padding: u32::to_le(0),
            s_reserved: [0u8; 200],
        }
    }
}

/// Type of EROFS inodes.
#[repr(u8)]
#[allow(non_camel_case_types, dead_code)]
enum EROFS_FILE_TYPE {
    /// Unknown file type.
    EROFS_FT_UNKNOWN,
    /// Regular file.
    EROFS_FT_REG_FILE,
    /// Directory.
    EROFS_FT_DIR,
    /// Character device.
    EROFS_FT_CHRDEV,
    /// Block device.
    EROFS_FT_BLKDEV,
    /// FIFO pipe.
    EROFS_FT_FIFO,
    /// Socket.
    EROFS_FT_SOCK,
    /// Symlink.
    EROFS_FT_SYMLINK,
    /// Maximum value of file type.
    EROFS_FT_MAX,
}

/// Trait to manipulate data fields of on-disk RAFS v6 inodes.
///
/// There are two types of on disk inode formats defined by EROFS:
/// - compact inode with 32-byte data
/// - extended inode with 64-byte data
pub trait RafsV6OndiskInode: RafsStore {
    fn set_size(&mut self, size: u64);
    fn set_ino(&mut self, ino: u32);
    fn set_nlink(&mut self, nlinks: u32);
    fn set_mode(&mut self, mode: u16);
    fn set_u(&mut self, u: u32);
    fn set_uidgid(&mut self, uid: u32, gid: u32);
    fn set_mtime(&mut self, _sec: u64, _nsec: u32);
    fn set_rdev(&mut self, rdev: u32);
    fn set_xattr_inline_count(&mut self, count: u16);
    fn set_data_layout(&mut self, data_layout: u16);

    /// Set inode data layout format to be PLAIN.
    #[inline]
    fn set_inline_plain_layout(&mut self) {
        self.set_data_layout(EROFS_INODE_FLAT_PLAIN);
    }

    /// Set inode data layout format to be INLINE.
    #[inline]
    fn set_inline_inline_layout(&mut self) {
        self.set_data_layout(EROFS_INODE_FLAT_INLINE);
    }

    /// Set inode data layout format to be CHUNKED.
    #[inline]
    fn set_chunk_based_layout(&mut self) {
        self.set_data_layout(EROFS_INODE_CHUNK_BASED);
    }

    fn format(&self) -> u16;
    fn mode(&self) -> u16;
    fn size(&self) -> u64;
    fn union(&self) -> u32;
    fn ino(&self) -> u32;
    fn ugid(&self) -> (u32, u32);
    fn mtime_s_ns(&self) -> (u64, u32);
    fn nlink(&self) -> u32;
    fn rdev(&self) -> u32;
    fn xattr_inline_count(&self) -> u16;

    fn load(&mut self, r: &mut RafsIoReader) -> Result<()>;
}

impl Debug for &dyn RafsV6OndiskInode {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        f.debug_struct("RafsV6OndiskInode")
            .field("format", &self.format())
            .field("ino", &self.ino())
            .field("mode", &self.mode())
            .field("size", &self.size())
            .field("union", &self.union())
            .field("nlink", &self.nlink())
            .field("xattr count", &self.xattr_inline_count())
            .finish()
    }
}

/// RAFS v6 inode on-disk format, 32 bytes.
///
/// This structure is designed to be compatible with EROFS compact inode format.
#[repr(C)]
#[derive(Clone, Copy, Default, Debug)]
pub struct RafsV6InodeCompact {
    /// inode format hints
    pub i_format: u16,
    pub i_xattr_icount: u16,
    pub i_mode: u16,
    pub i_nlink: u16,
    pub i_size: u32,
    pub i_reserved: u32,
    /// raw_blkaddr or rdev or rafs_v6_inode_chunk_info
    pub i_u: u32,
    pub i_ino: u32,
    pub i_uid: u16,
    pub i_gid: u16,
    pub i_reserved2: [u8; 4],
}

impl RafsV6InodeCompact {
    pub fn new() -> Self {
        Self {
            i_format: u16::to_le(EROFS_INODE_LAYOUT_COMPACT | (EROFS_INODE_FLAT_PLAIN << 1)),
            i_xattr_icount: 0,
            i_mode: 0,
            i_nlink: 0,
            i_size: 0,
            i_reserved: 0,
            i_u: 0,
            i_ino: 0,
            i_uid: 0,
            i_gid: 0,
            i_reserved2: [0u8; 4],
        }
    }
}

impl RafsV6OndiskInode for RafsV6InodeCompact {
    /// Set file size for inode.
    fn set_size(&mut self, size: u64) {
        self.i_size = u32::to_le(size as u32);
    }

    /// Set ino for inode.
    fn set_ino(&mut self, ino: u32) {
        self.i_ino = ino.to_le();
    }

    /// Set number of hardlink.
    fn set_nlink(&mut self, nlinks: u32) {
        self.i_nlink = u16::to_le(nlinks as u16);
    }

    /// Set file protection mode.
    fn set_mode(&mut self, mode: u16) {
        self.i_mode = mode.to_le();
    }

    /// Set the union field.
    fn set_u(&mut self, u: u32) {
        self.i_u = u.to_le();
    }

    /// Set uid and gid for the inode.
    fn set_uidgid(&mut self, uid: u32, gid: u32) {
        self.i_uid = u16::to_le(uid as u16);
        self.i_gid = u16::to_le(gid as u16);
    }

    /// Set last modification time for the inode.
    fn set_mtime(&mut self, _sec: u64, _nsec: u32) {}

    /// Set real device id.
    fn set_rdev(&mut self, _rdev: u32) {}

    /// Set xattr inline count.
    fn set_xattr_inline_count(&mut self, count: u16) {
        self.i_xattr_icount = count.to_le();
    }

    /// Set inode data layout format.
    fn set_data_layout(&mut self, data_layout: u16) {
        self.i_format = u16::to_le(EROFS_INODE_LAYOUT_COMPACT | (data_layout << 1));
    }

    fn format(&self) -> u16 {
        u16::from_le(self.i_format)
    }

    fn mode(&self) -> u16 {
        u16::from_le(self.i_mode)
    }

    fn size(&self) -> u64 {
        u32::from_le(self.i_size) as u64
    }

    fn union(&self) -> u32 {
        u32::from_le(self.i_u)
    }

    fn ino(&self) -> u32 {
        u32::from_le(self.i_ino)
    }

    fn ugid(&self) -> (u32, u32) {
        (
            u16::from_le(self.i_uid) as u32,
            u16::from_le(self.i_gid) as u32,
        )
    }

    fn mtime_s_ns(&self) -> (u64, u32) {
        (0, 0)
    }

    fn nlink(&self) -> u32 {
        u16::from_le(self.i_nlink) as u32
    }

    fn rdev(&self) -> u32 {
        0
    }

    fn xattr_inline_count(&self) -> u16 {
        u16::from_le(self.i_xattr_icount)
    }

    /// Load a `RafsV6InodeCompact` from a reader.
    fn load(&mut self, r: &mut RafsIoReader) -> Result<()> {
        r.read_exact(self.as_mut())
    }
}

impl_bootstrap_converter!(RafsV6InodeCompact);

impl RafsStore for RafsV6InodeCompact {
    fn store(&self, w: &mut dyn RafsIoWrite) -> Result<usize> {
        // TODO: need to write xattr as well.
        w.write_all(self.as_ref())?;
        Ok(self.as_ref().len())
    }
}

/// RAFS v6 inode on-disk format, 64 bytes.
///
/// This structure is designed to be compatible with EROFS extended inode format.
#[repr(C)]
#[derive(Clone, Copy, Default, Debug)]
pub struct RafsV6InodeExtended {
    /// Layout format for of the inode.
    pub i_format: u16,
    /// Size of extended attributes, in unit of 4Byte
    pub i_xattr_icount: u16,
    /// Protection mode.
    pub i_mode: u16,
    i_reserved: u16,
    /// Size of the file content.
    pub i_size: u64,
    /// A `u32` union: raw_blkaddr or `rdev` or `rafs_v6_inode_chunk_info`
    pub i_u: u32,
    /// Inode number.
    pub i_ino: u32,
    /// User ID of owner.
    pub i_uid: u32,
    /// Group ID of owner
    pub i_gid: u32,
    /// Time of last modification - second part.
    pub i_mtime: u64,
    /// Time of last modification - nanoseconds part.
    pub i_mtime_nsec: u32,
    /// Number of links.
    pub i_nlink: u32,
    i_reserved2: [u8; 16],
}

impl RafsV6InodeExtended {
    /// Create a new instance of `RafsV6InodeExtended`.
    pub fn new() -> Self {
        Self {
            i_format: u16::to_le(EROFS_INODE_LAYOUT_EXTENDED | (EROFS_INODE_FLAT_PLAIN << 1)),
            i_xattr_icount: 0,
            i_mode: 0,
            i_reserved: 0,
            i_size: 0,
            i_u: 0,
            i_ino: 0,
            i_uid: 0,
            i_gid: 0,
            i_mtime: 0,
            i_mtime_nsec: 0,
            i_nlink: 0,
            i_reserved2: [0u8; 16],
        }
    }
}

impl RafsV6OndiskInode for RafsV6InodeExtended {
    /// Set file size for inode.
    fn set_size(&mut self, size: u64) {
        self.i_size = size.to_le();
    }

    /// Set ino for inode.
    fn set_ino(&mut self, ino: u32) {
        self.i_ino = ino.to_le();
    }

    /// Set number of hardlink.
    fn set_nlink(&mut self, nlinks: u32) {
        self.i_nlink = nlinks.to_le();
    }

    /// Set file protection mode.
    fn set_mode(&mut self, mode: u16) {
        self.i_mode = mode.to_le();
    }

    /// Set the union field.
    fn set_u(&mut self, u: u32) {
        self.i_u = u.to_le();
    }

    /// Set uid and gid for the inode.
    fn set_uidgid(&mut self, uid: u32, gid: u32) {
        self.i_uid = u32::to_le(uid);
        self.i_gid = u32::to_le(gid);
    }

    /// Set last modification time for the inode.
    fn set_mtime(&mut self, sec: u64, nsec: u32) {
        self.i_mtime = u64::to_le(sec);
        self.i_mtime_nsec = u32::to_le(nsec);
    }

    fn set_rdev(&mut self, rdev: u32) {
        self.i_u = rdev.to_le()
    }

    /// Set xattr inline count.
    fn set_xattr_inline_count(&mut self, count: u16) {
        self.i_xattr_icount = count.to_le();
    }

    /// Set inode data layout format.
    fn set_data_layout(&mut self, data_layout: u16) {
        self.i_format = u16::to_le(EROFS_INODE_LAYOUT_EXTENDED | (data_layout << 1));
    }

    fn format(&self) -> u16 {
        u16::from_le(self.i_format)
    }

    fn mode(&self) -> u16 {
        u16::from_le(self.i_mode)
    }

    fn size(&self) -> u64 {
        u64::from_le(self.i_size)
    }

    fn union(&self) -> u32 {
        u32::from_le(self.i_u)
    }

    fn ino(&self) -> u32 {
        u32::from_le(self.i_ino)
    }

    fn ugid(&self) -> (u32, u32) {
        (u32::from_le(self.i_uid), u32::from_le(self.i_gid))
    }

    fn mtime_s_ns(&self) -> (u64, u32) {
        (u64::from_le(self.i_mtime), u32::from_le(self.i_mtime_nsec))
    }

    fn nlink(&self) -> u32 {
        u32::from_le(self.i_nlink)
    }

    fn rdev(&self) -> u32 {
        u32::from_le(self.i_u)
    }

    fn xattr_inline_count(&self) -> u16 {
        u16::from_le(self.i_xattr_icount)
    }

    /// Load a `RafsV6InodeExtended` from a reader.
    fn load(&mut self, r: &mut RafsIoReader) -> Result<()> {
        r.read_exact(self.as_mut())
    }
}

impl_bootstrap_converter!(RafsV6InodeExtended);

impl RafsStore for RafsV6InodeExtended {
    fn store(&self, w: &mut dyn RafsIoWrite) -> Result<usize> {
        // TODO: need to write xattr as well.
        w.write_all(self.as_ref())?;
        Ok(self.as_ref().len())
    }
}

/// Dirent sorted in alphabet order to improve performance by binary search.
#[repr(C, packed(2))]
#[derive(Default, Clone, Copy, Debug)]
pub struct RafsV6Dirent {
    /// Node number, inode offset = s_meta_blkaddr * 4096 + nid * 32
    pub e_nid: u64,
    /// start offset of file name in the block
    pub e_nameoff: u16,
    /// file type
    pub e_file_type: u8,
    /// reserved
    e_reserved: u8,
}

impl_bootstrap_converter!(RafsV6Dirent);

impl RafsV6Dirent {
    /// Create a new instance of `RafsV6Dirent`.
    pub fn new(nid: u64, nameoff: u16, file_type: u8) -> Self {
        Self {
            e_nid: u64::to_le(nid),
            e_nameoff: u16::to_le(nameoff),
            e_file_type: u8::to_le(file_type),
            e_reserved: 0,
        }
    }

    /// Get file type from file mode.
    pub fn file_type(mode: u32) -> u8 {
        let val = match mode as libc::mode_t & libc::S_IFMT {
            libc::S_IFREG => EROFS_FILE_TYPE::EROFS_FT_REG_FILE,
            libc::S_IFDIR => EROFS_FILE_TYPE::EROFS_FT_DIR,
            libc::S_IFCHR => EROFS_FILE_TYPE::EROFS_FT_CHRDEV,
            libc::S_IFBLK => EROFS_FILE_TYPE::EROFS_FT_BLKDEV,
            libc::S_IFIFO => EROFS_FILE_TYPE::EROFS_FT_FIFO,
            libc::S_IFSOCK => EROFS_FILE_TYPE::EROFS_FT_SOCK,
            libc::S_IFLNK => EROFS_FILE_TYPE::EROFS_FT_SYMLINK,
            _ => EROFS_FILE_TYPE::EROFS_FT_UNKNOWN,
        };

        val as u8
    }

    /// Set name offset of the dirent.
    pub fn set_name_offset(&mut self, offset: u16) {
        assert!(offset < EROFS_BLOCK_SIZE as u16);
        self.e_nameoff = u16::to_le(offset);
    }

    /// Load a `RafsV6Dirent` from a reader.
    pub fn load(&mut self, r: &mut RafsIoReader) -> Result<()> {
        r.read_exact(self.as_mut())
    }
}

impl RafsStore for RafsV6Dirent {
    fn store(&self, w: &mut dyn RafsIoWrite) -> Result<usize> {
        w.write_all(self.as_ref())?;
        Ok(self.as_ref().len())
    }
}

/// Rafs v6 ChunkHeader on-disk format.
#[repr(C)]
#[derive(Default, Clone, Copy, Debug)]
pub struct RafsV6InodeChunkHeader {
    /// Chunk layout format.
    format: u16,
    reserved: u16,
}

impl RafsV6InodeChunkHeader {
    /// Create a new instance of `RafsV6InodeChunkHeader`.
    ///
    /// If all chunks are continous in uncompressed cache file, the `chunk_size` will set to
    /// `inode.size().next_power_of_two()`, so EROFS can optimize page cache in this case.
    /// Otherwise `chunk_size` is set to RAFS filesystem's chunk size.
    pub fn new(chunk_size: u64) -> Self {
        assert!(chunk_size.is_power_of_two());
        let chunk_bits = chunk_size.trailing_zeros() as u16;
        assert!(chunk_bits >= EROFS_BLOCK_BITS as u16);
        let chunk_bits = chunk_bits - EROFS_BLOCK_BITS as u16;
        assert!(chunk_bits <= EROFS_CHUNK_FORMAT_SIZE_MASK);
        let format = EROFS_CHUNK_FORMAT_INDEXES_FLAG | chunk_bits;

        Self {
            format: u16::to_le(format),
            reserved: 0,
        }
    }

    /// Convert to a u32 value.
    pub fn to_u32(&self) -> u32 {
        (u16::from_le(self.format) as u32) | ((u16::from_le(self.reserved) as u32) << 16)
    }

    /// Convert a u32 value to `RafsV6InodeChunkHeader`.
    pub fn from_u32(val: u32) -> Self {
        Self {
            format: (val as u16).to_le(),
            reserved: ((val >> 16) as u16).to_le(),
        }
    }
}

impl_bootstrap_converter!(RafsV6InodeChunkHeader);

/// Rafs v6 chunk address on-disk format, 8 bytes.
#[repr(C)]
#[derive(Default, Clone, Copy, Debug, Hash, Eq, PartialEq)]
pub struct RafsV6InodeChunkAddr {
    /// Lower part of encoded blob address.
    c_blob_addr_lo: u16,
    /// Higher part of encoded blob address.
    c_blob_addr_hi: u16,
    /// start block address of this inode chunk
    /// decompressed offset must be aligned, in unit of block
    c_blk_addr: u32,
}

impl RafsV6InodeChunkAddr {
    /// Create a new instance of `RafsV6InodeChunkIndex`.
    pub fn new() -> Self {
        Self {
            c_blob_addr_lo: 0,
            c_blob_addr_hi: 0,
            c_blk_addr: 0,
        }
    }

    /// Get the blob index associated with the chunk.
    ///
    /// Note: for erofs, bump id by 1 since device id 0 is bootstrap.
    /// The index in BlobInfo grows from 0, so when using this method to index the corresponding blob,
    /// the index always needs to be minus 1
    /// Get the blob index of the chunk.
    pub fn blob_index(&self) -> u32 {
        (u16::from_le(self.c_blob_addr_hi) & 0x00ff) as u32 - 1
    }

    /// Set the blob index of the chunk.
    pub fn set_blob_index(&mut self, blob_idx: u32) {
        assert!(blob_idx < u8::MAX as u32);
        let mut val = u16::from_le(self.c_blob_addr_hi);
        val &= 0xff00;
        val |= (blob_idx + 1) as u16;
        self.c_blob_addr_hi = val.to_le();
    }

    /// Get the 24-bits index into the blob compression information array.
    pub fn blob_ci_index(&self) -> u32 {
        let val = (u16::from_le(self.c_blob_addr_hi) as u32) >> 8;
        (val << 16) | (u16::from_le(self.c_blob_addr_lo) as u32)
    }

    /// Set the index into the blob compression information array.
    pub fn set_blob_ci_index(&mut self, ci_index: u32) {
        assert!(ci_index <= 0x00ff_ffff);
        let val = (ci_index >> 8) as u16 & 0xff00 | (u16::from_le(self.c_blob_addr_hi) & 0x00ff);
        self.c_blob_addr_hi = val.to_le();
        self.c_blob_addr_lo = u16::to_le(ci_index as u16);
    }

    /// Get block address.
    pub fn block_addr(&self) -> u32 {
        u32::from_le(self.c_blk_addr)
    }

    /// Set block address.
    pub fn set_block_addr(&mut self, addr: u32) {
        self.c_blk_addr = addr.to_le();
    }

    /// Validate the 'RafsV6InodeChunkAddr' object.
    pub fn validate(&self, max_blob_index: u32) -> bool {
        let blob_idx = (u16::from_le(self.c_blob_addr_hi) & 0x00ff) as u32;
        blob_idx > 0 && blob_idx - 1 <= max_blob_index
    }

    /// Load a `RafsV6InodeChunkAddr` from a reader.
    pub fn load(&mut self, r: &mut RafsIoReader) -> Result<()> {
        r.read_exact(self.as_mut())
    }
}

impl_bootstrap_converter!(RafsV6InodeChunkAddr);

impl RafsStore for RafsV6InodeChunkAddr {
    fn store(&self, w: &mut dyn RafsIoWrite) -> Result<usize> {
        w.write_all(self.as_ref())?;
        Ok(self.as_ref().len())
    }
}

/// Rafs v6 device information on-disk format, 128 bytes.
#[repr(C)]
#[derive(Clone, Copy, Debug)]
pub struct RafsV6Device {
    /// Blob id of sha256.
    blob_id: [u8; BLOB_SHA256_LEN],
    /// Number of blocks on the device.
    blocks: u32,
    /// Mapping start address.
    mapped_blkaddr: u32,
    reserved2: [u8; 56],
}

impl Default for RafsV6Device {
    fn default() -> Self {
        Self {
            blob_id: [0u8; 64],
            blocks: 0,
            mapped_blkaddr: 0,
            reserved2: [0u8; 56],
        }
    }
}

impl RafsV6Device {
    /// Create a new instance of `RafsV6DeviceSlot`.
    pub fn new() -> Self {
        Self::default()
    }

    /// Get blob id.
    pub fn blob_id(&self) -> &[u8] {
        &self.blob_id
    }

    /// Set blob id.
    pub fn set_blob_id(&mut self, id: &[u8; 64]) {
        self.blob_id.copy_from_slice(id);
    }

    /// Get number of blocks.
    pub fn blocks(&self) -> u32 {
        u32::from_le(self.blocks)
    }

    /// Set number of blocks.
    pub fn set_blocks(&mut self, blocks: u32) {
        self.blocks = blocks.to_le();
    }

    /// Set mapped block address.
    pub fn set_mapped_blkaddr(&mut self, addr: u32) {
        self.mapped_blkaddr = addr.to_le();
    }

    /// Load a `RafsV6Device` from a reader.
    pub fn load(&mut self, r: &mut RafsIoReader) -> Result<()> {
        r.read_exact(self.as_mut())
    }

    /// Validate the Rafs v6 Device slot.
    pub fn validate(&self) -> Result<()> {
        match String::from_utf8(self.blob_id.to_vec()) {
            Ok(v) => {
                if v.len() != BLOB_SHA256_LEN {
                    return Err(einval!(format!("v.len {} is invalid", v.len())));
                }
            }
            Err(_) => return Err(einval!("blob_id from_utf8 is invalid")),
        }

        if self.blocks() == 0 {
            let msg = format!("invalid blocks {} in Rafs v6 Device", self.blocks());
            return Err(einval!(msg));
        }

        if u32::from_le(self.mapped_blkaddr) != 0 {
            return Err(einval!("invalid mapped_addr in Rafs v6 Device"));
        }

        Ok(())
    }
}

impl_bootstrap_converter!(RafsV6Device);

impl RafsStore for RafsV6Device {
    fn store(&self, w: &mut dyn RafsIoWrite) -> Result<usize> {
        w.write_all(self.as_ref())?;

        Ok(self.as_ref().len())
    }
}

#[inline]
pub fn align_offset(offset: u64, aligned_size: u64) -> u64 {
    round_up(offset, aligned_size)
}

/// Generate EROFS `nid` from `offset`.
pub fn calculate_nid(offset: u64, meta_size: u64) -> u64 {
    (offset - meta_size) >> EROFS_INODE_SLOT_BITS
}

#[repr(C)]
#[derive(Clone, Copy, Debug)]
struct RafsV6Blob {
    // SHA256 digest of the blob containing chunk data.
    blob_id: [u8; BLOB_SHA256_LEN],
    // Index in the blob table.
    blob_index: u32,
    // Chunk size of the blob.
    chunk_size: u32,
    // Number of chunks in the blob.
    chunk_count: u32,
    // Compression algorithm for chunks in the blob.
    compression_algo: u32,
    // Digest algorithm for chunks in the blob.
    digest_algo: u32,
    // Feature flags.
    features: u32,
    // Size of the compressed blob, not including CI array and header.
    compressed_size: u64,
    // Size of the uncompressed blob, not including CI array and header.
    uncompressed_size: u64,

    // Size of blob ToC content, it's zero for blobs with inlined-meta.
    blob_toc_size: u32,
    // Compression algorithm for the compression information array.
    ci_compressor: u32,
    // Offset into the compressed blob for the compression information array.
    ci_offset: u64,
    // Size of the compressed compression information array.
    ci_compressed_size: u64,
    // Size of the uncompressed compression information array.
    ci_uncompressed_size: u64,

    // SHA256 digest of blob ToC content, including the toc tar header.
    // It's all zero for blobs with inlined-meta.
    blob_toc_digest: [u8; 32],
    // SHA256 digest of RAFS blob for ZRAN, containing `blob.meta`, `blob.digest` `blob.toc` and
    // optionally 'image.boot`. It's all zero for ZRAN blobs with inlined-meta, so need special
    // handling.
    blob_meta_digest: [u8; 32],
    // Size of RAFS blob for ZRAN. It's zero ZRAN blobs with inlined-meta.
    blob_meta_size: u64,

    reserved2: [u8; 48],
}

impl Default for RafsV6Blob {
    fn default() -> Self {
        RafsV6Blob {
            blob_id: [0u8; BLOB_SHA256_LEN],
            blob_index: 0u32,
            chunk_size: 0u32,
            chunk_count: 0u32,
            compression_algo: (compress::Algorithm::None as u32).to_le(),
            digest_algo: (digest::Algorithm::Blake3 as u32).to_le(),
            features: 0u32,
            compressed_size: 0u64,
            uncompressed_size: 0u64,
            ci_compressor: (compress::Algorithm::None as u32).to_le(),
            ci_offset: 0u64,
            ci_compressed_size: 0u64,
            ci_uncompressed_size: 0u64,

            blob_toc_digest: [0u8; 32],
            blob_meta_digest: [0u8; 32],
            blob_meta_size: 0,
            blob_toc_size: 0u32,

            reserved2: [0u8; 48],
        }
    }
}

impl_bootstrap_converter!(RafsV6Blob);

impl RafsV6Blob {
    #[allow(clippy::wrong_self_convention)]
    fn to_blob_info(&self) -> Result<BlobInfo> {
        // debug_assert!(RAFS_DIGEST_LENGTH == 32);
        debug_assert!(size_of::<RafsV6Blob>() == 256);

        let blob_id = String::from_utf8(self.blob_id.to_vec())
            .map_err(|e| einval!(format!("invalid blob id, {}", e)))?;
        let blob_features = BlobFeatures::try_from(u32::from_le(self.features))?;
        let mut blob_info = BlobInfo::new(
            u32::from_le(self.blob_index),
            blob_id,
            u64::from_le(self.uncompressed_size),
            u64::from_le(self.compressed_size),
            u32::from_le(self.chunk_size),
            u32::from_le(self.chunk_count),
            blob_features,
        );

        let comp = compress::Algorithm::try_from(u32::from_le(self.compression_algo))
            .map_err(|_| einval!("invalid compression algorithm in Rafs v6 blob entry"))?;
        blob_info.set_compressor(comp);
        let digest = digest::Algorithm::try_from(u32::from_le(self.digest_algo))
            .map_err(|_| einval!("invalid digest algorithm in Rafs v6 blob entry"))?;
        blob_info.set_digester(digest);
        blob_info.set_blob_meta_info(
            u64::from_le(self.ci_offset),
            u64::from_le(self.ci_compressed_size),
            u64::from_le(self.ci_uncompressed_size),
            u32::from_le(self.ci_compressor),
        );
        blob_info.set_blob_toc_digest(self.blob_toc_digest);
        blob_info.set_blob_meta_digest(self.blob_meta_digest);
        blob_info.set_blob_meta_size(self.blob_meta_size);
        blob_info.set_blob_toc_size(self.blob_toc_size);

        Ok(blob_info)
    }

    fn from_blob_info(blob_info: &BlobInfo) -> Result<Self> {
        if blob_info.blob_id().len() > BLOB_SHA256_LEN || blob_info.blob_id().is_empty() {
            let msg = format!("invalid blob id in blob info, {}", blob_info.blob_id());
            return Err(einval!(msg));
        }

        let blob_id = blob_info.blob_id();
        let id = blob_id.as_bytes();
        let mut blob_id = [0u8; BLOB_SHA256_LEN];
        blob_id[..id.len()].copy_from_slice(id);

        Ok(RafsV6Blob {
            blob_id,
            blob_index: blob_info.blob_index().to_le(),
            chunk_size: blob_info.chunk_size().to_le(),
            chunk_count: blob_info.chunk_count().to_le(),
            compression_algo: (blob_info.compressor() as u32).to_le(),
            digest_algo: (blob_info.digester() as u32).to_le(),
            compressed_size: blob_info.compressed_size().to_le(),
            uncompressed_size: blob_info.uncompressed_size().to_le(),
            features: blob_info.features().bits().to_le(),
            ci_compressor: (blob_info.meta_ci_compressor() as u32).to_le(),
            ci_offset: blob_info.meta_ci_offset().to_le(),
            ci_compressed_size: blob_info.meta_ci_compressed_size().to_le(),
            ci_uncompressed_size: blob_info.meta_ci_uncompressed_size().to_le(),

            blob_toc_digest: *blob_info.blob_toc_digest(),
            blob_meta_digest: *blob_info.blob_meta_digest(),
            blob_meta_size: blob_info.blob_meta_size(),
            blob_toc_size: blob_info.blob_toc_size(),

            reserved2: [0u8; 48],
        })
    }

    fn validate(&self, blob_index: u32, chunk_size: u32, _flags: RafsSuperFlags) -> bool {
        match String::from_utf8(self.blob_id.to_vec()) {
            Ok(v) => {
                if v.len() != BLOB_SHA256_LEN {
                    error!(
                        "RafsV6Blob: idx {} blob id length {:x} is invalid",
                        blob_index,
                        v.len()
                    );
                    return false;
                }
            }
            Err(_) => {
                error!(
                    "RafsV6Blob: idx {} blob_id from_utf8 is invalid",
                    blob_index
                );
                return false;
            }
        }

        if u32::from_le(self.blob_index) != blob_index {
            error!(
                "RafsV6Blob: blob_index doesn't match {} {}",
                u32::from_le(self.blob_index),
                blob_index
            );
            return false;
        }

        let c_size = u32::from_le(self.chunk_size) as u64;
        if c_size.count_ones() != 1
            || !(EROFS_BLOCK_SIZE..=RAFS_MAX_CHUNK_SIZE).contains(&c_size)
            || c_size != chunk_size as u64
        {
            error!(
                "RafsV6Blob: idx {} invalid chunk_size 0x{:x}, expect 0x{:x}",
                blob_index, c_size, chunk_size
            );
            return false;
        }

        let chunk_count = u32::from_le(self.chunk_count);
        if chunk_count > RAFS_MAX_CHUNKS_PER_BLOB {
            error!(
                "RafsV6Blob: idx {} invalid chunk_count {:x}",
                blob_index, chunk_count
            );
            return false;
        }

        if compress::Algorithm::try_from(u32::from_le(self.compression_algo)).is_err()
            || compress::Algorithm::try_from(u32::from_le(self.ci_compressor)).is_err()
            || digest::Algorithm::try_from(u32::from_le(self.digest_algo)).is_err()
        {
            error!(
                "RafsV6Blob: idx {} invalid compression_algo {} ci_compressor {} digest_algo {}",
                blob_index, self.compression_algo, self.ci_compressor, self.digest_algo
            );
            return false;
        }

        let uncompressed_blob_size = u64::from_le(self.uncompressed_size);
        let compressed_blob_size = u64::from_le(self.compressed_size);
        if uncompressed_blob_size > BLOB_MAX_SIZE_UNCOMPRESSED {
            error!(
                "RafsV6Blob: idx {} invalid uncompressed_size {:x}",
                blob_index, uncompressed_blob_size
            );
            return false;
        }
        if compressed_blob_size > BLOB_MAX_SIZE_COMPRESSED {
            error!(
                "RafsV6Blob: idx {} invalid compressed_size {:x}",
                blob_index, compressed_blob_size
            );
            return false;
        }

        let blob_features = match BlobFeatures::try_from(self.features) {
            Ok(v) => v,
            Err(_) => return false,
        };
        if !blob_features.contains(BlobFeatures::ALIGNED) {
            error!(
                "RafsV6Blob: idx {} should have 4K-aligned feature bit",
                blob_index
            );
            return false;
        }

        let ci_offset = u64::from_le(self.ci_offset);
        let ci_compr_size = u64::from_le(self.ci_compressed_size);
        let ci_uncompr_size = u64::from_le(self.ci_uncompressed_size);
        if ci_offset.checked_add(ci_compr_size).is_none() {
            error!("RafsV6Blob: idx {} invalid fields, ci_compressed_size {:x} + ci_offset {:x} wraps around", blob_index, ci_compr_size, ci_offset);
            return false;
        } else if ci_compr_size > ci_uncompr_size {
            error!("RafsV6Blob: idx {} invalid fields, ci_compressed_size {:x} is greater than ci_uncompressed_size {:x}", blob_index, ci_compr_size, ci_uncompr_size);
            return false;
        }

        let count = chunk_count as u64;
        if blob_features.contains(BlobFeatures::CHUNK_INFO_V2)
            && blob_features.contains(BlobFeatures::ZRAN)
        {
            if ci_uncompr_size < count * size_of::<BlobChunkInfoV2Ondisk>() as u64 {
                error!(
                    "RafsV6Blob: idx {} invalid ci_d_size {}",
                    blob_index, ci_uncompr_size
                );
                return false;
            }
        } else if blob_features.contains(BlobFeatures::CHUNK_INFO_V2) {
            if ci_uncompr_size != count * size_of::<BlobChunkInfoV2Ondisk>() as u64 {
                error!(
                    "RafsV6Blob: idx {} invalid ci_d_size {}",
                    blob_index, ci_uncompr_size
                );
                return false;
            }
        } else if blob_features.contains(BlobFeatures::ZRAN) {
            error!(
                "RafsV6Blob: idx {} invalid feature bits {}",
                blob_index,
                blob_features.bits()
            );
            return false;
        } else if ci_uncompr_size != count * size_of::<BlobChunkInfoV1Ondisk>() as u64 {
            error!(
                "RafsV6Blob: idx {} invalid fields, ci_d_size {:x}, chunk_count {:x}",
                blob_index, ci_uncompr_size, chunk_count
            );
            return false;
        }

        true
    }
}

/// Rafs v6 blob description table.
#[derive(Clone, Debug, Default)]
pub struct RafsV6BlobTable {
    /// Base blob information array.
    entries: Vec<Arc<BlobInfo>>,
}

impl RafsV6BlobTable {
    /// Create a new instance of `RafsV6BlobTable`.
    pub fn new() -> Self {
        RafsV6BlobTable {
            entries: Vec::new(),
        }
    }

    /// Get blob table size.
    pub fn size(&self) -> usize {
        self.entries.len() * size_of::<RafsV6Blob>()
    }

    /// Get base information for a blob.
    #[inline]
    pub fn get(&self, blob_index: u32) -> Result<Arc<BlobInfo>> {
        if blob_index >= self.entries.len() as u32 {
            Err(enoent!("blob not found"))
        } else {
            Ok(self.entries[blob_index as usize].clone())
        }
    }

    /// Get the base blob information array.
    pub fn get_all(&self) -> Vec<Arc<BlobInfo>> {
        self.entries.clone()
    }

    /// Add information for new blob into the blob information table.
    #[allow(clippy::too_many_arguments)]
    pub fn add(
        &mut self,
        blob_id: String,
        prefetch_offset: u32,
        prefetch_size: u32,
        chunk_size: u32,
        chunk_count: u32,
        uncompressed_size: u64,
        compressed_size: u64,
        flags: RafsSuperFlags,
        blob_meta_digest: [u8; 32],
        blob_toc_digest: [u8; 32],
        blob_meta_size: u64,
        blob_toc_size: u32,
        header: BlobCompressionContextHeader,
    ) -> u32 {
        let blob_index = self.entries.len() as u32;
        let blob_features = BlobFeatures::try_from(header.features()).unwrap();
        let mut blob_info = BlobInfo::new(
            blob_index,
            blob_id,
            uncompressed_size,
            compressed_size,
            chunk_size,
            chunk_count,
            blob_features,
        );

        blob_info.set_compressor(flags.into());
        blob_info.set_digester(flags.into());
        blob_info.set_prefetch_info(prefetch_offset as u64, prefetch_size as u64);
        blob_info.set_blob_meta_info(
            header.ci_compressed_offset(),
            header.ci_compressed_size(),
            header.ci_uncompressed_size(),
            header.ci_compressor() as u32,
        );
        blob_info.set_blob_meta_digest(blob_meta_digest);
        blob_info.set_blob_toc_digest(blob_toc_digest);
        blob_info.set_blob_meta_size(blob_meta_size);
        blob_info.set_blob_toc_size(blob_toc_size);

        self.entries.push(Arc::new(blob_info));

        blob_index
    }

    /// Load blob information table from a reader.
    pub fn load(
        &mut self,
        r: &mut RafsIoReader,
        blob_table_size: u32,
        chunk_size: u32,
        flags: RafsSuperFlags,
    ) -> Result<()> {
        if blob_table_size == 0 {
            return Ok(());
        }
        if blob_table_size as usize % size_of::<RafsV6Blob>() != 0 {
            let msg = format!("invalid Rafs v6 blob table size {}", blob_table_size);
            return Err(einval!(msg));
        }

        for idx in 0..(blob_table_size as usize / size_of::<RafsV6Blob>()) {
            let mut blob = RafsV6Blob::default();
            r.read_exact(blob.as_mut())?;
            if !blob.validate(idx as u32, chunk_size, flags) {
                return Err(einval!("invalid Rafs v6 blob entry"));
            }
            let blob_info = blob.to_blob_info()?;
            self.entries.push(Arc::new(blob_info));
        }

        Ok(())
    }
}

impl RafsStore for RafsV6BlobTable {
    fn store(&self, w: &mut dyn RafsIoWrite) -> Result<usize> {
        for blob_info in self.entries.iter() {
            let blob: RafsV6Blob = RafsV6Blob::from_blob_info(blob_info)?;
            trace!(
                "blob_info index {}, chunk_count {} blob_id {:?}",
                blob_info.blob_index(),
                blob_info.chunk_count(),
                blob_info.blob_id(),
            );
            w.write_all(blob.as_ref())?;
        }

        Ok(self.entries.len() * size_of::<RafsV6Blob>())
    }
}

// RafsV6 xattr
const EROFS_XATTR_INDEX_USER: u8 = 1;
const EROFS_XATTR_INDEX_POSIX_ACL_ACCESS: u8 = 2;
const EROFS_XATTR_INDEX_POSIX_ACL_DEFAULT: u8 = 3;
const EROFS_XATTR_INDEX_TRUSTED: u8 = 4;
// const EROFS_XATTR_INDEX_LUSTRE: u8 = 5;
const EROFS_XATTR_INDEX_SECURITY: u8 = 6;

const XATTR_USER_PREFIX: &str = "user.";
const XATTR_SECURITY_PREFIX: &str = "security.";
const XATTR_TRUSTED_PREFIX: &str = "trusted.";
const XATTR_NAME_POSIX_ACL_ACCESS: &str = "system.posix_acl_access";
const XATTR_NAME_POSIX_ACL_DEFAULT: &str = "system.posix_acl_default";

struct RafsV6XattrPrefix {
    index: u8,
    prefix: &'static str,
    prefix_len: usize,
}

impl RafsV6XattrPrefix {
    fn new(prefix: &'static str, index: u8, prefix_len: usize) -> Self {
        RafsV6XattrPrefix {
            index,
            prefix,
            prefix_len,
        }
    }
}

lazy_static! {
    static ref RAFSV6_XATTR_TYPES: Vec<RafsV6XattrPrefix> = vec![
        RafsV6XattrPrefix::new(
            XATTR_USER_PREFIX,
            EROFS_XATTR_INDEX_USER,
            XATTR_USER_PREFIX.as_bytes().len()
        ),
        RafsV6XattrPrefix::new(
            XATTR_NAME_POSIX_ACL_ACCESS,
            EROFS_XATTR_INDEX_POSIX_ACL_ACCESS,
            XATTR_NAME_POSIX_ACL_ACCESS.as_bytes().len()
        ),
        RafsV6XattrPrefix::new(
            XATTR_NAME_POSIX_ACL_DEFAULT,
            EROFS_XATTR_INDEX_POSIX_ACL_DEFAULT,
            XATTR_NAME_POSIX_ACL_DEFAULT.as_bytes().len()
        ),
        RafsV6XattrPrefix::new(
            XATTR_TRUSTED_PREFIX,
            EROFS_XATTR_INDEX_TRUSTED,
            XATTR_TRUSTED_PREFIX.as_bytes().len()
        ),
        RafsV6XattrPrefix::new(
            XATTR_SECURITY_PREFIX,
            EROFS_XATTR_INDEX_SECURITY,
            XATTR_SECURITY_PREFIX.as_bytes().len()
        ),
    ];
}

// inline xattrs (n == i_xattr_icount):
// erofs_xattr_ibody_header(1) + (n - 1) * 4 bytes
//          12 bytes           /                   \
//                            /                     \
//                           /-----------------------\
//                           |  erofs_xattr_entries+ |
//                           +-----------------------+
// inline xattrs must starts with erofs_xattr_ibody_header.
#[repr(C)]
#[derive(Default)]
pub struct RafsV6XattrIbodyHeader {
    h_reserved: u32,
    h_shared_count: u8,
    h_reserved2: [u8; 7],
    // may be followed by shared xattr id array
}

impl_bootstrap_converter!(RafsV6XattrIbodyHeader);

impl RafsV6XattrIbodyHeader {
    pub fn new() -> Self {
        RafsV6XattrIbodyHeader::default()
    }

    /// Load a `RafsV6XattrIbodyHeader` from a reader.
    pub fn load(&mut self, r: &mut RafsIoReader) -> Result<()> {
        r.read_exact(self.as_mut())
    }
}

// RafsV6 xattr entry (for both inline & shared xattrs)
#[repr(C)]
#[derive(Default, PartialEq)]
pub struct RafsV6XattrEntry {
    // length of name
    e_name_len: u8,
    // attribute name index
    e_name_index: u8,
    // size of attribute value
    e_value_size: u16,
    // followed by e_name and e_value
}

impl_bootstrap_converter!(RafsV6XattrEntry);

impl RafsV6XattrEntry {
    fn new() -> Self {
        RafsV6XattrEntry::default()
    }

    pub fn name_len(&self) -> u32 {
        self.e_name_len as u32
    }

    pub fn name_index(&self) -> u8 {
        self.e_name_index
    }

    pub fn value_size(&self) -> u32 {
        u16::from_le(self.e_value_size) as u32
    }

    fn set_name_len(&mut self, v: u8) {
        self.e_name_len = v;
    }

    fn set_name_index(&mut self, v: u8) {
        self.e_name_index = v;
    }

    fn set_value_size(&mut self, v: u16) {
        self.e_value_size = v.to_le();
    }
}

pub(crate) fn recover_namespace(index: u8) -> Result<OsString> {
    let pos = RAFSV6_XATTR_TYPES
        .iter()
        .position(|x| x.index == index)
        .ok_or_else(|| einval!(format!("invalid xattr name index {}", index)))?;
    OsString::from_str(RAFSV6_XATTR_TYPES[pos].prefix)
        .map_err(|_e| einval!("invalid xattr name prefix"))
}

impl RafsXAttrs {
    /// Get the number of xattr pairs.
    pub fn count_v6(&self) -> usize {
        if self.is_empty() {
            0
        } else {
            let size = self.aligned_size_v6();
            (size - size_of::<RafsV6XattrIbodyHeader>()) / size_of::<RafsV6XattrEntry>() + 1
        }
    }

    /// Get aligned size of all xattr pairs.
    pub fn aligned_size_v6(&self) -> usize {
        if self.is_empty() {
            0
        } else {
            let mut size: usize = size_of::<RafsV6XattrIbodyHeader>();
            for (key, value) in self.pairs.iter() {
                // Safe to unwrap() because RafsXAttrs.add()/adds() has validated the prefix.
                let (_, prefix_len) = Self::match_prefix(key).expect("xattr is not valid");

                size += size_of::<RafsV6XattrEntry>();
                size += key.byte_size() - prefix_len + value.len();
                size = round_up(size as u64, size_of::<RafsV6XattrEntry>() as u64) as usize;
            }
            size
        }
    }

    /// Write Xattr to rafsv6 ondisk inode.
    pub fn store_v6(&self, w: &mut dyn RafsIoWrite) -> Result<usize> {
        let header = RafsV6XattrIbodyHeader::new();
        w.write_all(header.as_ref())?;

        if !self.pairs.is_empty() {
            for (key, value) in self.pairs.iter() {
                let (index, prefix_len) = Self::match_prefix(key)
                    .map_err(|_| einval!(format!("invalid xattr key {:?}", key)))?;
                if key.len() <= prefix_len {
                    return Err(einval!(format!("invalid xattr key {:?}", key)));
                }
                if value.len() > u16::MAX as usize {
                    return Err(einval!("xattr value size is too big"));
                }

                let mut entry = RafsV6XattrEntry::new();
                entry.set_name_len((key.byte_size() - prefix_len) as u8);
                entry.set_name_index(index);
                entry.set_value_size(value.len() as u16);

                w.write_all(entry.as_ref())?;
                w.write_all(&key.as_bytes()[prefix_len..])?;
                w.write_all(value.as_ref())?;

                let size =
                    size_of::<RafsV6XattrEntry>() + key.byte_size() - prefix_len + value.len();
                let padding =
                    round_up(size as u64, size_of::<RafsV6XattrEntry>() as u64) as usize - size;
                w.write_padding(padding)?;
            }
        }

        Ok(0)
    }

    fn match_prefix(key: &OsStr) -> Result<(u8, usize)> {
        let key_str = key.to_string_lossy();
        let pos = RAFSV6_XATTR_TYPES
            .iter()
            .position(|x| key_str.starts_with(x.prefix))
            .ok_or_else(|| einval!(format!("xattr prefix {:?} is not valid", key)))?;
        Ok((
            RAFSV6_XATTR_TYPES[pos].index,
            RAFSV6_XATTR_TYPES[pos].prefix_len,
        ))
    }
}

#[derive(Clone, Default, Debug)]
pub struct RafsV6PrefetchTable {
    /// List of inode numbers for prefetch.
    /// Note: It's not inode index of inodes table being stored here.
    pub inodes: Vec<u32>,
}

impl RafsV6PrefetchTable {
    /// Create a new instance of `RafsV6PrefetchTable`.
    pub fn new() -> RafsV6PrefetchTable {
        RafsV6PrefetchTable { inodes: vec![] }
    }

    /// Get content size of the inode prefetch table.
    pub fn size(&self) -> usize {
        self.len() * size_of::<u32>()
    }

    /// Get number of entries in the prefetch table.
    pub fn len(&self) -> usize {
        self.inodes.len()
    }

    /// Check whether the inode prefetch table is empty.
    pub fn is_empty(&self) -> bool {
        self.inodes.is_empty()
    }

    /// Add an inode into the inode prefetch table.
    pub fn add_entry(&mut self, ino: u32) {
        self.inodes.push(ino);
    }

    /// Store the inode prefetch table to a writer.
    pub fn store(&mut self, w: &mut dyn RafsIoWrite) -> Result<usize> {
        let (_, data, _) = unsafe { self.inodes.align_to::<u8>() };
        w.write_all(data.as_ref())?;

        // OK. Let's see if we have to align... :-(
        // let cur_len = self.inodes.len() * size_of::<u32>();

        Ok(data.len())
    }

    /// Load a inode prefetch table from a reader.
    ///
    /// Note: Generally, prefetch happens after loading bootstrap, so with methods operating
    /// files with changing their offset won't bring errors. But we still use `pread` now so as
    /// to make this method more stable and robust. Even dup(2) can't give us a separated file struct.
    pub fn load_prefetch_table_from(
        &mut self,
        r: &mut RafsIoReader,
        offset: u64,
        entries: usize,
    ) -> Result<usize> {
        self.inodes = vec![0u32; entries];

        let (_, data, _) = unsafe { self.inodes.align_to_mut::<u8>() };
        r.seek_to_offset(offset)?;
        r.read_exact(data)?;

        Ok(data.len())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{BufWriter, RafsIoRead};
    use std::fs::OpenOptions;
    use std::io::Write;
    use vmm_sys_util::tempfile::TempFile;

    #[test]
    fn test_super_block_load_store() {
        let mut sb = RafsV6SuperBlock::new();
        let temp = TempFile::new().unwrap();
        let w = OpenOptions::new()
            .read(true)
            .write(true)
            .open(temp.as_path())
            .unwrap();
        let r = OpenOptions::new()
            .read(true)
            .write(false)
            .open(temp.as_path())
            .unwrap();
        let mut writer = BufWriter::new(w);
        let mut reader: Box<dyn RafsIoRead> = Box::new(r);

        sb.s_blocks = 0x1000;
        sb.s_extra_devices = 5;
        sb.s_inos = 0x200;
        sb.store(&mut writer).unwrap();
        writer.flush().unwrap();

        let mut sb2 = RafsV6SuperBlock::new();
        sb2.load(&mut reader).unwrap();
        assert_eq!(sb2.s_magic, EROFS_SUPER_MAGIC_V1.to_le());
        assert_eq!(sb2.s_blocks, 0x1000u32.to_le());
        assert_eq!(sb2.s_extra_devices, 5u16.to_le());
        assert_eq!(sb2.s_inos, 0x200u64.to_le());
        assert_eq!(sb2.s_feature_compat, EROFS_FEATURE_COMPAT_RAFS_V6.to_le());
        assert_eq!(
            sb2.s_feature_incompat,
            (EROFS_FEATURE_INCOMPAT_CHUNKED_FILE | EROFS_FEATURE_INCOMPAT_DEVICE_TABLE).to_le()
        );
    }

    #[test]
    fn test_rafs_v6_inode_extended() {
        let temp = TempFile::new().unwrap();
        let w = OpenOptions::new()
            .read(true)
            .write(true)
            .open(temp.as_path())
            .unwrap();
        let r = OpenOptions::new()
            .read(true)
            .write(false)
            .open(temp.as_path())
            .unwrap();
        let mut writer = BufWriter::new(w);
        let mut reader: Box<dyn RafsIoRead> = Box::new(r);

        let mut inode = RafsV6InodeExtended::new();
        assert_eq!(
            inode.i_format,
            u16::to_le(EROFS_INODE_LAYOUT_EXTENDED | (EROFS_INODE_FLAT_PLAIN << 1))
        );
        inode.set_data_layout(EROFS_INODE_FLAT_INLINE);
        assert_eq!(
            inode.i_format,
            u16::to_le(EROFS_INODE_LAYOUT_EXTENDED | (EROFS_INODE_FLAT_INLINE << 1))
        );
        inode.set_inline_plain_layout();
        assert_eq!(
            inode.i_format,
            u16::to_le(EROFS_INODE_LAYOUT_EXTENDED | (EROFS_INODE_FLAT_PLAIN << 1))
        );
        inode.set_inline_inline_layout();
        assert_eq!(
            inode.i_format,
            u16::to_le(EROFS_INODE_LAYOUT_EXTENDED | (EROFS_INODE_FLAT_INLINE << 1))
        );
        inode.set_chunk_based_layout();
        assert_eq!(
            inode.i_format,
            u16::to_le(EROFS_INODE_LAYOUT_EXTENDED | (EROFS_INODE_CHUNK_BASED << 1))
        );
        inode.set_uidgid(1, 2);
        inode.set_mtime(3, 4);
        inode.store(&mut writer).unwrap();
        writer.flush().unwrap();

        let mut inode2 = RafsV6InodeExtended::new();
        inode2.load(&mut reader).unwrap();
        assert_eq!(inode2.i_uid, 1u32.to_le());
        assert_eq!(inode2.i_gid, 2u32.to_le());
        assert_eq!(inode2.i_mtime, 3u64.to_le());
        assert_eq!(inode2.i_mtime_nsec, 4u32.to_le());
        assert_eq!(
            inode2.i_format,
            u16::to_le(EROFS_INODE_LAYOUT_EXTENDED | (EROFS_INODE_CHUNK_BASED << 1))
        );
    }

    #[test]
    fn test_rafs_v6_chunk_header() {
        let chunk_size: u32 = 1024 * 1024;
        let header = RafsV6InodeChunkHeader::new(chunk_size as u64);
        let target = EROFS_CHUNK_FORMAT_INDEXES_FLAG | (20 - 12) as u16;
        assert_eq!(u16::from_le(header.format), target);
    }

    #[test]
    fn test_rafs_v6_chunk_addr() {
        let temp = TempFile::new().unwrap();
        let w = OpenOptions::new()
            .read(true)
            .write(true)
            .open(temp.as_path())
            .unwrap();
        let r = OpenOptions::new()
            .read(true)
            .write(false)
            .open(temp.as_path())
            .unwrap();
        let mut writer = BufWriter::new(w);
        let mut reader: Box<dyn RafsIoRead> = Box::new(r);

        let mut chunk = RafsV6InodeChunkAddr::new();
        chunk.set_blob_index(3);
        chunk.set_blob_ci_index(0x123456);
        chunk.set_block_addr(0xa5a53412);
        chunk.store(&mut writer).unwrap();
        writer.flush().unwrap();
        let mut chunk2 = RafsV6InodeChunkAddr::new();
        chunk2.load(&mut reader).unwrap();
        assert_eq!(chunk2.blob_index(), 3);
        assert_eq!(chunk2.blob_ci_index(), 0x123456);
        assert_eq!(chunk2.block_addr(), 0xa5a53412);
        assert!(chunk2.validate(4));
        assert!(chunk2.validate(3));
        assert!(!chunk2.validate(2));
    }

    #[test]
    fn test_rafs_v6_device() {
        let temp = TempFile::new().unwrap();
        let w = OpenOptions::new()
            .read(true)
            .write(true)
            .open(temp.as_path())
            .unwrap();
        let r = OpenOptions::new()
            .read(true)
            .write(false)
            .open(temp.as_path())
            .unwrap();
        let mut writer = BufWriter::new(w);
        let mut reader: Box<dyn RafsIoRead> = Box::new(r);

        let id = [0xa5u8; 64];
        let mut device = RafsV6Device::new();
        device.set_blocks(0x1234);
        device.set_blob_id(&id);
        device.store(&mut writer).unwrap();
        writer.flush().unwrap();
        let mut device2 = RafsV6Device::new();
        device2.load(&mut reader).unwrap();
        assert_eq!(device2.blocks(), 0x1234);
        assert_eq!(device.blob_id(), &id);
    }

    #[test]
    fn test_rafs_xattr_count_v6() {
        let mut xattrs = RafsXAttrs::new();
        xattrs.add(OsString::from("user.a"), vec![1u8]).unwrap();
        xattrs.add(OsString::from("trusted.b"), vec![2u8]).unwrap();

        assert_eq!(xattrs.count_v6(), 5);

        let xattrs2 = RafsXAttrs::new();
        assert_eq!(xattrs2.count_v6(), 0);
    }

    #[test]
    fn test_rafs_xattr_size_v6() {
        let mut xattrs = RafsXAttrs::new();
        xattrs.add(OsString::from("user.a"), vec![1u8]).unwrap();
        xattrs.add(OsString::from("trusted.b"), vec![2u8]).unwrap();

        let size = 12 + 8 + 8;
        assert_eq!(xattrs.aligned_size_v6(), size);

        let xattrs2 = RafsXAttrs::new();
        assert_eq!(xattrs2.aligned_size_v6(), 0);

        let mut xattrs2 = RafsXAttrs::new();
        xattrs2.add(OsString::from("user.a"), vec![1u8]).unwrap();
        xattrs2
            .add(OsString::from("unknown.b"), vec![2u8])
            .unwrap_err();
    }

    #[test]
    fn test_rafs_xattr_store_v6() {
        let temp = TempFile::new().unwrap();
        let w = OpenOptions::new()
            .read(true)
            .write(true)
            .open(temp.as_path())
            .unwrap();
        let r = OpenOptions::new()
            .read(true)
            .write(false)
            .open(temp.as_path())
            .unwrap();
        let mut writer = BufWriter::new(w);
        let mut reader: Box<dyn RafsIoRead> = Box::new(r);

        let mut xattrs = RafsXAttrs::new();
        xattrs.add(OsString::from("user.nydus"), vec![1u8]).unwrap();
        xattrs
            .add(OsString::from("security.rafs"), vec![2u8, 3u8])
            .unwrap();
        xattrs.store_v6(&mut writer).unwrap();
        writer.flush().unwrap();

        let mut header = RafsV6XattrIbodyHeader::new();
        header.load(&mut reader).unwrap();
        let mut size = size_of::<RafsV6XattrIbodyHeader>();

        assert_eq!(header.h_shared_count, 0u8);

        let target1 = RafsV6XattrEntry {
            e_name_len: 4u8,
            e_name_index: 6u8,
            e_value_size: u16::to_le(2u16),
        };

        let target2 = RafsV6XattrEntry {
            e_name_len: 5u8,
            e_name_index: 1u8,
            e_value_size: u16::to_le(1u16),
        };

        let mut entry1 = RafsV6XattrEntry::new();
        reader.read_exact(entry1.as_mut()).unwrap();
        assert!((entry1 == target1 || entry1 == target2));

        size += size_of::<RafsV6XattrEntry>()
            + entry1.name_len() as usize
            + entry1.value_size() as usize;

        reader
            .seek_to_offset(round_up(size as u64, size_of::<RafsV6XattrEntry>() as u64))
            .unwrap();

        let mut entry2 = RafsV6XattrEntry::new();
        reader.read_exact(entry2.as_mut()).unwrap();
        if entry1 == target1 {
            assert!(entry2 == target2);
        } else {
            assert!(entry2 == target1);
        }
    }
}