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
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
//! ext2 / ext3 / ext4 filesystem implementation.
//!
//! v1 writes ext2 (no journal, no extents, no htree). Feature-flag wiring
//! for ext3/ext4 follows in P4; the on-disk format types are intentionally
//! shared so adding the deltas does not duplicate the superblock /
//! group-descriptor / inode encoders.
//!
//! ## Streaming
//!
//! Only *metadata* is kept in memory during a write — per-group bitmaps,
//! the in-progress inode table (one slot per allocated inode), and the
//! data blocks of directories being assembled. File contents are streamed
//! straight to the device through a fixed-size buffer; no file is ever
//! fully resident in memory regardless of size.
//!
//! ## Binary-exact compatibility with genext2fs
//!
//! Defaults are chosen to match `genext2fs -d <dir> -f -q` (-f = zero
//! timestamps, -q = squash uids/perms). See `tests/ext2_genext2fs_compat.rs`
//! for the diff harness once it lands.
pub mod build_plan;
pub mod constants;
pub mod csum;
pub mod dir;
pub mod extent;
pub mod group;
pub mod htree;
pub mod inode;
pub mod jbd2;
pub mod layout;
pub mod rw;
pub mod superblock;
pub mod xattr;
pub use build_plan::BuildPlan;
use std::io::Read;
use constants::{INO_ROOT_DIR, SUPERBLOCK_OFFSET};
use group::{GroupDesc, set_bit, set_first_n, test_bit};
use inode::{Inode, SpecialKind};
use layout::Layout;
use superblock::Superblock;
use crate::Result;
use crate::block::BlockDevice;
use crate::fs::rootdevs::{RootDevs, device_table};
use crate::fs::{DeviceKind, FileMeta, FileSource};
/// Which member of the ext family to produce. Controls which feature flags
/// are set and whether a journal is allocated. ext4-specific format work
/// (extent tree, 64-bit, flex_bg, ...) lands incrementally — v1 accepts
/// `Ext4` but currently emits the same on-disk layout as ext3, which
/// modern kernels mount as ext4 once the feature flags are set.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum FsKind {
#[default]
Ext2,
Ext3,
Ext4,
}
impl FsKind {
/// Whether this kind uses a journal.
pub fn has_journal(self) -> bool {
matches!(self, FsKind::Ext3 | FsKind::Ext4)
}
}
/// Options accepted by [`Ext::format_with`].
///
/// Defaults mirror `genext2fs -d <dir> -f -q -B 1024`: 1 KiB blocks, no
/// features, all-zero UUID + label, mtime 0, 5% reserved blocks, lost+found
/// pre-allocated.
#[derive(Debug, Clone)]
pub struct FormatOpts {
pub kind: FsKind,
pub block_size: u32,
pub blocks_count: u32,
pub inodes_count: u32,
pub uuid: [u8; 16],
pub volume_label: [u8; 16],
pub mtime: u32,
pub reserved_blocks_percent: u8,
pub create_lost_found: bool,
/// Journal size in FS blocks. Only used when `kind.has_journal()`.
/// 0 → pick a sensible default (256 blocks).
pub journal_blocks: u32,
/// When set, regular files are written sparsely: any block that is
/// entirely zero is left unallocated (a hole) instead of consuming a
/// data block. The file still reads back identically. Off by default
/// so plain ext2 output stays byte-for-byte comparable with genext2fs.
pub sparse: bool,
/// When true, only groups 0 and 1 plus groups whose number is a power
/// of 3, 5, or 7 hold a superblock + GDT backup; the rest skip them.
/// Advertised on disk by `RO_COMPAT_SPARSE_SUPER`. Off by default so
/// raw-ext2 output stays binary-exact with genext2fs (which doesn't
/// emit sparse_super); on by default for ext3/ext4 (which match mke2fs).
pub sparse_super: bool,
/// Base-2 logarithm of the flex-unit size when `INCOMPAT_FLEX_BG` is
/// enabled (0 disables the feature).
///
/// With flex_bg the block bitmap, inode bitmap, and inode table of
/// every group in a flex unit are packed contiguously into the first
/// group of that unit; the remaining groups in the unit hold only
/// data (and optional SB+GDT backups). Improves large-FS performance
/// at the cost of clustered metadata.
///
/// Valid range: 0..=5 (1 to 32 groups per unit). Defaults to 0
/// (disabled) so that ext2/3/4 output stays bit-for-bit compatible
/// with the pre-flex_bg writer; opt in by setting this to 4 (mke2fs's
/// default for small/medium FSes, 16 groups per unit).
pub log_groups_per_flex: u8,
/// When true, emit 64-byte group descriptors and advertise
/// `INCOMPAT_64BIT` + `INCOMPAT_META_BG` in the superblock. Required
/// for filesystems whose block count exceeds 2³² (≈ 16 TiB with 4 KiB
/// blocks). The reader transparently handles either descriptor size.
/// Off by default — the v1 writer never emits block numbers above 2³²,
/// so the upper halves remain zero.
pub use_64bit: bool,
/// When true, emit the `sparse_super2` compat feature: SB+GDT backups
/// live in exactly the two block groups listed (rather than groups 0,
/// 1, and powers-of-3/5/7 under classic `sparse_super`). The two
/// groups are recorded in `s_backup_bgs[2]`; the writer picks
/// `[1, last_group]` automatically. Off by default.
pub sparse_super2: bool,
/// When true, advertise `INCOMPAT_INLINE_DATA` and store small
/// regular files (≤ 60 bytes) directly in the inode's `i_block`
/// array instead of allocating a data block. Saves one block per
/// small file. Off by default — flipping it changes the on-disk
/// shape of the FS so kernel/e2fsck installations older than ~3.8
/// would refuse to mount the result.
pub inline_data: bool,
}
impl Default for FormatOpts {
fn default() -> Self {
Self {
kind: FsKind::Ext2,
block_size: 1024,
blocks_count: 1024,
inodes_count: 16,
uuid: [0; 16],
volume_label: [0; 16],
mtime: 0,
reserved_blocks_percent: 5,
create_lost_found: true,
journal_blocks: 0,
sparse: false,
sparse_super: false,
log_groups_per_flex: 0,
use_64bit: false,
sparse_super2: false,
inline_data: false,
}
}
}
impl FormatOpts {
/// Recommended `log_groups_per_flex` for a filesystem with the given
/// number of block groups. Mirrors mke2fs's heuristic: leave flex_bg
/// off for very small FSes (it buys nothing) and use a 16-group flex
/// unit (log 4) otherwise. The integrator is free to override.
pub const fn default_log_groups_per_flex(num_groups: u32) -> u8 {
if num_groups < 16 { 0 } else { 4 }
}
/// Pull ext-specific keys out of an [`OptionMap`] and apply them on
/// top of `self`. Recognised keys mirror the field names of this
/// struct verbatim (so `-O block_size=4096` does what you expect):
///
/// - `block_size` (u32)
/// - `blocks_count` (u32)
/// - `inodes_count` (u32)
/// - `reserved_blocks_percent` (u8)
/// - `mtime` (u32, Unix epoch seconds)
/// - `journal_blocks` (u32)
/// - `sparse` (bool)
/// - `sparse_super` (bool)
/// - `sparse_super2` (bool)
/// - `use_64bit` (bool)
/// - `log_groups_per_flex` (u8, 0..=5)
/// - `volume_label` (string, ≤ 16 bytes; longer is rejected)
/// - `create_lost_found` (bool)
///
/// Leaves `kind` and `uuid` alone — those are set by the caller
/// (the CLI's `--type` flag drives `kind`; the spec doesn't
/// surface a UUID knob yet).
///
/// [`OptionMap`]: crate::format_opts::OptionMap
pub fn apply_options(&mut self, map: &mut crate::format_opts::OptionMap) -> crate::Result<()> {
if let Some(v) = map.take_u32("block_size")? {
self.block_size = v;
}
if let Some(v) = map.take_u32("blocks_count")? {
self.blocks_count = v;
}
if let Some(v) = map.take_u32("inodes_count")? {
self.inodes_count = v;
}
if let Some(v) = map.take_u8("reserved_blocks_percent")? {
self.reserved_blocks_percent = v;
}
if let Some(v) = map.take_u32("mtime")? {
self.mtime = v;
}
if let Some(v) = map.take_u32("journal_blocks")? {
self.journal_blocks = v;
}
if let Some(v) = map.take_bool("sparse")? {
self.sparse = v;
}
if let Some(v) = map.take_bool("sparse_super")? {
self.sparse_super = v;
}
if let Some(v) = map.take_bool("sparse_super2")? {
self.sparse_super2 = v;
}
if let Some(v) = map.take_bool("use_64bit")? {
self.use_64bit = v;
}
if let Some(v) = map.take_u8("log_groups_per_flex")? {
self.log_groups_per_flex = v;
}
if let Some(v) = map.take_bool("create_lost_found")? {
self.create_lost_found = v;
}
if let Some(label) = map.take_label::<16>("volume_label", 0)? {
self.volume_label = label;
}
Ok(())
}
/// Validate this opts' flex_bg setting before format. Returns Ok if
/// flex_bg is disabled or in-range; an error if `log_groups_per_flex`
/// exceeds the 5 (32-groups) cap defined by the on-disk format.
fn check_flex_bg(&self) -> crate::Result<()> {
if self.log_groups_per_flex > 5 {
return Err(crate::Error::InvalidArgument(format!(
"ext: log_groups_per_flex {} > 5 (max 32 groups per flex unit)",
self.log_groups_per_flex
)));
}
Ok(())
}
}
/// In-memory state of a block group during writing.
#[derive(Debug, Clone)]
struct GroupState {
block_bitmap: Vec<u8>,
inode_bitmap: Vec<u8>,
desc: GroupDesc,
}
/// An open / under-construction ext filesystem.
///
/// During the build phase the on-disk state may be inconsistent: bitmaps
/// and inode-table entries are only written when [`Ext::flush`] runs
/// (called automatically at the end of [`Ext::format_with`] for the empty
/// FS case, and explicitly after a batch of `add_*` calls).
#[derive(Debug)]
pub struct Ext {
pub sb: Superblock,
pub layout: Layout,
/// Which ext flavour to write — controls extent-vs-indirect block
/// pointers, FILETYPE in dirents, etc.
pub kind: FsKind,
/// When set, all-zero blocks in regular files are written as holes.
pub sparse: bool,
groups: Vec<GroupState>,
/// Next free inode number to hand out (starts at first_ino).
next_inode: u32,
/// Inodes allocated so far during this build session. Written to the
/// on-disk inode table during [`flush_metadata`].
pub(crate) inodes: Vec<(u32, Inode)>,
/// Data blocks staged for write (typically directory data blocks and
/// indirect-block tables, which we assemble in memory). Regular file
/// data is NOT staged here — it streams straight to the device.
pub(crate) data_blocks: Vec<(u32, Vec<u8>)>,
/// Directory data blocks staged in `data_blocks`, tagged with their
/// owning directory inode. Used at flush time to stamp the per-block
/// CRC32C checksum tail when `metadata_csum` is active.
dir_blocks: Vec<(u32, u32)>,
/// Extent-tree leaf blocks staged in `data_blocks`, tagged with their
/// owning inode. Used at flush time to stamp the 4-byte
/// `ext4_extent_tail` CRC32C when `metadata_csum` is active.
extent_leaf_blocks: Vec<(u32, u32)>,
/// HTree dx_root blocks staged in `data_blocks`. Tuple is
/// (block, owning_inode, dx_entry_count). The CRC at flush time
/// covers only the in-use prefix (count_offset + count * 8 bytes)
/// plus a 4-byte dt_reserved + a 4-byte dt_checksum placeholder —
/// distinct from both the dir-block tail csum and the extent_tail
/// csum.
dx_root_blocks: Vec<(u32, u32, u16)>,
/// HTree dx_node intermediate blocks staged in `data_blocks`,
/// used only when a directory's index has `indirect_levels = 1`.
/// Same csum scheme as dx_root but with the smaller 12-byte
/// fake-dirent prefix (no `.` / `..` / dx_root_info overhead).
dx_node_blocks: Vec<(u32, u32, u16)>,
/// True until the first flush after a `format_with` lands. The
/// initial flush is a "blast everything fresh" write that doesn't
/// ride a journal transaction (there's nothing yet to be consistent
/// with — the journal is fresh and clean). Subsequent flushes on an
/// image with a journal go through the JBD2 commit/checkpoint path.
bootstrap: bool,
}
impl Ext {
/// Format the device, returning an `Ext` handle. At return the on-disk
/// image is a valid ext2 containing just the root directory (and
/// `/lost+found` if requested in `opts`).
pub fn format_with(dev: &mut dyn BlockDevice, opts: &FormatOpts) -> Result<Self> {
opts.check_flex_bg()?;
// Pre-compute the sparse-super mode and the `s_backup_bgs` pair so
// both the layout planner and the on-disk superblock agree on
// which groups carry SB+GDT backups.
//
// For `sparse_super2` we need to know the group count to pick the
// two backup groups (`[1, last]` matches mke2fs's default). Probe
// the layout once with All to get `num_groups`, then replan with
// the real mode if sparse_super2 is on.
let (sparse_mode, backup_bgs) = if opts.sparse_super2 {
// First pass: just need group count.
let probe = layout::plan_layout(
opts.block_size,
opts.blocks_count,
opts.inodes_count,
layout::SparseSuperMode::All,
opts.log_groups_per_flex,
opts.use_64bit,
)?;
let last = probe.num_groups().saturating_sub(1);
// For a single-group FS use [0, 0] — group 0 always carries
// the primary SB anyway.
let bgs = if probe.num_groups() <= 1 {
[0, 0]
} else {
[1, last]
};
(layout::SparseSuperMode::Two(bgs), bgs)
} else if opts.sparse_super {
(layout::SparseSuperMode::Classic, [0, 0])
} else {
(layout::SparseSuperMode::All, [0, 0])
};
let layout = layout::plan_layout(
opts.block_size,
opts.blocks_count,
opts.inodes_count,
sparse_mode,
opts.log_groups_per_flex,
opts.use_64bit,
)?;
let total_bytes = layout.blocks_count as u64 * layout.block_size as u64;
if dev.total_size() < total_bytes {
return Err(crate::Error::InvalidArgument(format!(
"ext: device has {} bytes, need {total_bytes}",
dev.total_size()
)));
}
// Zero the FS region. Backends may treat this as a sparse hole.
dev.zero_range(0, total_bytes)?;
// Build superblock.
let mut sb = Superblock::ext2_default();
sb.blocks_count = layout.blocks_count;
sb.inodes_count = layout.inodes_count;
sb.first_data_block = layout.first_data_block;
sb.log_block_size = layout.block_size.trailing_zeros() - 10;
sb.log_frag_size = sb.log_block_size;
sb.blocks_per_group = layout.blocks_per_group;
sb.frags_per_group = layout.blocks_per_group;
sb.inodes_per_group = layout.inodes_per_group;
sb.mtime = opts.mtime;
sb.wtime = opts.mtime;
sb.uuid = opts.uuid;
sb.volume_name = opts.volume_label;
sb.r_blocks_count =
(layout.blocks_count as u64 * opts.reserved_blocks_percent as u64 / 100) as u32;
sb.lastcheck = opts.mtime;
// Initialise per-group bitmaps with metadata blocks already marked
// as used, plus padding-bit-as-used tails for short groups and small
// inode counts.
let bs = layout.block_size;
let mut groups = Vec::with_capacity(layout.groups.len());
for g in &layout.groups {
let mut block_bitmap = vec![0u8; bs as usize];
let mut inode_bitmap = vec![0u8; bs as usize];
// Mark metadata blocks of this group as used.
for blk in g.start_block..g.data_start {
set_bit(&mut block_bitmap, blk - g.start_block);
}
// For 1 KiB blocks where first_data_block == 1, block 0 (boot
// block) is outside the bitmap entirely. Higher block sizes
// overlap the boot region with block 0 itself, which IS the
// first block of group 0, so it must be marked used: that's
// already covered above because block 0 lies in [start, data_start).
let group_blocks = g.end_block - g.start_block + 1;
// Bits past the group's last valid block are marked used so the
// allocator never picks them.
for bit in group_blocks..(bs * 8) {
set_bit(&mut block_bitmap, bit);
}
// Same on the inode bitmap.
for bit in layout.inodes_per_group..(bs * 8) {
set_bit(&mut inode_bitmap, bit);
}
let desc = GroupDesc {
block_bitmap: g.block_bitmap,
inode_bitmap: g.inode_bitmap,
inode_table: g.inode_table,
free_blocks_count: 0,
free_inodes_count: 0,
used_dirs_count: 0,
flags: 0,
};
groups.push(GroupState {
block_bitmap,
inode_bitmap,
desc,
});
}
let mut ext = Self {
sb,
layout,
kind: opts.kind,
sparse: opts.sparse,
groups,
next_inode: 0,
inodes: Vec::new(),
data_blocks: Vec::new(),
dir_blocks: Vec::new(),
extent_leaf_blocks: Vec::new(),
dx_root_blocks: Vec::new(),
dx_node_blocks: Vec::new(),
// During format the journal SB is staged in `data_blocks`
// and the file system as a whole is being assembled fresh;
// the initial flush is a "blast everything" write rather
// than a JBD2-protected transaction. After the first flush
// lands this is set to false so subsequent incremental
// edits ride the journal commit/checkpoint path.
bootstrap: true,
};
// Set feature flags up front — before create_root / create_lost_found
// run — so those build their directory blocks with the right layout
// (FILETYPE dirents, metadata_csum tail). The journal feature is set
// here too; allocate_journal itself runs further down.
if matches!(opts.kind, FsKind::Ext4) {
ext.sb.feature_incompat |= constants::feature::INCOMPAT_EXTENTS;
// FILETYPE is required for metadata_csum's directory checksum
// tail (the tail uses the dirent file_type byte as its marker),
// and matches mke2fs ext4 anyway.
ext.sb.feature_incompat |= constants::feature::INCOMPAT_FILETYPE;
// Match mke2fs: a fresh ext4 carries CRC32C metadata checksums.
ext.sb.feature_ro_compat |= constants::feature::RO_COMPAT_METADATA_CSUM;
// Advertise DIR_INDEX (HTree) capability. Setting the bit
// doesn't oblige every dir to be indexed — un-indexed dirs
// are still valid; we set EXT4_INDEX_FL per-inode on the
// ones we actually emit as HTree.
ext.sb.feature_compat |= constants::feature::COMPAT_DIR_INDEX;
}
if opts.sparse_super {
ext.sb.feature_ro_compat |= constants::feature::RO_COMPAT_SPARSE_SUPER;
}
if opts.kind.has_journal() {
ext.sb.feature_compat |= constants::feature::COMPAT_HAS_JOURNAL;
}
// flex_bg: when log_groups_per_flex != 0 the layout planner has
// already packed metadata into the first group of each flex unit;
// we just record the feature flag + the log value in the
// superblock so the kernel and e2fsck know to expect the packed
// layout.
if opts.log_groups_per_flex > 0 {
ext.sb.feature_incompat |= constants::feature::INCOMPAT_FLEX_BG;
ext.sb.log_groups_per_flex = opts.log_groups_per_flex;
}
// 64-bit FS: 64-byte group descriptors carry the upper half of the
// bitmap/itable block numbers. Kernel docs pair `INCOMPAT_64BIT`
// with `INCOMPAT_META_BG`; set both. `s_desc_size = 64` tells the
// reader to expect the wider descriptor.
if opts.use_64bit {
ext.sb.feature_incompat |= constants::feature::INCOMPAT_64BIT;
ext.sb.feature_incompat |= constants::feature::INCOMPAT_META_BG;
ext.sb.desc_size = constants::GROUP_DESC_SIZE_64 as u16;
}
// sparse_super2: backups only in the two listed groups. Mutually
// exclusive with `sparse_super` in semantics (the layout planner
// gives `Two` precedence), but the kernel docs put each flag in
// its own feature word so both bits *could* be set. We only flip
// the sparse_super2 bit; the on-disk `s_backup_bgs` array carries
// the actual group numbers.
if opts.sparse_super2 {
ext.sb.feature_compat |= constants::feature::COMPAT_SPARSE_SUPER2;
ext.sb.backup_bgs = backup_bgs;
}
if opts.inline_data {
ext.sb.feature_incompat |= constants::feature::INCOMPAT_INLINE_DATA;
}
// Reserve inodes 1..first_ino-1 (1..=10 for dynamic rev).
let first_ino = ext.sb.first_ino;
set_first_n(&mut ext.groups[0].inode_bitmap, first_ino - 1);
ext.next_inode = first_ino;
// Create the root directory at inode 2.
ext.create_root(opts.mtime)?;
// Optional /lost+found.
if opts.create_lost_found {
ext.create_lost_found(dev, opts.mtime)?;
}
// Optional journal (ext3 / ext4). JBD2 requires a minimum of 1024
// blocks; smaller journals are rejected by the kernel + e2fsck.
if opts.kind.has_journal() {
let blocks = if opts.journal_blocks == 0 {
1024
} else {
opts.journal_blocks
};
ext.allocate_journal(blocks, opts.mtime)?;
ext.sb.journal_inum = constants::INO_JOURNAL;
}
ext.recompute_free_counts();
ext.flush_metadata(dev)?;
Ok(ext)
}
/// Whether the `metadata_csum` feature is active on this filesystem.
pub(crate) fn has_metadata_csum(&self) -> bool {
self.sb.feature_ro_compat & constants::feature::RO_COMPAT_METADATA_CSUM != 0
}
/// Whether the `inline_data` feature is active. When true, small
/// regular files (≤ 60 bytes) get stored in `i_block` directly
/// instead of allocating a data block; readers honour the
/// `EXT4_INLINE_DATA_FL` flag on the inode to decode them.
pub(crate) fn has_inline_data(&self) -> bool {
self.sb.feature_incompat & constants::feature::INCOMPAT_INLINE_DATA != 0
}
/// If the filesystem carries a JBD2 journal with committed-but-not-
/// checkpointed transactions, replay them onto the device. Mirrors
/// what the Linux kernel does on first mount of an unclean ext{3,4}
/// filesystem: walk the journal log starting at `s_start`, apply
/// each transaction's data blocks to their target FS locations,
/// then mark the journal clean (`s_start = 0`).
///
/// No-op when the journal is clean, absent, or the FS isn't a
/// journalled flavour.
///
/// Returns `true` if any work was replayed. After a successful
/// replay the in-memory bitmaps and group descriptors are
/// re-read from disk (replay rewrote them) and `INCOMPAT_RECOVER`
/// is cleared from the in-memory superblock — recovery has been
/// completed, even if we haven't yet flushed that back to the
/// on-disk SB (callers writing back to the source should issue a
/// fresh flush; read-only consumers won't notice the difference).
pub fn replay_pending_journal(&mut self, dev: &mut dyn BlockDevice) -> Result<bool> {
if self.sb.feature_compat & constants::feature::COMPAT_HAS_JOURNAL == 0 {
return Ok(false);
}
let replayed = jbd2::replay_journal(self, dev)?;
if replayed {
self.reload_groups_from_disk(dev)?;
self.sb.feature_incompat &= !constants::feature::INCOMPAT_RECOVER;
}
Ok(replayed)
}
/// Public accessor for `Self::has_metadata_csum`, exposed for the
/// repack layer (which needs to mirror destination metadata_csum
/// state when pre-sizing directories).
pub fn has_metadata_csum_pub(&self) -> bool {
self.has_metadata_csum()
}
/// Whether directory entries carry a `file_type` byte (`INCOMPAT_FILETYPE`).
fn has_filetype(&self) -> bool {
self.sb.feature_incompat & constants::feature::INCOMPAT_FILETYPE != 0
}
/// The filesystem-wide checksum seed. genfs never sets the
/// `metadata_csum_seed` feature, so the seed is always derived from the
/// UUID.
fn csum_seed(&self) -> u32 {
csum::fs_seed(&self.sb.uuid, None)
}
/// Wire `data_blocks` into an inode's block-pointer array. Picks the
/// representation based on the filesystem kind: ext4 uses an extent
/// tree (depth 0, up to 4 leaves, no extra metadata blocks); ext2/3 use
/// the classic direct + single-indirect + double-indirect scheme.
/// Returns the number of metadata (indirection) blocks allocated.
fn fill_block_pointers(&mut self, inode: &mut Inode, data: &[u32]) -> Result<u32> {
if matches!(self.kind, FsKind::Ext4) {
return self.fill_block_pointers_extent(inode, data);
}
self.fill_block_pointers_indirect(inode, data)
}
/// Ext4 path: pack `data` into an extent tree stored directly in
/// `i_block` and set `EXT4_EXTENTS_FL` on the inode. Allocates no extra
/// metadata blocks for depth-0 trees (the cap is 4 extents per inode).
fn fill_block_pointers_extent(&mut self, inode: &mut Inode, data: &[u32]) -> Result<u32> {
let runs = extent::coalesce(data);
let packed = extent::pack_into_iblock(&runs)?;
// Decode the 60 packed bytes back into the 15 u32 slots of i_block.
for (i, slot) in inode.block.iter_mut().enumerate() {
let off = i * 4;
*slot = u32::from_le_bytes(packed[off..off + 4].try_into().unwrap());
}
inode.flags |= constants::EXT4_EXTENTS_FL;
Ok(0)
}
/// Ext2 / Ext3 path: direct + single + double indirection. v1 cap.
/// At 1 KiB blocks that's up to 12 + 256 + 256² ≈ 65 MiB; at 4 KiB
/// it's ~4 GiB.
///
/// A `0` in `data` is a hole (sparse file): the corresponding block
/// pointer stays 0, and an indirect block whose entire range is holes
/// is not allocated at all.
fn fill_block_pointers_indirect(&mut self, inode: &mut Inode, data: &[u32]) -> Result<u32> {
let bs = self.layout.block_size;
let ptrs_per_block = (bs / 4) as usize;
let n = data.len();
let n_direct = constants::N_DIRECT.min(n);
inode.block[..n_direct].copy_from_slice(&data[..n_direct]);
let mut allocated_meta = 0u32;
let mut consumed = n_direct;
if consumed < n {
// Single-indirect — only allocate the indirect block if at least
// one block in its range is actually present.
let take = (n - consumed).min(ptrs_per_block);
let range = &data[consumed..consumed + take];
if range.iter().any(|&b| b != 0) {
let ind = self.alloc_data_block()?;
allocated_meta += 1;
inode.block[constants::IDX_INDIRECT] = ind;
let mut buf = vec![0u8; bs as usize];
for (i, &b) in range.iter().enumerate() {
buf[i * 4..i * 4 + 4].copy_from_slice(&b.to_le_bytes());
}
self.data_blocks.push((ind, buf));
}
consumed += take;
}
if consumed < n {
// Double-indirect. Each sub-indirect block is allocated only if
// its range has a non-hole block; the double-indirect block
// itself is allocated only if at least one sub-indirect is.
let mut dind_buf = vec![0u8; bs as usize];
let mut dind_slot = 0;
let mut any_sub = false;
while consumed < n {
if dind_slot >= ptrs_per_block {
return Err(crate::Error::Unsupported(
"ext: file exceeds direct+single+double indirection capacity".into(),
));
}
let take = (n - consumed).min(ptrs_per_block);
let range = &data[consumed..consumed + take];
if range.iter().any(|&b| b != 0) {
let ind = self.alloc_data_block()?;
allocated_meta += 1;
any_sub = true;
dind_buf[dind_slot * 4..dind_slot * 4 + 4].copy_from_slice(&ind.to_le_bytes());
let mut ind_buf = vec![0u8; bs as usize];
for (i, &b) in range.iter().enumerate() {
ind_buf[i * 4..i * 4 + 4].copy_from_slice(&b.to_le_bytes());
}
self.data_blocks.push((ind, ind_buf));
}
consumed += take;
dind_slot += 1;
}
if any_sub {
let dind = self.alloc_data_block()?;
allocated_meta += 1;
inode.block[constants::IDX_DOUBLE_INDIRECT] = dind;
self.data_blocks.push((dind, dind_buf));
}
}
Ok(allocated_meta)
}
/// Allocate the journal inode (inode 8) and its data blocks. The first
/// data block is initialised with a JBD2 v2 journal superblock marking
/// the journal as clean (s_start = 0, so no recovery needed). The rest
/// of the journal is zeroed by the up-front zero_range, which JBD2
/// reads as empty log blocks.
fn allocate_journal(&mut self, blocks: u32, mtime: u32) -> Result<()> {
let ino = constants::INO_JOURNAL;
let bs = self.layout.block_size;
let mut data = Vec::with_capacity(blocks as usize);
for _ in 0..blocks {
data.push(self.alloc_data_block()?);
}
let mut inode = Inode::regular(blocks * bs, 0o600, 0, 0, mtime);
let meta_blocks = self.fill_block_pointers(&mut inode, &data)?;
inode.blocks_512 = (blocks + meta_blocks) * (bs / 512);
// Build the JBD2 v2 journal superblock for block 0 of the journal.
let jsb = build_jbd2_superblock(bs, blocks);
self.data_blocks.push((data[0], jsb));
self.inodes.push((ino, inode));
Ok(())
}
/// Allocate inode #2 (the root dir), give it a fresh data block with
/// "." and "..", and stage both for write.
fn create_root(&mut self, mtime: u32) -> Result<()> {
let ino = INO_ROOT_DIR;
set_bit(&mut self.groups[0].inode_bitmap, ino - 1);
let blk = self.alloc_data_block()?;
let csum_tail = self.has_metadata_csum();
let with_filetype = self.has_filetype();
let block_bytes =
dir::make_initial_dir_block(ino, ino, self.layout.block_size, with_filetype, csum_tail);
let mut inode = Inode::directory(self.layout.block_size, 0o755, 0, 0, mtime);
inode.block[0] = blk;
inode.blocks_512 = self.layout.block_size / 512;
self.groups[0].desc.used_dirs_count += 1;
self.inodes.push((ino, inode));
self.data_blocks.push((blk, block_bytes));
self.dir_blocks.push((blk, ino));
Ok(())
}
/// Create the conventional /lost+found directory pre-allocated to 16 KiB.
fn create_lost_found(&mut self, dev: &mut dyn BlockDevice, mtime: u32) -> Result<()> {
let bs = self.layout.block_size;
let target_data_blocks: u32 = 16384u32.div_ceil(bs);
// Allocate inode first (uses next_inode).
let ino = self.alloc_inode()?;
// Allocate data blocks sequentially.
let mut data_blocks = Vec::with_capacity(target_data_blocks as usize);
for _ in 0..target_data_blocks {
data_blocks.push(self.alloc_data_block()?);
}
let mut inode = Inode::directory(16384, 0o700, 0, 0, mtime);
let meta_blocks = self.fill_block_pointers(&mut inode, &data_blocks)?;
inode.blocks_512 = (target_data_blocks + meta_blocks) * (bs / 512);
// First data block: "." / "..". All blocks of lost+found are
// directory blocks owned by inode `ino`.
let csum_tail = self.has_metadata_csum();
let with_filetype = self.has_filetype();
let dir_block =
dir::make_initial_dir_block(ino, INO_ROOT_DIR, bs, with_filetype, csum_tail);
self.data_blocks.push((data_blocks[0], dir_block));
self.dir_blocks.push((data_blocks[0], ino));
// All trailing data blocks: empty-placeholder entry so e2fsck reads
// them as well-formed empty dir blocks.
for &blk in &data_blocks[1..] {
self.data_blocks
.push((blk, dir::make_empty_dir_block(bs, csum_tail)));
self.dir_blocks.push((blk, ino));
}
self.groups[0].desc.used_dirs_count += 1;
self.inodes.push((ino, inode));
// Add to root dir + bump root's link count (a new subdir's ".." is
// a fresh link to the parent).
self.add_entry_to_dir_block_for(
dev,
INO_ROOT_DIR,
b"lost+found",
ino,
constants::DENT_DIR,
)?;
self.patch_inode(dev, INO_ROOT_DIR, |i| i.links_count += 1)?;
Ok(())
}
/// Append a dir entry into the data block(s) of the directory whose
/// inode is `dir_inode`. Walks the existing data blocks (last-to-first,
/// since appends cluster at the tail) and writes into the first one
/// with room; if every block is full, allocates a new data block,
/// extends the inode's block-pointer storage, and writes into the
/// fresh block.
fn add_entry_to_dir_block_for(
&mut self,
dev: &mut dyn BlockDevice,
dir_inode: u32,
name: &[u8],
child_ino: u32,
file_type: u8,
) -> Result<()> {
self.ensure_inode_staged(dev, dir_inode)?;
let bs = self.layout.block_size;
let usable = dir::usable_dir_len(bs, self.has_metadata_csum());
let with_filetype = self.has_filetype();
// HTree-indexed dir? Route by hash to the right leaf instead
// of scanning linearly. The leaf is always non-block-0 (block 0
// is the dx_root and never holds real entries).
let inode_copy = self
.inodes
.iter()
.find(|(i, _)| *i == dir_inode)
.map(|(_, i)| *i)
.unwrap();
if inode_copy.flags & constants::EXT4_INDEX_FL != 0 {
let logical_leaf = self.dx_route_logical_leaf(dev, dir_inode, name)?;
let phys = self.file_block(dev, &inode_copy, logical_leaf)?;
self.ensure_block_staged(dev, phys)?;
if !self.dir_blocks.iter().any(|(b, _)| *b == phys) {
self.dir_blocks.push((phys, dir_inode));
}
let block = self
.data_blocks
.iter_mut()
.find(|(b, _)| *b == phys)
.map(|(_, bytes)| bytes)
.unwrap();
if !try_append_dir_entry(block, name, child_ino, file_type, with_filetype, usable)? {
return Err(crate::Error::Unsupported(format!(
"ext: HTree leaf {phys} for dir {dir_inode} is full — bucket-split not implemented"
)));
}
return Ok(());
}
let n_blocks = inode_copy.size.div_ceil(bs);
// Try existing blocks last-to-first: the tail block is the only
// candidate with room under a build-only workload; falling back
// to earlier blocks covers the cold path where deletions opened
// slack.
for logical in (0..n_blocks).rev() {
let blk = self.file_block(dev, &inode_copy, logical)?;
if blk == 0 {
// Sparse gap inside a directory — skip.
continue;
}
self.ensure_block_staged(dev, blk)?;
if !self.dir_blocks.iter().any(|(b, _)| *b == blk) {
self.dir_blocks.push((blk, dir_inode));
}
let block = self
.data_blocks
.iter_mut()
.find(|(b, _)| *b == blk)
.map(|(_, bytes)| bytes)
.unwrap();
if try_append_dir_entry(block, name, child_ino, file_type, with_filetype, usable)? {
return Ok(());
}
}
// Every existing block is full (or there are none): grow the dir
// by one block and write the entry into it.
self.grow_dir_block_and_append(dev, dir_inode, name, child_ino, file_type)
}
/// Allocate one new data block for directory `dir_inode`, append it to
/// the inode's block-pointer storage (extents for ext4, direct +
/// single-indirect for ext2/3), initialise it as an empty dir block,
/// and write the new entry into it.
fn grow_dir_block_and_append(
&mut self,
dev: &mut dyn BlockDevice,
dir_inode: u32,
name: &[u8],
child_ino: u32,
file_type: u8,
) -> Result<()> {
let bs = self.layout.block_size;
let csum_tail = self.has_metadata_csum();
let with_filetype = self.has_filetype();
let usable = dir::usable_dir_len(bs, csum_tail);
let new_blk = self.alloc_data_block()?;
// Compute the next logical block index from the current inode size.
let inode_copy = self
.inodes
.iter()
.find(|(i, _)| *i == dir_inode)
.map(|(_, i)| *i)
.unwrap();
let new_logical = inode_copy.size.div_ceil(bs);
// Wire the new block into the inode's block-pointer storage.
let meta_blocks_added =
self.append_data_block_to_inode(dev, dir_inode, new_logical, new_blk)?;
// Grow i_size by one block and account for the new data block plus
// any indirection metadata that the append required.
let sectors_per_block = bs / 512;
self.patch_inode(dev, dir_inode, |i| {
i.size += bs;
i.blocks_512 += sectors_per_block * (1 + meta_blocks_added);
})?;
// Initialise the new dir block in memory (one empty placeholder
// entry spanning the usable region; csum tail stamped at flush).
let mut new_buf = dir::make_empty_dir_block(bs, csum_tail);
// Write the actual entry into the placeholder.
if !try_append_dir_entry(
&mut new_buf,
name,
child_ino,
file_type,
with_filetype,
usable,
)? {
return Err(crate::Error::Unsupported(format!(
"ext: dir entry for {:?} doesn't fit in a fresh {bs}-byte block",
String::from_utf8_lossy(name)
)));
}
self.data_blocks.push((new_blk, new_buf));
self.dir_blocks.push((new_blk, dir_inode));
Ok(())
}
/// Append a single new data block to the block-pointer storage of
/// inode `inode_no`. Dispatches on the extent-tree flag: extents for
/// ext4 inodes, classic direct + single-indirect for ext2/3 inodes.
///
/// Returns the number of newly allocated *metadata* blocks (indirect
/// blocks for ext2/3, extent-tree leaves for ext4) so the caller can
/// fold them into `blocks_512`. The data block itself is allocated by
/// the caller and is not counted here.
fn append_data_block_to_inode(
&mut self,
dev: &mut dyn BlockDevice,
inode_no: u32,
new_logical: u32,
new_phys: u32,
) -> Result<u32> {
let uses_extents = self
.inodes
.iter()
.find(|(i, _)| *i == inode_no)
.map(|(_, i)| i.flags & constants::EXT4_EXTENTS_FL != 0)
.unwrap();
if uses_extents {
self.append_extent_inline(dev, inode_no, new_logical, new_phys)
} else {
self.append_indirect_block(dev, inode_no, new_logical, new_phys)
}
}
/// Append `new_phys` (at logical block `new_logical`) to an
/// inline-extent-tree inode. Tries to extend the last extent first
/// (zero allocation, best for the typical contiguous case); otherwise
/// adds a new extent. Promotes a depth-0 tree to depth-1 when more
/// than 4 leaf extents would be needed, and appends into an existing
/// depth-1 tree's last leaf.
///
/// Returns the number of newly allocated metadata blocks (extent
/// leaves) so the caller can fold them into `blocks_512`.
fn append_extent_inline(
&mut self,
dev: &mut dyn BlockDevice,
inode_no: u32,
new_logical: u32,
new_phys: u32,
) -> Result<u32> {
let inode_copy = self
.inodes
.iter()
.find(|(i, _)| *i == inode_no)
.map(|(_, i)| *i)
.unwrap();
let iblock = extent::iblock_to_bytes(&inode_copy.block);
let header = extent::decode_header(&iblock[..12])?;
match header.depth {
0 => self.append_extent_depth0(dev, inode_no, &iblock, new_logical, new_phys),
1 => self.append_extent_depth1(dev, inode_no, new_logical, new_phys),
d => Err(crate::Error::Unsupported(format!(
"ext4: extent tree depth {d} growth not supported (writer caps at depth-1)"
))),
}
}
/// Depth-0 append: try last-extent extension, fall back to adding a
/// new extent. If that would exceed the 4-extent inline cap, promote
/// the tree to depth-1.
fn append_extent_depth0(
&mut self,
dev: &mut dyn BlockDevice,
inode_no: u32,
iblock: &[u8; 60],
new_logical: u32,
new_phys: u32,
) -> Result<u32> {
let (_, mut runs) = extent::decode_depth0_iblock(iblock)?;
let extended = if let Some(last) = runs.last_mut() {
last.physical + last.len as u64 == new_phys as u64
&& (last.logical + last.len as u32) == new_logical
&& last.len < extent::MAX_LEN_PER_EXTENT
&& {
last.len += 1;
true
}
} else {
false
};
if !extended {
runs.push(extent::ExtentRun {
logical: new_logical,
len: 1,
physical: new_phys as u64,
});
}
if runs.len() <= extent::MAX_EXTENTS_IN_INODE {
let packed = extent::pack_into_iblock(&runs)?;
self.patch_inode(dev, inode_no, |i| {
i.block = extent::bytes_to_iblock(&packed);
})?;
return Ok(0);
}
// Promote depth-0 → depth-1. With locality-favouring sequential
// allocation, runs.len() usually stays small; we still need this
// path when files are interleaved with directory growth.
self.promote_extent_tree_to_depth1(dev, inode_no, runs)
}
/// Rebuild the inode's extent tree as a depth-1 layout: one idx node
/// inline in `i_block`, plus N leaf blocks (each capped to `per_leaf`
/// extents). Allocates the leaf blocks fresh, stages them in
/// `data_blocks`, and tracks them for CRC stamping when
/// `metadata_csum` is on.
fn promote_extent_tree_to_depth1(
&mut self,
dev: &mut dyn BlockDevice,
inode_no: u32,
runs: Vec<extent::ExtentRun>,
) -> Result<u32> {
let bs = self.layout.block_size;
let csum_tail = self.has_metadata_csum();
let per_leaf = extent::entries_per_leaf_block_capped(bs, csum_tail);
let need_leaves = runs.len().div_ceil(per_leaf);
if need_leaves > extent::MAX_INDICES_IN_INODE {
return Err(crate::Error::Unsupported(format!(
"ext4: depth-1 tree needs {need_leaves} leaf blocks, max {} inline (depth>1 not supported)",
extent::MAX_INDICES_IN_INODE
)));
}
let mut leaf_phys = Vec::with_capacity(need_leaves);
for _ in 0..need_leaves {
leaf_phys.push(self.alloc_data_block()?);
}
let (i_block_bytes, leaf_images) = extent::pack_depth1(&runs, bs, csum_tail, &leaf_phys)?;
for (phys, image) in leaf_phys.iter().zip(leaf_images) {
// Stage in data_blocks; track for CRC stamping at flush.
if let Some(slot) = self.data_blocks.iter_mut().find(|(b, _)| b == phys) {
slot.1 = image;
} else {
self.data_blocks.push((*phys, image));
}
self.track_extent_leaf_block(*phys, inode_no);
}
self.patch_inode(dev, inode_no, |i| {
i.block = extent::bytes_to_iblock(&i_block_bytes);
})?;
Ok(need_leaves as u32)
}
/// Depth-1 append: walk the idx array, load the last leaf block,
/// extend its last extent or add a new one; if that leaf is full,
/// allocate another leaf and add an idx entry pointing at it (capped
/// at 4 inline idx entries — beyond that we'd need depth-2).
fn append_extent_depth1(
&mut self,
dev: &mut dyn BlockDevice,
inode_no: u32,
new_logical: u32,
new_phys: u32,
) -> Result<u32> {
let bs = self.layout.block_size;
let csum_tail = self.has_metadata_csum();
let per_leaf = extent::entries_per_leaf_block_capped(bs, csum_tail);
let inode_copy = self
.inodes
.iter()
.find(|(i, _)| *i == inode_no)
.map(|(_, i)| *i)
.unwrap();
let iblock = extent::iblock_to_bytes(&inode_copy.block);
let (_, mut indices) = extent::decode_idx_iblock(&iblock)?;
if indices.is_empty() {
return Err(crate::Error::InvalidImage(
"ext4: depth-1 extent tree with zero idx entries".into(),
));
}
// Append to the LAST leaf block (the only candidate with room
// under the streaming-build workload).
let last_idx = indices.last().copied().unwrap();
let last_leaf_phys = last_idx.leaf as u32;
self.ensure_block_staged(dev, last_leaf_phys)?;
self.track_extent_leaf_block(last_leaf_phys, inode_no);
let leaf_bytes = self
.data_blocks
.iter()
.find(|(b, _)| *b == last_leaf_phys)
.map(|(_, bytes)| bytes.clone())
.unwrap();
let (leaf_header, mut leaf_runs) = extent::decode_leaf_block(&leaf_bytes[..bs as usize])?;
let _ = leaf_header;
// Try extending the last extent on the last leaf.
let extended = if let Some(last) = leaf_runs.last_mut() {
last.physical + last.len as u64 == new_phys as u64
&& (last.logical + last.len as u32) == new_logical
&& last.len < extent::MAX_LEN_PER_EXTENT
&& {
last.len += 1;
true
}
} else {
false
};
let mut allocated_meta = 0u32;
if extended {
// Re-encode the last leaf in place.
let new_image = extent::encode_leaf_block(&leaf_runs, bs, csum_tail)?;
if let Some(slot) = self
.data_blocks
.iter_mut()
.find(|(b, _)| *b == last_leaf_phys)
{
slot.1 = new_image;
}
return Ok(allocated_meta);
}
// Try adding a new extent into the last leaf.
if leaf_runs.len() < per_leaf {
leaf_runs.push(extent::ExtentRun {
logical: new_logical,
len: 1,
physical: new_phys as u64,
});
let new_image = extent::encode_leaf_block(&leaf_runs, bs, csum_tail)?;
if let Some(slot) = self
.data_blocks
.iter_mut()
.find(|(b, _)| *b == last_leaf_phys)
{
slot.1 = new_image;
}
return Ok(allocated_meta);
}
// Last leaf is full. Allocate a new leaf with the single new
// extent, and add an idx entry pointing at it.
if indices.len() >= extent::MAX_INDICES_IN_INODE {
return Err(crate::Error::Unsupported(format!(
"ext4: depth-1 tree has {} idx slots filled with full leaves; depth-2 not supported",
indices.len()
)));
}
let new_leaf_phys = self.alloc_data_block()?;
allocated_meta += 1;
let new_run = extent::ExtentRun {
logical: new_logical,
len: 1,
physical: new_phys as u64,
};
let new_leaf_image = extent::encode_leaf_block(&[new_run], bs, csum_tail)?;
self.data_blocks.push((new_leaf_phys, new_leaf_image));
self.track_extent_leaf_block(new_leaf_phys, inode_no);
indices.push(extent::ExtentIdx {
block: new_logical,
leaf: new_leaf_phys as u64,
});
let packed = extent::pack_idx_into_iblock(&indices)?;
self.patch_inode(dev, inode_no, |i| {
i.block = extent::bytes_to_iblock(&packed);
})?;
Ok(allocated_meta)
}
/// Append `new_phys` (at logical block `new_logical`) to an ext2/3
/// inode using direct + single-indirect block pointers. Allocates an
/// indirect block on demand (returning 1 in that case so the caller
/// folds it into `blocks_512`).
fn append_indirect_block(
&mut self,
dev: &mut dyn BlockDevice,
inode_no: u32,
new_logical: u32,
new_phys: u32,
) -> Result<u32> {
let bs = self.layout.block_size;
let ptrs_per_block = bs / 4;
let n_direct = constants::N_DIRECT as u32;
if new_logical < n_direct {
self.patch_inode(dev, inode_no, |i| {
i.block[new_logical as usize] = new_phys;
})?;
return Ok(0);
}
let single_off = new_logical - n_direct;
if single_off >= ptrs_per_block {
return Err(crate::Error::Unsupported(format!(
"ext: directory grew past single-indirect capacity at logical block {new_logical}"
)));
}
// Locate (or allocate) the single-indirect block.
let inode_copy = self
.inodes
.iter()
.find(|(i, _)| *i == inode_no)
.map(|(_, i)| *i)
.unwrap();
let (ind_blk, meta_added) = match inode_copy.block[constants::IDX_INDIRECT] {
0 => {
let blk = self.alloc_data_block()?;
self.patch_inode(dev, inode_no, |i| {
i.block[constants::IDX_INDIRECT] = blk;
})?;
// Initialise the indirect block to all zeros (the holes
// pattern); the slot we're about to write is the only
// non-zero entry initially.
self.data_blocks.push((blk, vec![0u8; bs as usize]));
(blk, 1u32)
}
existing => {
self.ensure_block_staged(dev, existing)?;
(existing, 0u32)
}
};
let ind_buf = self
.data_blocks
.iter_mut()
.find(|(b, _)| *b == ind_blk)
.map(|(_, bytes)| bytes)
.unwrap();
let off = single_off as usize * 4;
ind_buf[off..off + 4].copy_from_slice(&new_phys.to_le_bytes());
Ok(meta_added)
}
/// Mutate an inode in place. If the inode isn't already in the staged
/// cache, reads it from disk first so the mutation is preserved across
/// the next flush.
fn patch_inode<F: FnOnce(&mut Inode)>(
&mut self,
dev: &mut dyn BlockDevice,
ino: u32,
f: F,
) -> Result<()> {
self.ensure_inode_staged(dev, ino)?;
for (i_no, i) in self.inodes.iter_mut() {
if *i_no == ino {
f(i);
return Ok(());
}
}
unreachable!("ensure_inode_staged guarantees the inode is present")
}
/// Ensure inode `ino` is in the staged write set, fetching from disk if
/// not. No-op if already staged.
pub(crate) fn ensure_inode_staged(
&mut self,
dev: &mut dyn BlockDevice,
ino: u32,
) -> Result<()> {
if self.inodes.iter().any(|(i, _)| *i == ino) {
return Ok(());
}
let inode = self.read_inode(dev, ino)?;
self.inodes.push((ino, inode));
Ok(())
}
/// Ensure block `blk` is in the staged write set, fetching from disk
/// if not. No-op if already staged.
fn ensure_block_staged(&mut self, dev: &mut dyn BlockDevice, blk: u32) -> Result<()> {
if self.data_blocks.iter().any(|(b, _)| *b == blk) {
return Ok(());
}
let mut buf = vec![0u8; self.layout.block_size as usize];
self.read_block(dev, blk, &mut buf)?;
self.data_blocks.push((blk, buf));
Ok(())
}
/// Reserve the next available inode. Inode `N` lives in group
/// `(N-1) / inodes_per_group` at bitmap bit `(N-1) % inodes_per_group`,
/// so a monotonic `next_inode` counter spans all groups.
fn alloc_inode(&mut self) -> Result<u32> {
if self.next_inode > self.layout.inodes_count {
return Err(crate::Error::Unsupported(format!(
"ext: out of inodes (allocated {}, max {})",
self.next_inode - 1,
self.layout.inodes_count
)));
}
let ino = self.next_inode;
let g = ((ino - 1) / self.layout.inodes_per_group) as usize;
let idx = (ino - 1) % self.layout.inodes_per_group;
set_bit(&mut self.groups[g].inode_bitmap, idx);
self.next_inode += 1;
Ok(ino)
}
/// Allocate a single data block. Scans groups in order and returns the
/// first free data block, so callers get contiguous runs within a group
/// (good for extent coalescing) and spill into later groups when a group
/// fills up.
pub(crate) fn alloc_data_block(&mut self) -> Result<u32> {
for gi in 0..self.layout.groups.len() {
let layout_g = self.layout.groups[gi];
let start_rel = layout_g.data_start - layout_g.start_block;
let group_blocks = layout_g.end_block - layout_g.start_block + 1;
let bitmap = &mut self.groups[gi].block_bitmap;
for bit in start_rel..group_blocks {
if !test_bit(bitmap, bit) {
set_bit(bitmap, bit);
return Ok(layout_g.start_block + bit);
}
}
}
Err(crate::Error::Unsupported(
"ext: filesystem has no free data blocks".into(),
))
}
fn recompute_free_counts(&mut self) {
let mut total_free_blocks = 0u64;
let mut total_free_inodes = 0u64;
for (i, g) in self.layout.groups.iter().enumerate() {
let group_blocks = g.end_block - g.start_block + 1;
let used_blocks = popcount_bits(&self.groups[i].block_bitmap, 0, group_blocks);
let free_blocks = group_blocks - used_blocks;
let used_inodes = popcount_bits(
&self.groups[i].inode_bitmap,
0,
self.layout.inodes_per_group,
);
let free_inodes = self.layout.inodes_per_group - used_inodes;
self.groups[i].desc.free_blocks_count = free_blocks as u16;
self.groups[i].desc.free_inodes_count = free_inodes as u16;
total_free_blocks += free_blocks as u64;
total_free_inodes += free_inodes as u64;
}
self.sb.free_blocks_count = total_free_blocks as u32;
self.sb.free_inodes_count = total_free_inodes as u32;
}
/// Write all staged state to the device. Primary superblock is written
/// **last** to maintain the "torn write → unmountable, not corrupt"
/// invariant. When the filesystem has a JBD2 journal the metadata
/// updates ride a real journal transaction (descriptor + data + commit);
/// otherwise they go straight to the device (ext2 path).
fn flush_metadata(&mut self, dev: &mut dyn BlockDevice) -> Result<()> {
// Stamp dir-block checksum tails into `data_blocks` before we
// serialise the metadata image set; the journal must carry the
// checksum-stamped versions.
self.stamp_dir_block_checksums();
// Build the block-aligned metadata image set: every full-block
// write that flush would emit (bitmaps, GDTs, inode-table blocks,
// staged dir / extent leaf / indirect blocks). Excludes the
// primary and backup superblocks: those are written outside the
// journal as the final step.
let images = self.collect_metadata_images(dev)?;
// Initial format flush ("bootstrap") writes every block directly
// — the journal SB itself is in `images` and has no prior on-disk
// state to stay consistent with. Subsequent flushes on an image
// that carries a journal go through the JBD2 commit/checkpoint
// path so a crash mid-flush leaves a replayable transaction in
// the log instead of a torn metadata block.
if self.has_journal() && !self.bootstrap {
self.commit_journal_and_checkpoint(dev, &images)?;
} else {
for (blk, bytes) in &images {
let bs = self.layout.block_size as u64;
dev.write_at(*blk as u64 * bs, bytes)?;
}
}
// Backup SB copies and the primary SB. The primary SB is the very
// last write to preserve the "torn write → unmountable, not
// corrupt" invariant.
self.write_superblocks(dev)?;
dev.sync()?;
// Subsequent flushes (e.g. from open_file_rw) ride the journal.
self.bootstrap = false;
// The staged dir / extent leaf / indirect data blocks have
// landed on disk; drop them so the next flush only journals
// genuine new edits (not stale snapshots from before this
// flush). `self.inodes` is kept around — open file handles
// assume their inode stays staged across `sync` calls.
self.data_blocks.clear();
self.dir_blocks.clear();
self.extent_leaf_blocks.clear();
self.dx_root_blocks.clear();
self.dx_node_blocks.clear();
Ok(())
}
/// Stamp every staged metadata block's CRC32C tail in place: regular
/// dir blocks (12-byte trailing dirent + CRC), extent-tree leaf
/// blocks (4-byte `ext4_extent_tail`), and HTree dx_root blocks
/// (8-byte `dx_tail` covering only the in-use prefix). No-op when
/// `metadata_csum` is off. Called by [`flush_metadata`] before the
/// journal commit so the journaled image matches what the checkpoint
/// phase writes to each block's home location.
fn stamp_dir_block_checksums(&mut self) {
if !self.has_metadata_csum() {
return;
}
let seed = self.csum_seed();
for (blk, bytes) in &mut self.data_blocks {
// dx_root: distinct csum layout (dt_tail at the very end,
// covers only `count_offset + count * 8` bytes from the
// start). Check this BEFORE the generic dir_blocks lookup
// because dx_root blocks aren't tagged in dir_blocks.
if let Some((_, owner_ino, count)) = self
.dx_root_blocks
.iter()
.find(|(b, _, _)| b == blk)
.copied()
{
let generation = self
.inodes
.iter()
.find(|(i, _)| *i == owner_ino)
.map(|(_, i)| i.generation)
.unwrap_or(0);
let c = htree::compute_dx_csum(
csum::raw_update,
seed,
owner_ino,
generation,
bytes,
htree::DX_ROOT_HEADER_LEN,
count as usize,
);
htree::stamp_dx_csum(bytes, c);
continue;
}
// dx_node: same csum scheme but smaller header (12 bytes
// for the fake dirent vs 32 for dx_root's `.`/`..`/info).
if let Some((_, owner_ino, count)) = self
.dx_node_blocks
.iter()
.find(|(b, _, _)| b == blk)
.copied()
{
let generation = self
.inodes
.iter()
.find(|(i, _)| *i == owner_ino)
.map(|(_, i)| i.generation)
.unwrap_or(0);
let c = htree::compute_dx_csum(
csum::raw_update,
seed,
owner_ino,
generation,
bytes,
htree::DX_NODE_HEADER_LEN,
count as usize,
);
htree::stamp_dx_csum(bytes, c);
continue;
}
if let Some((_, dir_ino)) = self.dir_blocks.iter().find(|(b, _)| b == blk) {
let generation = self
.inodes
.iter()
.find(|(i, _)| i == dir_ino)
.map(|(_, i)| i.generation)
.unwrap_or(0);
let n = bytes.len();
let c = csum::dir_block(seed, *dir_ino, generation, &bytes[..n - 12]);
bytes[n - 4..].copy_from_slice(&c.to_le_bytes());
continue;
}
if let Some((_, owner_ino)) = self.extent_leaf_blocks.iter().find(|(b, _)| b == blk) {
let generation = self
.inodes
.iter()
.find(|(i, _)| i == owner_ino)
.map(|(_, i)| i.generation)
.unwrap_or(0);
let n = bytes.len();
let c = csum::extent_tail(seed, *owner_ino, generation, &bytes[..n - 4]);
bytes[n - 4..].copy_from_slice(&c.to_le_bytes());
}
}
}
/// Register `blk` as an extent-tree leaf block owned by `inode_no`.
/// At flush time the per-block `ext4_extent_tail` CRC32C is stamped
/// against this inode's number + generation. Idempotent.
pub(crate) fn track_extent_leaf_block(&mut self, blk: u32, inode_no: u32) {
if !self.extent_leaf_blocks.iter().any(|(b, _)| *b == blk) {
self.extent_leaf_blocks.push((blk, inode_no));
}
}
/// Reverse of [`track_extent_leaf_block`]: drop the record so a freed
/// leaf block is no longer stamped on flush.
pub(crate) fn untrack_extent_leaf_block(&mut self, blk: u32) {
self.extent_leaf_blocks.retain(|(b, _)| *b != blk);
}
/// Build the block-aligned metadata image set (block_no, full-block
/// bytes). Includes bitmaps (every group), GDT blocks (every backup
/// group + group 0), inode-table blocks (each block patched with all
/// staged inodes whose slot falls inside it), and staged data blocks
/// (dir / extent leaf / indirect). Does NOT include superblocks.
fn collect_metadata_images(&self, dev: &mut dyn BlockDevice) -> Result<Vec<(u32, Vec<u8>)>> {
let bs = self.layout.block_size as u64;
let mut out: Vec<(u32, Vec<u8>)> = Vec::new();
// Build encoded GDT (same content for every group's copy). With
// metadata_csum each descriptor's bg_checksum + bitmap checksums
// are stamped here.
let desc_size = self.layout.desc_size;
let with_csum = self.has_metadata_csum();
let seed = self.csum_seed();
let bbm_len = (self.layout.blocks_per_group / 8) as usize;
let ibm_len = (self.layout.inodes_per_group / 8) as usize;
let mut gdt = vec![0u8; self.layout.gdt_blocks as usize * bs as usize];
for (i, g) in self.groups.iter().enumerate() {
let off = i * desc_size;
let desc = &mut gdt[off..off + desc_size];
desc[..constants::GROUP_DESC_SIZE].copy_from_slice(&g.desc.encode());
if with_csum {
let bbm_full = csum::bitmap(seed, &g.block_bitmap[..bbm_len]);
let ibm_full = csum::bitmap(seed, &g.inode_bitmap[..ibm_len]);
let bbm_lo = bbm_full as u16;
let ibm_lo = ibm_full as u16;
desc[0x18..0x1A].copy_from_slice(&bbm_lo.to_le_bytes());
desc[0x1A..0x1C].copy_from_slice(&ibm_lo.to_le_bytes());
if desc_size >= 64 {
let bbm_hi = (bbm_full >> 16) as u16;
let ibm_hi = (ibm_full >> 16) as u16;
desc[0x38..0x3A].copy_from_slice(&bbm_hi.to_le_bytes());
desc[0x3A..0x3C].copy_from_slice(&ibm_hi.to_le_bytes());
}
let bg = csum::group_desc(seed, i as u32, desc);
desc[0x1E..0x20].copy_from_slice(&bg.to_le_bytes());
}
}
// Bitmaps and GDT copies, per group.
for (i, g) in self.layout.groups.iter().enumerate() {
if g.has_superblock {
// The GDT itself; SB backup is handled by write_superblocks.
let gdt_start_block = if i == 0 {
if self.layout.first_data_block == 1 {
2u32
} else {
1u32
}
} else {
g.start_block + 1
};
for (blk_off, chunk) in gdt.chunks(bs as usize).enumerate() {
out.push((gdt_start_block + blk_off as u32, chunk.to_vec()));
}
}
out.push((g.block_bitmap, self.groups[i].block_bitmap.clone()));
out.push((g.inode_bitmap, self.groups[i].inode_bitmap.clone()));
}
// Inode-table blocks: group staged inodes by their containing
// table block, then RMW each block.
let inode_size = self.layout.inode_size as u64;
let inodes_per_block = (bs / inode_size) as u32;
let mut by_block: std::collections::BTreeMap<u32, Vec<(u32, &Inode)>> =
std::collections::BTreeMap::new();
for (ino, inode) in &self.inodes {
let (group, idx_in_group) = self.inode_location(*ino);
let table_block = self.layout.groups[group as usize].inode_table;
let block_off = idx_in_group / inodes_per_block;
let blk = table_block + block_off;
by_block.entry(blk).or_default().push((*ino, inode));
}
for (blk, slots) in by_block {
// RMW: start from the current on-disk content. We avoid
// touching staged data_blocks here because inode-table blocks
// are not staged in `data_blocks` (only dirs / extent leaves
// / indirects are).
let mut buf = vec![0u8; bs as usize];
dev.read_at(blk as u64 * bs, &mut buf)?;
for (ino, inode) in slots {
let (_, idx_in_group) = self.inode_location(ino);
let inblock_idx = idx_in_group % inodes_per_block;
let off = inblock_idx as u64 * inode_size;
let encoded = self.encode_inode(ino, inode);
let body_len = encoded.len().min(inode_size as usize);
buf[off as usize..off as usize + body_len].copy_from_slice(&encoded[..body_len]);
// Tail bytes (i_extra_isize region of large inodes, if any)
// are left as their on-disk values.
}
out.push((blk, buf));
}
// Staged data blocks (directories, extent leaves, indirect blocks).
// These are already block-sized in `data_blocks`. Dir-block
// checksums are already stamped (stamp_dir_block_checksums).
for (blk, bytes) in &self.data_blocks {
out.push((*blk, bytes.clone()));
}
// De-duplicate by block number, keeping the latest write per block
// (a later entry wins). This matters when, e.g., an inode-table
// block is also staged as a generic data block (shouldn't happen
// today, but the guard is cheap and keeps the journal payload
// free of duplicates).
let mut seen: std::collections::BTreeMap<u32, Vec<u8>> = std::collections::BTreeMap::new();
for (blk, bytes) in out {
seen.insert(blk, bytes);
}
Ok(seen.into_iter().collect())
}
/// Write the GDT + bitmap + inode + data-block updates as a single
/// JBD2 transaction, fsync, then checkpoint by writing the same blocks
/// to their target FS locations.
fn commit_journal_and_checkpoint(
&mut self,
dev: &mut dyn BlockDevice,
images: &[(u32, Vec<u8>)],
) -> Result<()> {
let jino = self.sb.journal_inum;
if jino == 0 {
return Err(crate::Error::InvalidImage(
"ext: HAS_JOURNAL set but s_journal_inum is 0".into(),
));
}
let bs = self.layout.block_size;
if images.is_empty() {
// Nothing to journal; SB will still be written by the caller.
return Ok(());
}
// Read journal SB and inode. The journal SB may be staged in
// `data_blocks` (first flush after format) — consult that cache
// before falling back to the device.
let journal_inode = self.read_inode(dev, jino)?;
let jsb_phys = self.file_block(dev, &journal_inode, 0)?;
if jsb_phys == 0 {
return Err(crate::Error::InvalidImage(
"ext: journal block 0 unmapped".into(),
));
}
let mut jsb_buf = vec![0u8; bs as usize];
self.read_block(dev, jsb_phys, &mut jsb_buf)?;
let jsb = jbd2::JournalSuperblock::decode(&jsb_buf)?;
if jsb.blocksize != bs {
return Err(crate::Error::InvalidImage(format!(
"ext: journal blocksize {} != FS blocksize {bs}",
jsb.blocksize
)));
}
// Build payload list.
let blocks: Vec<jbd2::JournalBlock> = images
.iter()
.map(|(blk, bytes)| jbd2::JournalBlock {
fs_block: *blk,
bytes: bytes.clone(),
})
.collect();
// Pick the next tid and the start of the log ring. Path A v1 only
// writes one transaction at a time, starting at `s_first`; the
// ring isn't reused mid-flush.
let tid = jsb.sequence;
let start_idx = jsb.first;
let _next_idx = jbd2::write_transaction(
self,
dev,
&journal_inode,
&mut jsb_buf,
&jsb,
start_idx,
tid,
&blocks,
self.sb.wtime as u64,
0,
)?;
dev.sync()?;
// Now stamp s_start + s_sequence so a crash from here on yields
// a replayable journal: replay will see this exact transaction
// and re-apply it.
jbd2::set_start(&mut jsb_buf, start_idx);
jbd2::set_sequence(&mut jsb_buf, tid);
dev.write_at(jsb_phys as u64 * bs as u64, &jsb_buf)?;
dev.sync()?;
// Checkpoint: write each block image to its FS-home location.
let bs64 = bs as u64;
for (blk, bytes) in images {
dev.write_at(*blk as u64 * bs64, bytes)?;
}
dev.sync()?;
// Mark the journal clean: s_start = 0, s_sequence = tid + 1. A
// future open sees a clean journal and skips replay.
jbd2::set_start(&mut jsb_buf, 0);
jbd2::set_sequence(&mut jsb_buf, tid.wrapping_add(1));
dev.write_at(jsb_phys as u64 * bs as u64, &jsb_buf)?;
Ok(())
}
/// Write every group's superblock copy (primary and any backups).
/// Called as the final phase of `flush_metadata` so a torn write of
/// the primary leaves the on-disk state mountable from a backup.
fn write_superblocks(&self, dev: &mut dyn BlockDevice) -> Result<()> {
let bs = self.layout.block_size as u64;
for (i, g) in self.layout.groups.iter().enumerate() {
if g.has_superblock && i != 0 {
let mut sb_copy = self.sb.clone();
sb_copy.block_group_nr = i as u16;
dev.write_at(g.start_block as u64 * bs, &self.encode_sb(&sb_copy))?;
}
}
dev.write_at(SUPERBLOCK_OFFSET, &self.encode_sb(&self.sb))?;
Ok(())
}
/// Whether the filesystem has a JBD2 journal (`COMPAT_HAS_JOURNAL`)
/// AND it's not an external journal device.
fn has_journal(&self) -> bool {
self.sb.feature_compat & constants::feature::COMPAT_HAS_JOURNAL != 0
&& self.sb.feature_incompat & constants::feature::INCOMPAT_JOURNAL_DEV == 0
}
/// Encode an inode, stamping its CRC32C checksum (`l_i_checksum_lo` at
/// offset 124) when `metadata_csum` is set. With 128-byte inodes there
/// is no room for `i_checksum_hi`, so only the low 16 bits are stored —
/// the kernel handles a 16-bit inode checksum for small inodes.
fn encode_inode(&self, ino: u32, inode: &Inode) -> [u8; inode::INODE_BASE_SIZE] {
let mut buf = inode.encode();
if self.has_metadata_csum() {
// Zero the checksum field before summing — an inode read back
// from disk (modify-after-open) carries its previous checksum
// in osd2, which must not feed into the recomputed value.
buf[124..126].fill(0);
let c = csum::inode(self.csum_seed(), ino, inode.generation, &buf);
buf[124..126].copy_from_slice(&((c & 0xffff) as u16).to_le_bytes());
}
buf
}
/// Encode a superblock, stamping the CRC32C `s_checksum` field when the
/// `metadata_csum` feature is set. Without the feature the field stays
/// zero (the kernel ignores it).
fn encode_sb(&self, sb: &Superblock) -> [u8; constants::SUPERBLOCK_SIZE] {
let mut buf = sb.encode();
if self.has_metadata_csum() {
// s_checksum_type (offset 0x175) must be 1 (CRC32C) — the kernel
// refuses to mount a metadata_csum FS otherwise. Set it before
// computing the checksum so it's covered.
buf[0x175] = 1;
let c = csum::superblock(&buf);
buf[1020..1024].copy_from_slice(&c.to_le_bytes());
}
buf
}
fn inode_location(&self, ino: u32) -> (u32, u32) {
let g = (ino - 1) / self.layout.inodes_per_group;
let idx = (ino - 1) % self.layout.inodes_per_group;
(g, idx)
}
// ──────────────────────────── populate API ───────────────────────────
//
// These methods stage in-memory state (bitmaps, inode table, dir blocks)
// and stream regular-file data straight to the device. Call
// [`Ext::flush`] when done to persist the staged metadata.
/// Create a regular file under `parent_ino` with the given name and
/// metadata, streaming bytes from `src` straight to the device through a
/// fixed-size buffer. The file is *never* fully resident in memory.
pub fn add_file_to(
&mut self,
dev: &mut dyn BlockDevice,
parent_ino: u32,
name: &[u8],
src: FileSource,
meta: FileMeta,
) -> Result<u32> {
let len = src.len()?;
let (mut reader, _) = src.open()?;
self.add_file_to_streaming(dev, parent_ino, name, &mut *reader, len, meta)
}
/// Like [`Self::add_file_to`] but pulls bytes from any [`std::io::Read`]
/// instead of a [`FileSource`]. Useful when streaming from a borrowed
/// reader (e.g. another filesystem's `open_file_reader`) where the
/// `'static` lifetime in `FileSource::Reader` doesn't fit.
pub fn add_file_to_streaming(
&mut self,
dev: &mut dyn BlockDevice,
parent_ino: u32,
name: &[u8],
reader: &mut dyn std::io::Read,
len: u64,
meta: FileMeta,
) -> Result<u32> {
let bs = self.layout.block_size;
if len > u32::MAX as u64 {
return Err(crate::Error::Unsupported(
"ext: file > 4 GiB requires LARGE_FILE (deferred to ext4)".into(),
));
}
// Inline-data fast path: files that fit in the inode's
// i_block array don't need a data block at all. Reduces
// small-file overhead from "1 inode + 1 data block" to "1
// inode" — a 10-byte file goes from 4 KiB on disk to ~128.
//
// The on-disk contract: when `EXT4_INLINE_DATA_FL` is set
// every such inode MUST carry a `system.data` xattr too (the
// kernel uses its presence as the "this inode is inline-data"
// probe; e2fsck enforces it). The xattr's value holds any
// overflow beyond i_block's 60 bytes — for files ≤ 60 bytes
// we stamp an empty value to satisfy the invariant.
const INLINE_CAP: u64 = 60;
if self.has_inline_data() && len <= INLINE_CAP {
let mut payload = [0u8; INLINE_CAP as usize];
reader.read_exact(&mut payload[..len as usize])?;
let ino = self.alloc_inode()?;
let mut inode = Inode::regular(
len as u32,
meta.mode & 0o7777,
meta.uid,
meta.gid,
meta.mtime,
);
inode.flags |= constants::EXT4_INLINE_DATA_FL;
inode.blocks_512 = 0;
// Pack the data into i_block (60 bytes = 15 × 4-byte slots).
for (i, slot) in inode.block.iter_mut().enumerate() {
let off = i * 4;
*slot = u32::from_le_bytes(payload[off..off + 4].try_into().unwrap());
}
self.inodes.push((ino, inode));
self.add_entry_to_dir_block_for(dev, parent_ino, name, ino, constants::DENT_REG)?;
// Stamp the marker xattr. Value is empty for files that
// fit entirely in i_block; for > 60 bytes (deferred — see
// the cap above) it would hold bytes 60..end.
let marker = xattr::Xattr::new("system.data", Vec::<u8>::new());
self.set_xattrs(dev, ino, &[marker])?;
return Ok(ino);
}
let n_data_blocks = len.div_ceil(bs as u64) as u32;
let ino = self.alloc_inode()?;
let mut inode = Inode::regular(
len as u32,
meta.mode & 0o7777,
meta.uid,
meta.gid,
meta.mtime,
);
// Stream one block at a time. Each block is read into a fixed
// buffer (the file is never fully resident in memory). In sparse
// mode an all-zero block becomes a hole: `data_blocks[i] == 0`
// means logical block i is unallocated and reads back as zero.
let mut buf = vec![0u8; bs as usize];
let mut data_blocks = Vec::with_capacity(n_data_blocks as usize);
let mut remaining = len;
let mut allocated_data = 0u32;
for _ in 0..n_data_blocks {
let to_read = remaining.min(bs as u64) as usize;
buf.fill(0);
reader.read_exact(&mut buf[..to_read])?;
if self.sparse && buf.iter().all(|&b| b == 0) {
data_blocks.push(0);
} else {
let blk = self.alloc_data_block()?;
dev.write_at(blk as u64 * bs as u64, &buf[..to_read])?;
data_blocks.push(blk);
allocated_data += 1;
}
remaining -= to_read as u64;
}
debug_assert_eq!(remaining, 0);
let allocated_meta_blocks = self.fill_block_pointers(&mut inode, &data_blocks)?;
inode.blocks_512 = (allocated_data + allocated_meta_blocks) * (bs / 512);
self.inodes.push((ino, inode));
self.add_entry_to_dir_block_for(dev, parent_ino, name, ino, constants::DENT_REG)?;
Ok(ino)
}
/// Create a subdirectory under `parent_ino`. Allocates one data block
/// holding "." / "..", patches the parent's link count.
pub fn add_dir_to(
&mut self,
dev: &mut dyn BlockDevice,
parent_ino: u32,
name: &[u8],
meta: FileMeta,
) -> Result<u32> {
let bs = self.layout.block_size;
let ino = self.alloc_inode()?;
let blk = self.alloc_data_block()?;
let mut inode = Inode::directory(bs, meta.mode & 0o7777, meta.uid, meta.gid, meta.mtime);
// For ext4, encode the single data block as an inline extent tree;
// for ext2/3, store the block number directly in i_block[0].
if matches!(self.kind, FsKind::Ext4) {
self.fill_block_pointers_extent(&mut inode, &[blk])?;
} else {
inode.block[0] = blk;
}
inode.blocks_512 = bs / 512;
let csum_tail = self.has_metadata_csum();
let with_filetype = self.has_filetype();
let block_bytes =
dir::make_initial_dir_block(ino, parent_ino, bs, with_filetype, csum_tail);
self.data_blocks.push((blk, block_bytes));
self.dir_blocks.push((blk, ino));
self.inodes.push((ino, inode));
self.groups[0].desc.used_dirs_count += 1;
self.add_entry_to_dir_block_for(dev, parent_ino, name, ino, constants::DENT_DIR)?;
self.patch_inode(dev, parent_ino, |i| i.links_count += 1)?;
Ok(ino)
}
/// Like [`Self::add_dir_to`] but pre-allocates `n_blocks` data blocks
/// for the new directory's body, wired into the inode in one shot.
/// Use this when the caller knows the destination directory's child
/// count up front (e.g. repack walking a source directory): a
/// contiguous run from the sequential allocator coalesces into a
/// single extent, side-stepping the per-grow extent-tree mutations
/// and keeping the dir at depth-0 even with many entries.
///
/// `n_blocks` must be at least 1. If the caller under-estimates,
/// the streaming `add_entry_to_dir_block_for` growth path takes over
/// naturally — this is a hint, not a hard limit.
pub fn add_dir_to_with_blocks(
&mut self,
dev: &mut dyn BlockDevice,
parent_ino: u32,
name: &[u8],
meta: FileMeta,
n_blocks: u32,
) -> Result<u32> {
let n_blocks = n_blocks.max(1);
let bs = self.layout.block_size;
let csum_tail = self.has_metadata_csum();
let with_filetype = self.has_filetype();
let ino = self.alloc_inode()?;
// Allocate the dir's blocks back-to-back. With the sequential
// bitmap allocator this is a contiguous run within a group, so
// `coalesce` produces a single extent.
let mut blocks = Vec::with_capacity(n_blocks as usize);
for _ in 0..n_blocks {
blocks.push(self.alloc_data_block()?);
}
let mut inode = Inode::directory(
bs * n_blocks,
meta.mode & 0o7777,
meta.uid,
meta.gid,
meta.mtime,
);
// ext4: extent tree (depth-0 for any contiguous run that fits in
// 4 leaves, depth-1 otherwise via the streaming-grow promote
// path — but with sequential alloc we should always stay
// depth-0). ext2/3: direct + indirect chain.
let allocated_meta = if matches!(self.kind, FsKind::Ext4) {
self.fill_block_pointers_extent(&mut inode, &blocks)?
} else {
self.fill_block_pointers_indirect(&mut inode, &blocks)?
};
inode.blocks_512 = (n_blocks + allocated_meta) * (bs / 512);
// First block: "." / ".."; all trailing blocks: empty placeholder
// so the linear-scan reader sees well-formed dir blocks.
let head = dir::make_initial_dir_block(ino, parent_ino, bs, with_filetype, csum_tail);
self.data_blocks.push((blocks[0], head));
self.dir_blocks.push((blocks[0], ino));
for &blk in &blocks[1..] {
self.data_blocks
.push((blk, dir::make_empty_dir_block(bs, csum_tail)));
self.dir_blocks.push((blk, ino));
}
self.inodes.push((ino, inode));
self.groups[0].desc.used_dirs_count += 1;
self.add_entry_to_dir_block_for(dev, parent_ino, name, ino, constants::DENT_DIR)?;
self.patch_inode(dev, parent_ino, |i| i.links_count += 1)?;
Ok(ino)
}
/// Like [`Self::add_dir_to_with_blocks`] but builds an HTree-indexed
/// directory: block 0 becomes a `dx_root` pointing at K leaf
/// blocks, the new inode carries `EXT4_INDEX_FL`, and later
/// `add_entry_to_dir_block_for` calls hash each name and route to
/// the matching leaf (preserving lookup-by-hash order).
///
/// `expected_names` is the full list of names the caller will add
/// under this directory — needed up front so we can hash each one
/// and partition them into leaves. Names that don't end up being
/// added still cost an unused tail-slack byte or two in their
/// leaf, but the writer doesn't care; conversely, names added that
/// weren't predicted still fit because every entry is hash-routed
/// to a leaf with available room.
///
/// Ext2/Ext3 don't support HTree; calling this on a non-ext4
/// instance returns `Unsupported`.
pub fn add_dir_indexed(
&mut self,
dev: &mut dyn BlockDevice,
parent_ino: u32,
name: &[u8],
meta: FileMeta,
expected_names: &[&[u8]],
) -> Result<u32> {
if !matches!(self.kind, FsKind::Ext4) {
return Err(crate::Error::Unsupported(
"ext: HTree (DIR_INDEX) requires ext4".into(),
));
}
let bs = self.layout.block_size;
let csum_tail = self.has_metadata_csum();
let with_filetype = self.has_filetype();
let usable = dir::usable_dir_len(bs, csum_tail);
// Hash every expected name, sort, then bucket by byte budget
// (87.5% target fill so post-creation appends have slack).
let mut hashes: Vec<(u32, usize)> = expected_names
.iter()
.enumerate()
.map(|(i, n)| (htree::half_md4_hash(n).0, i))
.collect();
hashes.sort_by_key(|(h, _)| *h);
let mut leaves: Vec<Vec<usize>> = vec![Vec::new()];
let mut current_bytes: usize = 0;
let cap = usable.saturating_sub(usable / 8);
for &(_, idx) in &hashes {
let need = dir::min_rec_len(expected_names[idx].len());
if current_bytes + need > cap && !leaves.last().unwrap().is_empty() {
leaves.push(Vec::new());
current_bytes = 0;
}
leaves.last_mut().unwrap().push(idx);
current_bytes += need;
}
let n_leaves = leaves.len();
// First hash of each leaf — the dx_entry boundary key for the
// routing layers. Leaf 0's boundary is 0 (implicit leftmost).
let leaf_first_hash: Vec<u32> = leaves
.iter()
.map(|leaf| {
let idx = leaf[0];
htree::half_md4_hash(expected_names[idx]).0
})
.collect();
let root_limit = htree::dx_root_limit(bs, csum_tail);
let node_limit = htree::dx_node_limit(bs, csum_tail);
// Decide tree shape:
// indirect_levels = 0 — dx_root entries point at leaves.
// Cap: root_limit leaves.
// indirect_levels = 1 — dx_root entries point at dx_nodes,
// dx_node entries point at leaves.
// Cap: root_limit * node_limit leaves.
let (indirect_levels, n_nodes) = if n_leaves <= root_limit {
(0u8, 0usize)
} else {
// Partition leaves across as few dx_nodes as possible,
// each holding up to `node_limit` leaves.
let need_nodes = n_leaves.div_ceil(node_limit);
if need_nodes > root_limit {
return Err(crate::Error::Unsupported(format!(
"ext: HTree dir {:?} needs {n_leaves} leaves, exceeds the depth-1 cap \
(root_limit={root_limit} * node_limit={node_limit} = {}); depth >= 2 \
not implemented",
String::from_utf8_lossy(name),
root_limit * node_limit
)));
}
(1u8, need_nodes)
};
let total_blocks = 1 + n_nodes + n_leaves; // dx_root + dx_nodes + leaves
let ino = self.alloc_inode()?;
let mut blocks = Vec::with_capacity(total_blocks);
for _ in 0..total_blocks {
blocks.push(self.alloc_data_block()?);
}
let mut inode = Inode::directory(
bs * total_blocks as u32,
meta.mode & 0o7777,
meta.uid,
meta.gid,
meta.mtime,
);
let allocated_meta = self.fill_block_pointers_extent(&mut inode, &blocks)?;
inode.blocks_512 = (total_blocks as u32 + allocated_meta) * (bs / 512);
inode.flags |= constants::EXT4_INDEX_FL;
// Logical-block layout (for the inode's view of the dir body):
// [0] dx_root
// [1 .. 1+n_nodes] dx_nodes (only when indirect_levels = 1)
// [1+n_nodes ..] leaves
let nodes_start_logical: u32 = 1;
let leaves_start_logical: u32 = (1 + n_nodes) as u32;
if indirect_levels == 0 {
// Single-level: dx_root entries map directly to leaves.
// Slot 0 is the countlimit (with leftmost leaf in its
// block field); slots 1..n carry (hash, leaf_logical_blk).
let mut entries: Vec<htree::DxEntry> = Vec::with_capacity(n_leaves);
entries.push(htree::DxEntry {
hash: htree::pack_countlimit(root_limit as u16, n_leaves as u16),
block: leaves_start_logical,
});
for (i, &h) in leaf_first_hash.iter().enumerate().skip(1) {
entries.push(htree::DxEntry {
hash: h,
block: leaves_start_logical + i as u32,
});
}
let dx_root_buf = htree::make_dx_root_block(
ino,
parent_ino,
bs,
htree::DX_HASH_HALF_MD4,
0,
&entries,
with_filetype,
csum_tail,
);
self.data_blocks.push((blocks[0], dx_root_buf));
self.dx_root_blocks.push((blocks[0], ino, n_leaves as u16));
} else {
// Two-level: dx_root entries map to dx_nodes; dx_node
// entries map to leaves. We chunk leaves into groups of
// `node_limit`, one group per dx_node.
let mut leaf_idx = 0usize;
let mut node_first_hashes: Vec<u32> = Vec::with_capacity(n_nodes);
for node_i in 0..n_nodes {
let chunk_start = leaf_idx;
let chunk_end = (chunk_start + node_limit).min(n_leaves);
let chunk_len = chunk_end - chunk_start;
node_first_hashes.push(leaf_first_hash[chunk_start]);
// dx_node entries: countlimit + (chunk_len - 1) real slots.
let mut node_entries: Vec<htree::DxEntry> = Vec::with_capacity(chunk_len);
node_entries.push(htree::DxEntry {
hash: htree::pack_countlimit(node_limit as u16, chunk_len as u16),
block: leaves_start_logical + chunk_start as u32,
});
for off in 1..chunk_len {
node_entries.push(htree::DxEntry {
hash: leaf_first_hash[chunk_start + off],
block: leaves_start_logical + (chunk_start + off) as u32,
});
}
let node_buf = htree::make_dx_node_block(bs, &node_entries, csum_tail);
let phys = blocks[(nodes_start_logical as usize) + node_i];
self.data_blocks.push((phys, node_buf));
self.dx_node_blocks.push((phys, ino, chunk_len as u16));
leaf_idx = chunk_end;
}
// dx_root: slot 0 is countlimit pointing at the first
// dx_node; slots 1..n point at subsequent dx_nodes.
let mut root_entries: Vec<htree::DxEntry> = Vec::with_capacity(n_nodes);
root_entries.push(htree::DxEntry {
hash: htree::pack_countlimit(root_limit as u16, n_nodes as u16),
block: nodes_start_logical,
});
for (i, &h) in node_first_hashes.iter().enumerate().skip(1) {
root_entries.push(htree::DxEntry {
hash: h,
block: nodes_start_logical + i as u32,
});
}
let dx_root_buf = htree::make_dx_root_block(
ino,
parent_ino,
bs,
htree::DX_HASH_HALF_MD4,
1,
&root_entries,
with_filetype,
csum_tail,
);
self.data_blocks.push((blocks[0], dx_root_buf));
self.dx_root_blocks.push((blocks[0], ino, n_nodes as u16));
}
// Leaves start empty; the router fills them as entries arrive.
for i in 0..n_leaves {
let blk = blocks[(leaves_start_logical as usize) + i];
self.data_blocks
.push((blk, dir::make_empty_dir_block(bs, csum_tail)));
self.dir_blocks.push((blk, ino));
}
self.inodes.push((ino, inode));
self.groups[0].desc.used_dirs_count += 1;
self.add_entry_to_dir_block_for(dev, parent_ino, name, ino, constants::DENT_DIR)?;
self.patch_inode(dev, parent_ino, |i| i.links_count += 1)?;
Ok(ino)
}
/// Resolve a name to the logical block index of its HTree leaf.
/// Walks dx_root → (dx_node)* → leaf, picking the rightmost
/// dx_entry whose hash is ≤ the target hash at each level (with
/// the countlimit slot serving as the implicit "leftmost"
/// catch-all for hashes that precede the first real boundary).
fn dx_route_logical_leaf(
&mut self,
dev: &mut dyn BlockDevice,
dir_inode: u32,
name: &[u8],
) -> Result<u32> {
let inode_copy = self
.inodes
.iter()
.find(|(i, _)| *i == dir_inode)
.map(|(_, i)| *i)
.unwrap();
// Read dx_root from logical block 0.
let dx_root_blk = self.file_block(dev, &inode_copy, 0)?;
self.ensure_block_staged(dev, dx_root_blk)?;
let root_buf = self
.data_blocks
.iter()
.find(|(b, _)| *b == dx_root_blk)
.map(|(_, bytes)| bytes.clone())
.unwrap();
// dx_root_info.indirect_levels lives at offset 30.
let indirect_levels = root_buf[30];
let (hash, _minor) = htree::half_md4_hash(name);
// Walk dx_root's dx_entry table to pick the child (leaf or
// dx_node, depending on indirect_levels).
let next_logical = dx_lookup_logical(&root_buf, htree::DX_ROOT_HEADER_LEN, hash);
if indirect_levels == 0 {
return Ok(next_logical);
}
if indirect_levels != 1 {
return Err(crate::Error::Unsupported(format!(
"ext4: HTree indirect_levels={indirect_levels} not supported (writer caps at 1)"
)));
}
// Depth-1: next_logical is the logical block of a dx_node.
// Read it and walk its dx_entry table to find the leaf.
let dx_node_phys = self.file_block(dev, &inode_copy, next_logical)?;
self.ensure_block_staged(dev, dx_node_phys)?;
let node_buf = self
.data_blocks
.iter()
.find(|(b, _)| *b == dx_node_phys)
.map(|(_, bytes)| bytes.clone())
.unwrap();
let leaf_logical = dx_lookup_logical(&node_buf, htree::DX_NODE_HEADER_LEN, hash);
Ok(leaf_logical)
}
/// Create a symbolic link. Targets ≤ 60 bytes are stored inline in
/// `i_block[0..15]` (the "fast symlink" optimization — no data block
/// allocated, blocks_512 stays at zero). Longer targets get a data block.
pub fn add_symlink_to(
&mut self,
dev: &mut dyn BlockDevice,
parent_ino: u32,
name: &[u8],
target: &[u8],
meta: FileMeta,
) -> Result<u32> {
if target.len() > 4095 {
return Err(crate::Error::Unsupported(
"ext: symlink target > 4095 bytes".into(),
));
}
let bs = self.layout.block_size;
let ino = self.alloc_inode()?;
let mut inode = Inode::symlink(
target.len() as u32,
meta.mode & 0o7777,
meta.uid,
meta.gid,
meta.mtime,
);
// Fast symlink: target fits in i_block (60 bytes = 15 × 4).
const FAST_MAX: usize = 60;
if target.len() <= FAST_MAX {
// Pack target bytes into i_block array.
let mut packed = [0u8; FAST_MAX];
packed[..target.len()].copy_from_slice(target);
for (i, slot) in inode.block.iter_mut().enumerate() {
let off = i * 4;
*slot = u32::from_le_bytes(packed[off..off + 4].try_into().unwrap());
}
// blocks_512 stays 0; no data block.
} else {
// Slow symlink: target gets a data block.
let blk = self.alloc_data_block()?;
inode.block[0] = blk;
inode.blocks_512 = bs / 512;
let mut buf = vec![0u8; bs as usize];
buf[..target.len()].copy_from_slice(target);
dev.write_at(blk as u64 * bs as u64, &buf)?;
}
self.inodes.push((ino, inode));
self.add_entry_to_dir_block_for(dev, parent_ino, name, ino, constants::DENT_LNK)?;
Ok(ino)
}
/// Create a device node, FIFO, or socket. No data blocks are allocated;
/// for char/block devices the major+minor are encoded into `i_block\[0\]`.
#[allow(clippy::too_many_arguments)]
pub fn add_device_to(
&mut self,
dev: &mut dyn BlockDevice,
parent_ino: u32,
name: &[u8],
kind: DeviceKind,
major: u32,
minor: u32,
meta: FileMeta,
) -> Result<u32> {
let ino = self.alloc_inode()?;
let special = match kind {
DeviceKind::Char => SpecialKind::Char,
DeviceKind::Block => SpecialKind::Block,
DeviceKind::Fifo => SpecialKind::Fifo,
DeviceKind::Socket => SpecialKind::Socket,
};
let inode = Inode::special(
special,
major,
minor,
meta.mode & 0o7777,
meta.uid,
meta.gid,
meta.mtime,
);
let ft = match kind {
DeviceKind::Char => constants::DENT_CHR,
DeviceKind::Block => constants::DENT_BLK,
DeviceKind::Fifo => constants::DENT_FIFO,
DeviceKind::Socket => constants::DENT_SOCK,
};
self.inodes.push((ino, inode));
self.add_entry_to_dir_block_for(dev, parent_ino, name, ino, ft)?;
Ok(ino)
}
/// Create a hard link to an existing inode: add `name` under
/// `parent_ino` as a dirent pointing at `target_ino`, and bump
/// `target_ino`'s `links_count`. No inode is allocated and no data
/// is copied.
///
/// Refuses to link a directory inode — POSIX disallows it and
/// e2fsck would flag the result. Refuses targets whose mode is
/// unset (already-freed or never-initialised inodes).
pub fn add_link_to(
&mut self,
dev: &mut dyn BlockDevice,
parent_ino: u32,
name: &[u8],
target_ino: u32,
) -> Result<()> {
self.ensure_inode_staged(dev, target_ino)?;
let target = self
.inodes
.iter()
.find(|(i, _)| *i == target_ino)
.map(|(_, i)| *i)
.unwrap();
let mode_type = target.mode & constants::S_IFMT;
if mode_type == 0 {
return Err(crate::Error::InvalidArgument(format!(
"ext: cannot hardlink to uninitialised inode {target_ino}"
)));
}
if mode_type == constants::S_IFDIR {
return Err(crate::Error::InvalidArgument(format!(
"ext: cannot hardlink to directory inode {target_ino} (POSIX disallows)"
)));
}
let file_type = match mode_type {
constants::S_IFREG => constants::DENT_REG,
constants::S_IFLNK => constants::DENT_LNK,
constants::S_IFCHR => constants::DENT_CHR,
constants::S_IFBLK => constants::DENT_BLK,
constants::S_IFIFO => constants::DENT_FIFO,
constants::S_IFSOCK => constants::DENT_SOCK,
_ => 0,
};
self.patch_inode(dev, target_ino, |i| {
i.links_count = i.links_count.saturating_add(1);
})?;
self.add_entry_to_dir_block_for(dev, parent_ino, name, target_ino, file_type)?;
Ok(())
}
/// Remove the file / empty directory / symlink / device node at the
/// absolute path `path`. Frees its inode and data blocks and unlinks it
/// from its parent directory. A non-empty directory is rejected.
pub fn remove_path(&mut self, dev: &mut dyn BlockDevice, path: &str) -> Result<()> {
let (parent, name) = split_path(std::path::Path::new(path))?;
let parent_str = parent
.to_str()
.ok_or_else(|| crate::Error::InvalidArgument("ext: non-UTF-8 path".into()))?;
let parent_ino = self.path_to_inode(dev, parent_str)?;
// Locate the target entry in the parent directory.
let entries = self.list_inode(dev, parent_ino)?;
let target_ino = entries
.iter()
.find(|e| e.name.as_bytes() == name.as_bytes())
.map(|e| e.inode)
.ok_or_else(|| crate::Error::InvalidArgument(format!("ext: no such entry {name:?}")))?;
let target = self.read_inode(dev, target_ino)?;
let is_dir = target.mode & constants::S_IFMT == constants::S_IFDIR;
if is_dir {
let children = self.list_inode(dev, target_ino)?;
let non_self = children
.iter()
.filter(|e| e.name != "." && e.name != "..")
.count();
if non_self != 0 {
return Err(crate::Error::InvalidArgument(format!(
"ext: directory {name:?} is not empty ({non_self} entries)"
)));
}
}
// Unlink the dirent from the parent first; this is the
// operation that's visible to other observers. Inode-side
// cleanup follows.
self.unlink_dir_entry(dev, parent_ino, name.as_bytes())?;
if is_dir {
// Removing a directory always frees its inode (POSIX dirs
// can't be hardlinked outside ./.. so links_count is
// always exactly 2 here). The parent's links_count drops
// by 1 because the gone dir's ".." was a link back.
self.free_inode_blocks(dev, &target)?;
self.free_inode(target_ino);
self.inodes.retain(|(i, _)| *i != target_ino);
self.inodes.push((target_ino, Inode::default()));
self.patch_inode(dev, parent_ino, |i| {
i.links_count = i.links_count.saturating_sub(1);
})?;
self.groups[0].desc.used_dirs_count =
self.groups[0].desc.used_dirs_count.saturating_sub(1);
return Ok(());
}
// Non-dir: hardlink-aware. Decrement links_count; only free
// the inode and its data blocks when the last link is gone.
if target.links_count > 1 {
self.patch_inode(dev, target_ino, |i| {
i.links_count = i.links_count.saturating_sub(1);
})?;
} else {
self.free_inode_blocks(dev, &target)?;
self.free_inode(target_ino);
self.inodes.retain(|(i, _)| *i != target_ino);
self.inodes.push((target_ino, Inode::default()));
}
Ok(())
}
/// Change the permission bits (low 12 bits of `i_mode`) of an
/// existing inode. Preserves the file-type bits (`S_IFMT`).
/// POSIX `chmod`.
pub fn chmod(&mut self, dev: &mut dyn BlockDevice, ino: u32, mode_perms: u16) -> Result<()> {
let new_perms = mode_perms & 0o7777;
self.patch_inode(dev, ino, |i| {
i.mode = (i.mode & constants::S_IFMT) | new_perms;
})
}
/// Change the ownership (uid/gid) of an existing inode. POSIX
/// `chown`. Values are truncated to 16 bits — the high halves
/// would live in `osd2.l_i_uid_high` / `osd2.l_i_gid_high` but
/// the v1 inode encoder doesn't surface them yet.
pub fn chown(&mut self, dev: &mut dyn BlockDevice, ino: u32, uid: u32, gid: u32) -> Result<()> {
self.patch_inode(dev, ino, |i| {
i.uid = (uid & 0xffff) as u16;
i.gid = (gid & 0xffff) as u16;
})
}
/// Stamp atime / mtime / ctime on an existing inode. POSIX
/// `utimensat`. Each argument is a UNIX timestamp in seconds;
/// passing `None` leaves that field unchanged. We don't yet
/// store the nanosecond extension (`i_atime_extra` etc.).
pub fn set_times(
&mut self,
dev: &mut dyn BlockDevice,
ino: u32,
atime: Option<u32>,
mtime: Option<u32>,
ctime: Option<u32>,
) -> Result<()> {
self.patch_inode(dev, ino, |i| {
if let Some(a) = atime {
i.atime = a;
}
if let Some(m) = mtime {
i.mtime = m;
}
if let Some(c) = ctime {
i.ctime = c;
}
})
}
/// Truncate a regular file to `new_size` bytes. Grow: leaves a
/// hole — no blocks are allocated until the file is actually
/// written. Shrink: frees any data block past the new end and
/// shrinks the inode's block list / extent tree to match.
/// Only operates on regular files; returns `InvalidArgument` for
/// dirs, symlinks, devices.
pub fn truncate(&mut self, dev: &mut dyn BlockDevice, ino: u32, new_size: u64) -> Result<()> {
if new_size > u32::MAX as u64 {
return Err(crate::Error::Unsupported(
"ext: file > 4 GiB requires LARGE_FILE handling (deferred)".into(),
));
}
let new_size = new_size as u32;
self.ensure_inode_staged(dev, ino)?;
let inode = self
.inodes
.iter()
.find(|(i, _)| *i == ino)
.map(|(_, i)| *i)
.unwrap();
let mode_type = inode.mode & constants::S_IFMT;
if mode_type != constants::S_IFREG {
return Err(crate::Error::InvalidArgument(format!(
"ext: truncate target inode {ino} is not a regular file (mode={:#o})",
inode.mode
)));
}
let bs = self.layout.block_size;
let old_blocks = (inode.size as u64).div_ceil(bs as u64) as u32;
let new_blocks = (new_size as u64).div_ceil(bs as u64) as u32;
// Shrink path: free everything past the new end.
if new_blocks < old_blocks {
for n in new_blocks..old_blocks {
let phys = self.file_block(dev, &inode, n)?;
if phys != 0 {
self.free_block(phys);
}
}
// The simplest reliable way to rebuild the block-pointer
// structure is to gather the surviving block list and
// re-pack it. For ext4 extent trees this stays inline
// (≤ 4 leaves typical for small files); for ext2/3 it
// re-establishes a fresh indirect chain.
let surviving: Vec<u32> = (0..new_blocks)
.map(|n| self.file_block(dev, &inode, n).unwrap_or(0))
.collect();
// Clear the old block pointers so fill_block_pointers
// starts from a known state. Preserve EXTENTS_FL — we'll
// re-stamp it inside fill_block_pointers_extent.
self.patch_inode(dev, ino, |i| {
i.block = [0u32; constants::N_BLOCKS];
i.flags &= !constants::EXT4_EXTENTS_FL;
})?;
let mut staged = self
.inodes
.iter()
.find(|(i, _)| *i == ino)
.map(|(_, i)| *i)
.unwrap();
let allocated_meta = if matches!(self.kind, FsKind::Ext4) {
self.fill_block_pointers_extent(&mut staged, &surviving)?
} else {
self.fill_block_pointers_indirect(&mut staged, &surviving)?
};
let sectors_per_block = bs / 512;
let real_blocks: u32 = surviving.iter().filter(|&&b| b != 0).count() as u32;
self.patch_inode(dev, ino, |i| {
i.block = staged.block;
i.flags = staged.flags;
i.size = new_size;
i.blocks_512 = (real_blocks + allocated_meta) * sectors_per_block;
})?;
} else {
// Grow path (or no-op): leave block list alone, just bump
// size. Subsequent writes will allocate as needed.
self.patch_inode(dev, ino, |i| {
i.size = new_size;
})?;
}
Ok(())
}
/// Rename a single entry: remove `old_name` from `old_parent_ino`
/// and re-add it under `new_name` in `new_parent_ino`, preserving
/// the target inode (so all hardlinks survive). Cross-directory
/// moves correctly update the parent's `links_count` when the
/// target is a directory (its `..` link transfers).
///
/// `new_name` must not already exist in `new_parent_ino`. Posix
/// `rename` overwrites; we leave that to the caller
/// (probe-then-remove-then-rename) until we're ready to make
/// atomic-overwrite work end to end.
pub fn rename(
&mut self,
dev: &mut dyn BlockDevice,
old_parent_ino: u32,
old_name: &[u8],
new_parent_ino: u32,
new_name: &[u8],
) -> Result<()> {
// Look up the source.
let entries = self.list_inode(dev, old_parent_ino)?;
let target = entries
.iter()
.find(|e| e.name.as_bytes() == old_name)
.ok_or_else(|| {
crate::Error::InvalidArgument(format!(
"ext: rename source {:?} not found in dir {old_parent_ino}",
String::from_utf8_lossy(old_name)
))
})?;
let target_ino = target.inode;
let target_inode = self.read_inode(dev, target_ino)?;
let is_dir = target_inode.mode & constants::S_IFMT == constants::S_IFDIR;
// Ensure new_name doesn't already exist in new_parent_ino.
let dest_entries = self.list_inode(dev, new_parent_ino)?;
if dest_entries.iter().any(|e| e.name.as_bytes() == new_name) {
return Err(crate::Error::InvalidArgument(format!(
"ext: rename target {:?} already exists in dir {new_parent_ino}",
String::from_utf8_lossy(new_name)
)));
}
let file_type = match target_inode.mode & constants::S_IFMT {
constants::S_IFREG => constants::DENT_REG,
constants::S_IFDIR => constants::DENT_DIR,
constants::S_IFLNK => constants::DENT_LNK,
constants::S_IFCHR => constants::DENT_CHR,
constants::S_IFBLK => constants::DENT_BLK,
constants::S_IFIFO => constants::DENT_FIFO,
constants::S_IFSOCK => constants::DENT_SOCK,
_ => 0,
};
// Add the new dirent first so a partial-success crash leaves
// the file findable under SOME name (matches kernel rename
// semantics — better to have a duplicate than to lose the
// file). Then drop the old dirent.
self.add_entry_to_dir_block_for(dev, new_parent_ino, new_name, target_ino, file_type)?;
self.unlink_dir_entry(dev, old_parent_ino, old_name)?;
// Cross-directory move of a directory: the target's `..` now
// points at a different parent. Update old/new parents'
// links_count and rewrite the moved dir's `..` dirent.
if is_dir && old_parent_ino != new_parent_ino {
self.patch_inode(dev, old_parent_ino, |i| {
i.links_count = i.links_count.saturating_sub(1);
})?;
self.patch_inode(dev, new_parent_ino, |i| {
i.links_count = i.links_count.saturating_add(1);
})?;
self.repoint_dotdot(dev, target_ino, new_parent_ino)?;
}
Ok(())
}
/// Rewrite the `..` dirent of `dir_ino` to point at `new_parent`.
/// Called by `rename` on a cross-directory move of a directory.
fn repoint_dotdot(
&mut self,
dev: &mut dyn BlockDevice,
dir_ino: u32,
new_parent: u32,
) -> Result<()> {
self.ensure_inode_staged(dev, dir_ino)?;
let inode_copy = self
.inodes
.iter()
.find(|(i, _)| *i == dir_ino)
.map(|(_, i)| *i)
.unwrap();
let blk = self.file_block(dev, &inode_copy, 0)?;
if blk == 0 {
return Err(crate::Error::InvalidImage(format!(
"ext: dir inode {dir_ino} has no first data block"
)));
}
self.ensure_block_staged(dev, blk)?;
if !self.dir_blocks.iter().any(|(b, _)| *b == blk) {
self.dir_blocks.push((blk, dir_ino));
}
let block = self
.data_blocks
.iter_mut()
.find(|(b, _)| *b == blk)
.map(|(_, bytes)| bytes)
.unwrap();
// "." at offset 0 (rec_len 12). ".." at offset 12: inode in
// the first 4 bytes.
block[12..16].copy_from_slice(&new_parent.to_le_bytes());
Ok(())
}
/// Free every data block (and classic indirection metadata block) an
/// inode references. No-op for inodes with no allocated blocks (fast
/// symlinks, device nodes).
fn free_inode_blocks(&mut self, dev: &mut dyn BlockDevice, inode: &Inode) -> Result<()> {
if inode.blocks_512 == 0 {
return Ok(());
}
let bs = self.layout.block_size;
let n_blocks = (inode.size as u64).div_ceil(bs as u64) as u32;
for n in 0..n_blocks {
let phys = self.file_block(dev, inode, n)?;
if phys != 0 {
self.free_block(phys);
}
}
// Classic indirection metadata blocks (extent inodes keep their tree
// inline in i_block, so they have no external metadata blocks).
if inode.flags & constants::EXT4_EXTENTS_FL == 0 {
let ind = inode.block[constants::IDX_INDIRECT];
if ind != 0 {
self.free_block(ind);
}
let dind = inode.block[constants::IDX_DOUBLE_INDIRECT];
if dind != 0 {
let mut buf = vec![0u8; bs as usize];
self.read_block(dev, dind, &mut buf)?;
for i in 0..(bs as usize / 4) {
let sub = u32::from_le_bytes(buf[i * 4..i * 4 + 4].try_into().unwrap());
if sub != 0 {
self.free_block(sub);
}
}
self.free_block(dind);
}
}
Ok(())
}
/// Clear the block-bitmap bit for an absolute block number.
pub(crate) fn free_block(&mut self, blk: u32) {
for (gi, g) in self.layout.groups.iter().enumerate() {
if blk >= g.start_block && blk <= g.end_block {
group::clear_bit(&mut self.groups[gi].block_bitmap, blk - g.start_block);
return;
}
}
}
/// Clear the inode-bitmap bit for an inode number.
fn free_inode(&mut self, ino: u32) {
let (g, idx) = self.inode_location(ino);
group::clear_bit(&mut self.groups[g as usize].inode_bitmap, idx);
}
/// Remove the named entry from a directory's first data block by
/// merging its `rec_len` into the preceding entry.
fn unlink_dir_entry(
&mut self,
dev: &mut dyn BlockDevice,
dir_inode: u32,
name: &[u8],
) -> Result<()> {
self.ensure_inode_staged(dev, dir_inode)?;
let inode_copy = self
.inodes
.iter()
.find(|(i, _)| *i == dir_inode)
.map(|(_, i)| *i)
.unwrap();
let dir_block_num = self.file_block(dev, &inode_copy, 0)?;
self.ensure_block_staged(dev, dir_block_num)?;
if !self.dir_blocks.iter().any(|(b, _)| *b == dir_block_num) {
self.dir_blocks.push((dir_block_num, dir_inode));
}
let with_filetype = self.has_filetype();
let usable = dir::usable_dir_len(self.layout.block_size, self.has_metadata_csum());
let block = self
.data_blocks
.iter_mut()
.find(|(b, _)| *b == dir_block_num)
.map(|(_, bytes)| bytes)
.unwrap();
let mut off = 0usize;
let mut prev_off: Option<usize> = None;
loop {
let entry = dir::decode_entry(&block[off..], with_filetype).ok_or_else(|| {
crate::Error::InvalidImage("corrupt dir entry while unlinking".into())
})?;
let rec_len = entry.rec_len;
if entry.inode != 0 && entry.name == name {
match prev_off {
Some(p) => {
// Absorb this entry's rec_len into the previous one.
let prev = dir::decode_entry(&block[p..], with_filetype)
.expect("prev entry decodes");
let merged = (prev.rec_len + rec_len) as u16;
block[p + 4..p + 6].copy_from_slice(&merged.to_le_bytes());
}
None => {
// First entry (normally "."): just void the inode.
block[off..off + 4].fill(0);
}
}
return Ok(());
}
let next = off + rec_len;
if next >= usable {
break;
}
prev_off = Some(off);
off = next;
}
Err(crate::Error::InvalidArgument(format!(
"ext: entry {name:?} not found in directory"
)))
}
/// Persist all staged metadata (bitmaps, inode table, dir blocks,
/// superblock) to the device. The primary superblock is written last.
pub fn flush(&mut self, dev: &mut dyn BlockDevice) -> Result<()> {
self.recompute_free_counts();
self.flush_metadata(dev)
}
/// Recursively copy a host directory into `parent_ino`. Each file's
/// contents are streamed via `FileSource::HostPath` (never fully loaded
/// in memory). Mode bits are taken from host metadata; uid, gid, and
/// timestamps are squashed to 0 to keep the output reproducible.
/// Override per-entry by populating the tree yourself.
pub fn populate_from_host_dir(
&mut self,
dev: &mut dyn BlockDevice,
parent_ino: u32,
src: &std::path::Path,
) -> Result<()> {
for entry in std::fs::read_dir(src)? {
let entry = entry?;
let meta = entry.metadata()?;
let ft = meta.file_type();
let name = entry.file_name();
let name_bytes = name.as_encoded_bytes();
#[cfg(unix)]
let mode = {
use std::os::unix::fs::PermissionsExt;
(meta.permissions().mode() & 0o7777) as u16
};
#[cfg(not(unix))]
let mode: u16 = if ft.is_dir() { 0o755 } else { 0o644 };
let fmeta = FileMeta {
mode,
uid: 0,
gid: 0,
mtime: 0,
atime: 0,
ctime: 0,
};
if ft.is_dir() {
let child = self.add_dir_to(dev, parent_ino, name_bytes, fmeta)?;
self.populate_from_host_dir(dev, child, &entry.path())?;
} else if ft.is_file() {
let src_path = entry.path();
self.add_file_to(
dev,
parent_ino,
name_bytes,
FileSource::HostPath(src_path),
fmeta,
)?;
} else if ft.is_symlink() {
let target = std::fs::read_link(entry.path())?;
let target_str = target.to_string_lossy();
self.add_symlink_to(dev, parent_ino, name_bytes, target_str.as_bytes(), fmeta)?;
} else {
#[cfg(unix)]
{
use std::os::unix::fs::{FileTypeExt, MetadataExt};
if ft.is_block_device() || ft.is_char_device() {
let rdev = meta.rdev();
// Linux dev_t: major in bits 8..19 and 32..47, minor in 0..7 and 20..31.
let major = ((rdev >> 8) & 0xfff) | ((rdev >> 32) & !0xfff);
let minor = (rdev & 0xff) | ((rdev >> 12) & !0xff);
let kind = if ft.is_char_device() {
DeviceKind::Char
} else {
DeviceKind::Block
};
self.add_device_to(
dev,
parent_ino,
name_bytes,
kind,
major as u32,
minor as u32,
fmeta,
)?;
} else if ft.is_fifo() {
self.add_device_to(
dev,
parent_ino,
name_bytes,
DeviceKind::Fifo,
0,
0,
fmeta,
)?;
} else if ft.is_socket() {
self.add_device_to(
dev,
parent_ino,
name_bytes,
DeviceKind::Socket,
0,
0,
fmeta,
)?;
}
}
}
}
Ok(())
}
/// One-shot: scan a host directory, compute the needed FS geometry via
/// [`BuildPlan`], format the device, populate it, and flush. The closest
/// analogue to `genext2fs -d <dir> img.ext2` — except sizing is exact.
pub fn build_from_host_dir(
dev: &mut dyn BlockDevice,
src: &std::path::Path,
kind: FsKind,
block_size: u32,
) -> Result<Self> {
let mut plan = BuildPlan::new(block_size, kind);
plan.scan_host_path(src)?;
let opts = plan.to_format_opts();
let mut ext = Self::format_with(dev, &opts)?;
ext.populate_from_host_dir(dev, INO_ROOT_DIR, src)?;
ext.flush(dev)?;
Ok(ext)
}
/// Create `/dev` with the standard set of device nodes for `kind` —
/// the building block for `--rootdevs minimal | standard`. The `/dev`
/// directory is owned by `root:root` mode 0755; each node's permissions
/// follow the conventional Linux defaults from the device-numbers
/// registry (e.g. `console` is 0600, `null` is 0666).
///
/// Pass [`RootDevs::None`] to do nothing (returns `Ok(None)`).
/// Returns the inode number of `/dev` on success.
pub fn populate_rootdevs(
&mut self,
dev: &mut dyn BlockDevice,
kind: RootDevs,
owner_uid: u32,
owner_gid: u32,
mtime: u32,
) -> Result<Option<u32>> {
if kind == RootDevs::None {
return Ok(None);
}
let entries = device_table(kind);
if entries.is_empty() {
return Ok(None);
}
let dir_meta = FileMeta {
mode: 0o755,
uid: owner_uid,
gid: owner_gid,
mtime,
atime: mtime,
ctime: mtime,
};
let dev_ino = self.add_dir_to(dev, INO_ROOT_DIR, b"dev", dir_meta)?;
for e in entries {
let meta = FileMeta {
mode: e.mode,
uid: owner_uid,
gid: owner_gid,
mtime,
atime: mtime,
ctime: mtime,
};
self.add_device_to(
dev,
dev_ino,
e.name.as_bytes(),
e.kind,
e.major,
e.minor,
meta,
)?;
}
Ok(Some(dev_ino))
}
// ──────────────────────────────── reader API ─────────────────────────
//
// These methods do NOT touch the staged write state; they read directly
// from the device every time.
/// Open an existing ext filesystem from `dev`. Parses the primary
/// superblock, every group descriptor, and both bitmaps per group.
/// Inode-table and data-block contents are read lazily.
pub fn open(dev: &mut dyn BlockDevice) -> Result<Self> {
let mut sb_buf = [0u8; constants::SUPERBLOCK_SIZE];
dev.read_at(constants::SUPERBLOCK_OFFSET, &mut sb_buf)?;
let sb = Superblock::decode(&sb_buf)?;
// When metadata_csum is set, the superblock carries a CRC32C in its
// last 4 bytes. A mismatch means the image is corrupt — refuse it
// rather than silently working from bad metadata.
if sb.feature_ro_compat & constants::feature::RO_COMPAT_METADATA_CSUM != 0 {
let stored = u32::from_le_bytes(sb_buf[1020..1024].try_into().unwrap());
let computed = csum::superblock(&sb_buf);
if stored != computed {
return Err(crate::Error::InvalidImage(format!(
"ext: superblock checksum mismatch (stored {stored:#010x}, computed {computed:#010x})"
)));
}
}
let mut layout = layout::from_superblock(&sb)?;
// GDT location: same logic as the writer.
let bs = layout.block_size as u64;
let gdt_off = if layout.first_data_block == 1 {
2 * bs
} else {
bs
};
let mut gdt = vec![0u8; layout.gdt_blocks as usize * bs as usize];
dev.read_at(gdt_off, &mut gdt)?;
let desc_size = layout.desc_size;
let mut groups = Vec::with_capacity(layout.groups.len());
for i in 0..layout.groups.len() {
let off = i * desc_size;
let desc = GroupDesc::decode(&gdt[off..off + constants::GROUP_DESC_SIZE]);
// The metadata positions in `layout.groups[i]` were *computed*
// assuming the classic contiguous layout. With flex_bg (and in
// general for any third-party writer) the descriptor is the
// authoritative source — overwrite the computed positions with
// the on-disk pointers so inode/bitmap reads land correctly.
layout.groups[i].block_bitmap = desc.block_bitmap;
layout.groups[i].inode_bitmap = desc.inode_bitmap;
layout.groups[i].inode_table = desc.inode_table;
let mut block_bitmap = vec![0u8; bs as usize];
dev.read_at(desc.block_bitmap as u64 * bs, &mut block_bitmap)?;
let mut inode_bitmap = vec![0u8; bs as usize];
dev.read_at(desc.inode_bitmap as u64 * bs, &mut inode_bitmap)?;
groups.push(GroupState {
block_bitmap,
inode_bitmap,
desc,
});
}
// next_inode: first clear bit in group 0's inode bitmap past the
// reserved range. (Subsequent groups can be tackled later.)
let mut next_inode = sb.first_ino;
while next_inode <= layout.inodes_per_group
&& test_bit(&groups[0].inode_bitmap, next_inode - 1)
{
next_inode += 1;
}
// Infer kind from feature flags on the parsed superblock so reads
// post-open know whether to expect extent trees or indirect blocks.
let kind = if sb.feature_incompat & constants::feature::INCOMPAT_EXTENTS != 0 {
FsKind::Ext4
} else if sb.feature_compat & constants::feature::COMPAT_HAS_JOURNAL != 0 {
FsKind::Ext3
} else {
FsKind::Ext2
};
Ok(Self {
sb,
layout,
kind,
// Default sparse off for an opened image; the caller can flip it
// via `set_sparse` before adding files.
sparse: false,
groups,
next_inode,
inodes: Vec::new(),
data_blocks: Vec::new(),
dir_blocks: Vec::new(),
extent_leaf_blocks: Vec::new(),
dx_root_blocks: Vec::new(),
dx_node_blocks: Vec::new(),
// Opened (vs. just-formatted) images go through the journal
// path on flush. `open()` itself runs JBD2 replay before
// returning, so by the time we land here the on-disk journal
// is clean.
bootstrap: false,
})
}
/// Enable or disable sparse-file writing for subsequent `add_file_to`
/// calls. Useful after [`Ext::open`], which defaults it off.
pub fn set_sparse(&mut self, sparse: bool) {
self.sparse = sparse;
}
/// Re-read every group's bitmaps and group descriptor from disk into
/// the in-memory `groups` vector. Called by the journal-replay path
/// after applying a transaction so subsequent staged metadata
/// writes don't shadow the just-replayed values.
pub(crate) fn reload_groups_from_disk(&mut self, dev: &mut dyn BlockDevice) -> Result<()> {
let bs = self.layout.block_size as u64;
let gdt_off = if self.layout.first_data_block == 1 {
2 * bs
} else {
bs
};
let mut gdt = vec![0u8; self.layout.gdt_blocks as usize * bs as usize];
dev.read_at(gdt_off, &mut gdt)?;
let desc_size = self.layout.desc_size;
for i in 0..self.layout.groups.len() {
let off = i * desc_size;
let desc = GroupDesc::decode(&gdt[off..off + constants::GROUP_DESC_SIZE]);
self.layout.groups[i].block_bitmap = desc.block_bitmap;
self.layout.groups[i].inode_bitmap = desc.inode_bitmap;
self.layout.groups[i].inode_table = desc.inode_table;
dev.read_at(
desc.block_bitmap as u64 * bs,
&mut self.groups[i].block_bitmap,
)?;
dev.read_at(
desc.inode_bitmap as u64 * bs,
&mut self.groups[i].inode_bitmap,
)?;
self.groups[i].desc = desc;
}
Ok(())
}
/// Read inode number `ino`. Consults the in-memory staged-write cache
/// first so a caller can interleave `add_*` and read calls without an
/// explicit flush; falls back to the on-disk inode table.
pub fn read_inode(&self, dev: &mut dyn BlockDevice, ino: u32) -> Result<Inode> {
if ino == 0 || ino > self.layout.inodes_count {
return Err(crate::Error::InvalidArgument(format!(
"ext: inode {ino} out of range"
)));
}
for (i, staged) in &self.inodes {
if *i == ino {
return Ok(*staged);
}
}
let (group, idx) = self.inode_location(ino);
let table_block = self.layout.groups[group as usize].inode_table;
let bs = self.layout.block_size as u64;
let off = table_block as u64 * bs + idx as u64 * self.layout.inode_size as u64;
let mut buf = [0u8; inode::INODE_BASE_SIZE];
dev.read_at(off, &mut buf)?;
Ok(Inode::decode(&buf))
}
/// Read a single block's contents into `out`. Consults staged data
/// blocks first (dir blocks built up during writes) and falls back to
/// the device.
pub(crate) fn read_block(
&self,
dev: &mut dyn BlockDevice,
blk: u32,
out: &mut [u8],
) -> Result<()> {
for (b, bytes) in &self.data_blocks {
if *b == blk {
out.copy_from_slice(bytes);
return Ok(());
}
}
let bs = self.layout.block_size as u64;
dev.read_at(blk as u64 * bs, out)?;
Ok(())
}
/// Return the absolute block number for the `n`-th block (0-indexed) of
/// the file at inode `ino`. Picks the representation based on the
/// inode flags: `EXT4_EXTENTS_FL` → walk the extent tree;
/// otherwise → direct + single-indirect (double/triple deferred).
pub fn file_block(&self, dev: &mut dyn BlockDevice, ino: &Inode, n: u32) -> Result<u32> {
if ino.flags & constants::EXT4_EXTENTS_FL != 0 {
return self.file_block_extent(dev, ino, n);
}
if (n as usize) < constants::N_DIRECT {
return Ok(ino.block[n as usize]);
}
let ptrs_per_block = self.layout.block_size / 4;
let n_off = n - constants::N_DIRECT as u32;
if n_off < ptrs_per_block {
let ind = ino.block[constants::IDX_INDIRECT];
if ind == 0 {
return Err(crate::Error::InvalidImage(
"ext: indirect block index unset".into(),
));
}
let mut buf = vec![0u8; self.layout.block_size as usize];
self.read_block(dev, ind, &mut buf)?;
let off = (n_off as usize) * 4;
return Ok(u32::from_le_bytes(buf[off..off + 4].try_into().unwrap()));
}
Err(crate::Error::Unsupported(
"ext: double/triple indirection not yet supported in reader".into(),
))
}
/// Resolve logical block `n` against an inode that uses an ext4
/// extent tree. Supports depth-0 (inline up to 4 leaves) and depth-1
/// (up to 4 idx entries in `i_block`, each pointing at one leaf
/// block on disk holding the actual extent records).
#[allow(clippy::needless_pass_by_ref_mut)]
fn file_block_extent(&self, dev: &mut dyn BlockDevice, ino: &Inode, n: u32) -> Result<u32> {
let iblock = extent::iblock_to_bytes(&ino.block);
let header = extent::decode_header(&iblock[..12])?;
if header.depth == 0 {
let (_, runs) = extent::decode_depth0_iblock(&iblock)?;
return Ok(resolve_logical_in_runs(&runs, n));
}
if header.depth == 1 {
let (_, indices) = extent::decode_idx_iblock(&iblock)?;
// The idx array is sorted by ei_block ascending; find the
// last idx whose block <= n.
let mut chosen: Option<extent::ExtentIdx> = None;
for idx in &indices {
if idx.block <= n {
chosen = Some(*idx);
} else {
break;
}
}
let Some(idx) = chosen else {
return Ok(0);
};
let bs = self.layout.block_size as usize;
let mut buf = vec![0u8; bs];
self.read_block(dev, idx.leaf as u32, &mut buf)?;
let (_, runs) = extent::decode_leaf_block(&buf)?;
return Ok(resolve_logical_in_runs(&runs, n));
}
Err(crate::Error::Unsupported(format!(
"ext4: extent tree depth {} not yet supported in reader (depth-0 and depth-1 only)",
header.depth
)))
}
/// List the entries of the directory inode `ino`. Returns
/// [`crate::Error::InvalidArgument`] if `ino` is not a directory.
pub fn list_inode(
&self,
dev: &mut dyn BlockDevice,
ino: u32,
) -> Result<Vec<crate::fs::DirEntry>> {
let inode = self.read_inode(dev, ino)?;
if inode.mode & constants::S_IFMT != constants::S_IFDIR {
return Err(crate::Error::InvalidArgument(format!(
"ext: inode {ino} is not a directory"
)));
}
let bs = self.layout.block_size;
let n_blocks = inode.size.div_ceil(bs);
let mut out = Vec::new();
let with_filetype = self.sb.feature_incompat & constants::feature::INCOMPAT_FILETYPE != 0;
let mut block_buf = vec![0u8; bs as usize];
for n in 0..n_blocks {
let blk = self.file_block(dev, &inode, n)?;
if blk == 0 {
continue;
}
self.read_block(dev, blk, &mut block_buf)?;
let mut off = 0usize;
while off < block_buf.len() {
let Some(entry) = dir::decode_entry(&block_buf[off..], with_filetype) else {
break;
};
if entry.inode != 0 && !entry.name.is_empty() {
let child = self.read_inode(dev, entry.inode)?;
let kind = kind_from_mode(child.mode);
let size = if matches!(kind, crate::fs::EntryKind::Regular) {
u64::from(child.size)
} else {
0
};
out.push(crate::fs::DirEntry {
name: String::from_utf8_lossy(entry.name).into_owned(),
inode: entry.inode,
kind,
size,
});
}
off += entry.rec_len;
if entry.rec_len == 0 {
break;
}
}
}
Ok(out)
}
/// Resolve an absolute path (must start with '/') to its inode number.
/// Each component is matched exactly; symlinks are NOT followed in v1.
pub fn path_to_inode(&self, dev: &mut dyn BlockDevice, path: &str) -> Result<u32> {
if !path.starts_with('/') {
return Err(crate::Error::InvalidArgument(format!(
"ext: path must be absolute, got {path:?}"
)));
}
let mut cur = constants::INO_ROOT_DIR;
for comp in path.split('/').filter(|c| !c.is_empty()) {
let entries = self.list_inode(dev, cur)?;
let next = entries
.iter()
.find(|e| e.name == comp)
.map(|e| e.inode)
.ok_or_else(|| {
crate::Error::InvalidArgument(format!("ext: no such entry {comp:?} in path"))
})?;
cur = next;
}
Ok(cur)
}
/// Open a streaming reader over the regular file at `ino`. The reader
/// holds a mutable borrow of `dev` for its lifetime; reads pull the
/// file's data blocks lazily through a per-block fetch.
/// Read this inode's extended attributes. Combines two storage
/// locations: inline xattrs in the extended inode body (when
/// `inode_size > 128`, post-`i_extra_isize`) and external block
/// xattrs (pointed at by `inode.file_acl`). Inline entries come
/// first to match the kernel's ordering.
///
/// The per-block CRC32C isn't validated here.
pub fn read_xattrs(&self, dev: &mut dyn BlockDevice, ino: u32) -> Result<Vec<xattr::Xattr>> {
let mut out = Vec::new();
// Inline xattrs only exist when the on-disk inode is bigger than
// the classic 128 bytes.
if self.layout.inode_size > inode::INODE_BASE_SIZE as u16 {
out.extend(self.read_inline_xattrs(dev, ino)?);
}
let inode = self.read_inode(dev, ino)?;
if inode.file_acl != 0 {
let bs = self.layout.block_size as usize;
let mut block = vec![0u8; bs];
dev.read_at(inode.file_acl as u64 * bs as u64, &mut block)?;
out.extend(xattr::decode_block(&block)?);
}
Ok(out)
}
/// Read inline xattrs from the extended-inode area. `read_inode`
/// only returns the 128-byte base struct, so this re-reads the full
/// on-disk inode (`layout.inode_size` bytes) and walks anything past
/// the standard fields + `i_extra_isize`.
fn read_inline_xattrs(&self, dev: &mut dyn BlockDevice, ino: u32) -> Result<Vec<xattr::Xattr>> {
let (group, idx) = self.inode_location(ino);
let table_block = self.layout.groups[group as usize].inode_table;
let bs = self.layout.block_size as u64;
let inode_size = self.layout.inode_size as usize;
let off = table_block as u64 * bs + idx as u64 * inode_size as u64;
let mut buf = vec![0u8; inode_size];
dev.read_at(off, &mut buf)?;
// i_extra_isize is the first u16 of the extended area at offset 128.
if buf.len() < 130 {
return Ok(Vec::new());
}
let extra_isize = u16::from_le_bytes(buf[128..130].try_into().unwrap()) as usize;
let inline_start = inode::INODE_BASE_SIZE + extra_isize;
if inline_start >= buf.len() {
return Ok(Vec::new());
}
xattr::decode_inline(&buf[inline_start..])
}
/// Attach the given extended attributes to a freshly-staged inode.
/// Allocates one data block, encodes the xattrs into it, stamps the
/// CRC32C if `metadata_csum` is on, points `inode.file_acl` at the
/// new block, and sets `COMPAT_EXT_ATTR` on the superblock.
///
/// `ino` MUST refer to an inode that was just added via one of the
/// `add_*_to` methods (i.e. it lives in `self.inodes`). Setting
/// xattrs on a disk-resident inode is a separate code path and is
/// not implemented in v1.
pub fn set_xattrs(
&mut self,
dev: &mut dyn BlockDevice,
ino: u32,
xattrs: &[xattr::Xattr],
) -> Result<()> {
if xattrs.is_empty() {
return Ok(());
}
let bs = self.layout.block_size;
let mut block = xattr::encode_block(xattrs, bs as usize)?;
let block_num = self.alloc_data_block()?;
if self.has_metadata_csum() {
xattr::stamp_checksum(&mut block, self.csum_seed(), block_num as u64);
}
dev.write_at(block_num as u64 * bs as u64, &block)?;
let entry = self
.inodes
.iter_mut()
.find(|(i, _)| *i == ino)
.ok_or_else(|| {
crate::Error::Unsupported(format!(
"ext: set_xattrs on disk-resident inode {ino} not yet supported"
))
})?;
entry.1.file_acl = block_num;
entry.1.blocks_512 += bs / 512;
self.sb.feature_compat |= constants::feature::COMPAT_EXT_ATTR;
Ok(())
}
/// Read the target of the symlink at inode `ino`. Errors if the inode
/// isn't a symlink.
///
/// ext stores short symlinks (≤ 60 bytes) inline in the inode's
/// `block` array; longer ones go through the normal block-pointer
/// machinery and are streamed via [`Self::open_file_reader`].
pub fn read_symlink_target(&self, dev: &mut dyn BlockDevice, ino: u32) -> Result<String> {
use std::io::Read as _;
let inode = self.read_inode(dev, ino)?;
if inode.mode & constants::S_IFMT != constants::S_IFLNK {
return Err(crate::Error::InvalidArgument(format!(
"ext: inode {ino} is not a symlink"
)));
}
let size = inode.size as usize;
// Fast (inline) symlink: target is in the 60 bytes of block[].
if size <= 60 && inode.blocks_512 == 0 {
let mut bytes = [0u8; 60];
for (i, &w) in inode.block.iter().enumerate() {
bytes[i * 4..i * 4 + 4].copy_from_slice(&w.to_le_bytes());
}
return Ok(String::from_utf8_lossy(&bytes[..size]).into_owned());
}
// Slow symlink: stored in data blocks, same as a regular file's body.
// Spoof the mode bits so open_file_reader accepts it.
let mut reg_inode = inode;
reg_inode.mode = (reg_inode.mode & !constants::S_IFMT) | constants::S_IFREG;
let reader = FileReader {
ext: self,
dev,
inode: reg_inode,
pos: 0,
block_buf: vec![0u8; self.layout.block_size as usize],
cached_block: u32::MAX,
};
let mut buf = Vec::with_capacity(size);
let mut r = reader;
r.read_to_end(&mut buf)?;
buf.truncate(size);
Ok(String::from_utf8_lossy(&buf).into_owned())
}
pub fn open_file_reader<'a>(
&'a self,
dev: &'a mut dyn BlockDevice,
ino: u32,
) -> Result<FileReader<'a>> {
let inode = self.read_inode(dev, ino)?;
if inode.mode & constants::S_IFMT != constants::S_IFREG {
return Err(crate::Error::InvalidArgument(format!(
"ext: inode {ino} is not a regular file"
)));
}
Ok(FileReader {
ext: self,
dev,
inode,
pos: 0,
block_buf: vec![0u8; self.layout.block_size as usize],
cached_block: u32::MAX,
})
}
}
/// Streaming reader over a regular file's data blocks. Constructed via
/// [`Ext::open_file_reader`]. Reads pull one FS block at a time from the
/// device into an internal buffer; no full-file allocation.
pub struct FileReader<'a> {
ext: &'a Ext,
dev: &'a mut dyn BlockDevice,
inode: Inode,
pos: u64,
block_buf: Vec<u8>,
/// Block number currently in `block_buf`, or `u32::MAX` if empty.
cached_block: u32,
}
impl<'a> Read for FileReader<'a> {
fn read(&mut self, out: &mut [u8]) -> std::io::Result<usize> {
let total = self.inode.size as u64;
if self.pos >= total {
return Ok(0);
}
// Inline-data fast path: the file's body lives inside i_block
// (the 60-byte block-pointer array). No data block to walk.
if self.inode.flags & constants::EXT4_INLINE_DATA_FL != 0 {
let inline_bytes = extent::iblock_to_bytes(&self.inode.block);
let remaining_in_file = (total - self.pos) as usize;
let n = out.len().min(remaining_in_file);
out[..n].copy_from_slice(&inline_bytes[self.pos as usize..self.pos as usize + n]);
self.pos += n as u64;
return Ok(n);
}
let bs = self.ext.layout.block_size as u64;
let block_idx = (self.pos / bs) as u32;
let block_off = (self.pos % bs) as usize;
if self.cached_block != block_idx {
let abs = self
.ext
.file_block(self.dev, &self.inode, block_idx)
.map_err(std::io::Error::other)?;
if abs == 0 {
self.block_buf.fill(0);
} else {
self.dev
.read_at(abs as u64 * bs, &mut self.block_buf)
.map_err(std::io::Error::other)?;
}
self.cached_block = block_idx;
}
let remaining_in_block = bs as usize - block_off;
let remaining_in_file = (total - self.pos) as usize;
let n = out.len().min(remaining_in_block).min(remaining_in_file);
out[..n].copy_from_slice(&self.block_buf[block_off..block_off + n]);
self.pos += n as u64;
Ok(n)
}
}
impl<'a> std::io::Seek for FileReader<'a> {
fn seek(&mut self, pos: std::io::SeekFrom) -> std::io::Result<u64> {
let total = self.inode.size as i128;
let new = match pos {
std::io::SeekFrom::Start(n) => n as i128,
std::io::SeekFrom::Current(d) => self.pos as i128 + d as i128,
std::io::SeekFrom::End(d) => total + d as i128,
};
if new < 0 {
return Err(std::io::Error::new(
std::io::ErrorKind::InvalidInput,
"ext: seek to negative offset",
));
}
self.pos = new as u64;
Ok(self.pos)
}
}
impl<'a> crate::fs::FileReadHandle for FileReader<'a> {
fn len(&self) -> u64 {
self.inode.size as u64
}
}
/// Build a JBD2 v2 journal superblock for a clean (never-mounted) journal.
/// Layout per linux/include/linux/jbd2.h; note that JBD2 fields are
/// **big-endian** on disk, unlike the rest of the ext filesystem.
fn build_jbd2_superblock(block_size: u32, journal_blocks: u32) -> Vec<u8> {
let mut buf = vec![0u8; block_size as usize];
// journal_header_s: h_magic, h_blocktype, h_sequence (each u32 BE)
buf[0..4].copy_from_slice(&0xC03B_3998u32.to_be_bytes()); // h_magic
buf[4..8].copy_from_slice(&4u32.to_be_bytes()); // h_blocktype = SB v2
// 8..12: h_sequence — zero
// journal_superblock_s body:
buf[12..16].copy_from_slice(&block_size.to_be_bytes()); // s_blocksize
buf[16..20].copy_from_slice(&journal_blocks.to_be_bytes()); // s_maxlen
buf[20..24].copy_from_slice(&1u32.to_be_bytes()); // s_first = 1
buf[24..28].copy_from_slice(&1u32.to_be_bytes()); // s_sequence
// 28..32: s_start = 0 → CLEAN journal, no recovery needed
// 32..36: s_errno = 0
// 36..48: feature_{compat,incompat,ro_compat} = 0
// 48..64: s_uuid = 0
buf[64..68].copy_from_slice(&1u32.to_be_bytes()); // s_nr_users = 1
// rest zero
buf
}
/// Split an absolute path into (parent path, last component). Errors for
/// paths that don't start with '/', that ARE just '/', or whose last
/// component contains a slash (defensive).
pub(crate) fn split_path(path: &std::path::Path) -> Result<(std::path::PathBuf, String)> {
let s = path
.to_str()
.ok_or_else(|| crate::Error::InvalidArgument(format!("ext: non-UTF-8 path {path:?}")))?;
if !s.starts_with('/') {
return Err(crate::Error::InvalidArgument(format!(
"ext: path must be absolute, got {s:?}"
)));
}
if s == "/" {
return Err(crate::Error::InvalidArgument(
"ext: cannot create or remove the root".into(),
));
}
let trimmed = s.trim_end_matches('/');
let (parent, name) = match trimmed.rsplit_once('/') {
Some((p, n)) => (if p.is_empty() { "/" } else { p }, n),
None => {
return Err(crate::Error::InvalidArgument(format!(
"ext: bad path {s:?}"
)));
}
};
Ok((std::path::PathBuf::from(parent), name.to_string()))
}
impl crate::fs::FilesystemFactory for Ext {
type FormatOpts = FormatOpts;
fn format(dev: &mut dyn BlockDevice, opts: &Self::FormatOpts) -> Result<Self> {
Self::format_with(dev, opts)
}
fn open(dev: &mut dyn BlockDevice) -> Result<Self> {
Self::open(dev)
}
}
impl crate::fs::Filesystem for Ext {
fn create_file(
&mut self,
dev: &mut dyn BlockDevice,
path: &std::path::Path,
src: FileSource,
meta: FileMeta,
) -> Result<()> {
let (parent, name) = split_path(path)?;
let parent_str = parent
.to_str()
.ok_or_else(|| crate::Error::InvalidArgument("ext: non-UTF-8 parent path".into()))?;
let parent_ino = self.path_to_inode(dev, parent_str)?;
self.add_file_to(dev, parent_ino, name.as_bytes(), src, meta)?;
Ok(())
}
fn create_dir(
&mut self,
dev: &mut dyn BlockDevice,
path: &std::path::Path,
meta: FileMeta,
) -> Result<()> {
let (parent, name) = split_path(path)?;
let parent_str = parent.to_str().unwrap();
let parent_ino = self.path_to_inode(dev, parent_str)?;
self.add_dir_to(dev, parent_ino, name.as_bytes(), meta)?;
Ok(())
}
fn create_symlink(
&mut self,
dev: &mut dyn BlockDevice,
path: &std::path::Path,
target: &std::path::Path,
meta: FileMeta,
) -> Result<()> {
let (parent, name) = split_path(path)?;
let parent_str = parent.to_str().unwrap();
let parent_ino = self.path_to_inode(dev, parent_str)?;
let target_bytes = target
.to_str()
.ok_or_else(|| crate::Error::InvalidArgument("ext: non-UTF-8 symlink target".into()))?
.as_bytes();
self.add_symlink_to(dev, parent_ino, name.as_bytes(), target_bytes, meta)?;
Ok(())
}
fn create_device(
&mut self,
dev: &mut dyn BlockDevice,
path: &std::path::Path,
kind: DeviceKind,
major: u32,
minor: u32,
meta: FileMeta,
) -> Result<()> {
let (parent, name) = split_path(path)?;
let parent_str = parent.to_str().unwrap();
let parent_ino = self.path_to_inode(dev, parent_str)?;
self.add_device_to(dev, parent_ino, name.as_bytes(), kind, major, minor, meta)?;
Ok(())
}
fn remove(&mut self, dev: &mut dyn BlockDevice, path: &std::path::Path) -> Result<()> {
let s = path
.to_str()
.ok_or_else(|| crate::Error::InvalidArgument("ext: non-UTF-8 path".into()))?;
self.remove_path(dev, s)
}
fn list(
&mut self,
dev: &mut dyn BlockDevice,
path: &std::path::Path,
) -> Result<Vec<crate::fs::DirEntry>> {
let s = path
.to_str()
.ok_or_else(|| crate::Error::InvalidArgument("ext: non-UTF-8 path".into()))?;
let ino = self.path_to_inode(dev, s)?;
self.list_inode(dev, ino)
}
fn read_file<'a>(
&'a mut self,
dev: &'a mut dyn BlockDevice,
path: &std::path::Path,
) -> Result<Box<dyn Read + 'a>> {
let s = path
.to_str()
.ok_or_else(|| crate::Error::InvalidArgument("ext: non-UTF-8 path".into()))?;
let ino = self.path_to_inode(dev, s)?;
let reader = self.open_file_reader(dev, ino)?;
Ok(Box::new(reader))
}
fn open_file_ro<'a>(
&'a mut self,
dev: &'a mut dyn BlockDevice,
path: &std::path::Path,
) -> Result<Box<dyn crate::fs::FileReadHandle + 'a>> {
let s = path
.to_str()
.ok_or_else(|| crate::Error::InvalidArgument("ext: non-UTF-8 path".into()))?;
let ino = self.path_to_inode(dev, s)?;
let reader = self.open_file_reader(dev, ino)?;
Ok(Box::new(reader))
}
fn open_file_rw<'a>(
&'a mut self,
dev: &'a mut dyn BlockDevice,
path: &std::path::Path,
flags: crate::fs::OpenFlags,
meta: Option<FileMeta>,
) -> Result<Box<dyn crate::fs::FileHandle + 'a>> {
rw::open_file_rw_ext(self, dev, path, flags, meta)
}
fn flush(&mut self, dev: &mut dyn BlockDevice) -> Result<()> {
Self::flush(self, dev)
}
fn read_symlink(
&mut self,
dev: &mut dyn BlockDevice,
path: &std::path::Path,
) -> Result<std::path::PathBuf> {
let s = path
.to_str()
.ok_or_else(|| crate::Error::InvalidArgument("ext: non-UTF-8 path".into()))?;
let ino = self.path_to_inode(dev, s)?;
let target = self.read_symlink_target(dev, ino)?;
Ok(std::path::PathBuf::from(target))
}
fn getattr(
&mut self,
dev: &mut dyn BlockDevice,
path: &std::path::Path,
) -> Result<crate::fs::FileAttrs> {
let s = path
.to_str()
.ok_or_else(|| crate::Error::InvalidArgument("ext: non-UTF-8 path".into()))?;
let ino = self.path_to_inode(dev, s)?;
let inode = self.read_inode(dev, ino)?;
let kind = kind_from_mode(inode.mode);
// Device numbers live in i_block[0] when the inode is a
// char/block device (encoded by `add_device_to`).
let rdev = if matches!(
kind,
crate::fs::EntryKind::Char | crate::fs::EntryKind::Block
) {
inode.block[0]
} else {
0
};
Ok(crate::fs::FileAttrs {
kind,
mode: inode.mode & 0o7777,
uid: inode.uid as u32,
gid: inode.gid as u32,
size: inode.size as u64,
blocks: inode.blocks_512 as u64,
nlink: inode.links_count as u32,
atime: inode.atime,
mtime: inode.mtime,
ctime: inode.ctime,
rdev,
inode: ino,
})
}
fn set_attrs(
&mut self,
dev: &mut dyn BlockDevice,
path: &std::path::Path,
attrs: crate::fs::SetAttrs,
) -> Result<()> {
let s = path
.to_str()
.ok_or_else(|| crate::Error::InvalidArgument("ext: non-UTF-8 path".into()))?;
let ino = self.path_to_inode(dev, s)?;
if let Some(m) = attrs.mode {
self.chmod(dev, ino, m)?;
}
if attrs.uid.is_some() || attrs.gid.is_some() {
let cur = self.read_inode(dev, ino)?;
let new_uid = attrs.uid.unwrap_or(cur.uid as u32);
let new_gid = attrs.gid.unwrap_or(cur.gid as u32);
self.chown(dev, ino, new_uid, new_gid)?;
}
if attrs.atime.is_some() || attrs.mtime.is_some() || attrs.ctime.is_some() {
self.set_times(dev, ino, attrs.atime, attrs.mtime, attrs.ctime)?;
}
Ok(())
}
fn truncate(
&mut self,
dev: &mut dyn BlockDevice,
path: &std::path::Path,
new_size: u64,
) -> Result<()> {
let s = path
.to_str()
.ok_or_else(|| crate::Error::InvalidArgument("ext: non-UTF-8 path".into()))?;
let ino = self.path_to_inode(dev, s)?;
Self::truncate(self, dev, ino, new_size)
}
fn rename(
&mut self,
dev: &mut dyn BlockDevice,
old_path: &std::path::Path,
new_path: &std::path::Path,
) -> Result<()> {
let (op, on) = split_path(old_path)?;
let (np, nn) = split_path(new_path)?;
let op_s = op
.to_str()
.ok_or_else(|| crate::Error::InvalidArgument("ext: non-UTF-8 old parent".into()))?;
let np_s = np
.to_str()
.ok_or_else(|| crate::Error::InvalidArgument("ext: non-UTF-8 new parent".into()))?;
let op_ino = self.path_to_inode(dev, op_s)?;
let np_ino = self.path_to_inode(dev, np_s)?;
Self::rename(self, dev, op_ino, on.as_bytes(), np_ino, nn.as_bytes())
}
fn hardlink(
&mut self,
dev: &mut dyn BlockDevice,
target_path: &std::path::Path,
new_path: &std::path::Path,
) -> Result<()> {
let target_s = target_path
.to_str()
.ok_or_else(|| crate::Error::InvalidArgument("ext: non-UTF-8 target path".into()))?;
let target_ino = self.path_to_inode(dev, target_s)?;
let (np, nn) = split_path(new_path)?;
let np_s = np
.to_str()
.ok_or_else(|| crate::Error::InvalidArgument("ext: non-UTF-8 new parent".into()))?;
let np_ino = self.path_to_inode(dev, np_s)?;
self.add_link_to(dev, np_ino, nn.as_bytes(), target_ino)
}
fn list_xattrs(
&mut self,
dev: &mut dyn BlockDevice,
path: &std::path::Path,
) -> Result<Vec<crate::fs::XattrPair>> {
let s = path
.to_str()
.ok_or_else(|| crate::Error::InvalidArgument("ext: non-UTF-8 path".into()))?;
let ino = self.path_to_inode(dev, s)?;
let xattrs = self.read_xattrs(dev, ino)?;
Ok(xattrs
.into_iter()
.map(|x| crate::fs::XattrPair {
name: x.name,
value: x.value,
})
.collect())
}
fn statfs(&mut self, _dev: &mut dyn BlockDevice) -> Result<crate::fs::StatFs> {
let sb = &self.sb;
Ok(crate::fs::StatFs {
block_size: self.layout.block_size,
blocks: sb.blocks_count as u64,
blocks_free: sb.free_blocks_count as u64,
blocks_avail: sb.free_blocks_count as u64,
inodes: sb.inodes_count as u64,
inodes_free: sb.free_inodes_count as u64,
name_max: 255,
})
}
}
/// Scan a leaf-extent list for the run containing logical block `n` and
/// return the corresponding physical block. Returns 0 if `n` falls in a
/// hole (no extent covers it).
fn resolve_logical_in_runs(runs: &[extent::ExtentRun], n: u32) -> u32 {
for r in runs {
let len = if r.len > extent::MAX_LEN_PER_EXTENT {
r.len - extent::MAX_LEN_PER_EXTENT
} else {
r.len
};
if n >= r.logical && n < r.logical + len as u32 {
let phys = r.physical + (n - r.logical) as u64;
return phys as u32;
}
}
0
}
/// Translate an ext mode word into a [`crate::fs::EntryKind`].
fn kind_from_mode(mode: u16) -> crate::fs::EntryKind {
use crate::fs::EntryKind;
match mode & constants::S_IFMT {
constants::S_IFREG => EntryKind::Regular,
constants::S_IFDIR => EntryKind::Dir,
constants::S_IFLNK => EntryKind::Symlink,
constants::S_IFCHR => EntryKind::Char,
constants::S_IFBLK => EntryKind::Block,
constants::S_IFIFO => EntryKind::Fifo,
constants::S_IFSOCK => EntryKind::Socket,
_ => EntryKind::Unknown,
}
}
/// Append a dir entry to a directory block by shrinking the existing last
/// entry to its natural minimum and writing the new entry into the freed
/// tail.
///
/// `usable` is the byte length available for real entries — the whole
/// block, or `block_size - 12` when `metadata_csum` reserves a checksum
/// tail. The last real entry's `rec_len` always runs up to `usable`.
///
/// Returns `Ok(true)` when the entry fits and is written, `Ok(false)`
/// when the block has insufficient trailing slack (caller should grow the
/// directory by one block and retry), and `Err` only on a corrupt block.
fn try_append_dir_entry(
block: &mut [u8],
name: &[u8],
inode: u32,
file_type: u8,
with_filetype: bool,
usable: usize,
) -> Result<bool> {
let needed = dir::min_rec_len(name.len());
// Fresh-block fast path: when the sole entry is the empty placeholder
// produced by `make_empty_dir_block` (inode=0, name_len=0, rec_len
// spanning the usable region), overwrite it entirely with the new
// entry rather than leaving an 8-byte zero stub at offset 0. e2fsck
// accepts blocks that are *entirely* empty (single placeholder) and
// blocks whose first entry is a real one, but flags "placeholder stub
// followed by real entries" as a corrupted block.
if let Some(first) = dir::decode_entry(block, with_filetype) {
if first.inode == 0 && first.name.is_empty() && first.rec_len >= usable && needed <= usable
{
// Wipe the usable region (the csum tail past `usable` is
// untouched), then encode the single new entry to span it.
for b in block[..usable].iter_mut() {
*b = 0;
}
let mut tail = Vec::with_capacity(usable);
dir::encode_entry(
&mut tail,
inode,
name,
usable as u16,
file_type,
with_filetype,
);
debug_assert_eq!(tail.len(), usable);
block[..usable].copy_from_slice(&tail);
return Ok(true);
}
}
let mut off = 0usize;
let last_off: usize;
loop {
let entry = dir::decode_entry(&block[off..], with_filetype).ok_or_else(|| {
crate::Error::InvalidImage("corrupt dir entry while appending".into())
})?;
let next = off + entry.rec_len;
if next >= usable {
last_off = off;
break;
}
off = next;
}
let last_entry = dir::decode_entry(&block[last_off..], with_filetype).expect("decode last");
let last_min = dir::min_rec_len(last_entry.name.len());
let last_real_end = last_off + last_entry.rec_len;
let new_entry_off = last_off + last_min;
let new_entry_space = last_real_end - new_entry_off;
if new_entry_space < needed {
return Ok(false);
}
// Shrink the last entry's rec_len.
block[last_off + 4..last_off + 6].copy_from_slice(&(last_min as u16).to_le_bytes());
// Encode the new entry into a buffer, then copy.
let mut tail = Vec::with_capacity(new_entry_space);
dir::encode_entry(
&mut tail,
inode,
name,
new_entry_space as u16,
file_type,
with_filetype,
);
debug_assert_eq!(tail.len(), new_entry_space);
block[new_entry_off..new_entry_off + new_entry_space].copy_from_slice(&tail);
Ok(true)
}
fn popcount_bits(bm: &[u8], start: u32, end: u32) -> u32 {
(start..end).filter(|&i| test_bit(bm, i)).count() as u32
}
/// Walk a dx_root or dx_node's dx_entry table to find the child block
/// whose hash range covers `target`. `header_len` is the byte offset
/// where the dx_entry table starts (32 for dx_root, 12 for dx_node).
/// Slot 0 is the countlimit (high half of its hash field is `count`,
/// low half is `limit`); slots 1..count carry real `(hash, block)`
/// rows sorted by ascending hash, and the rightmost slot whose hash
/// ≤ target wins. The countlimit slot's `block` field is the
/// catch-all for hashes preceding any real boundary.
fn dx_lookup_logical(buf: &[u8], header_len: usize, target: u32) -> u32 {
let cl_hash = u32::from_le_bytes(buf[header_len..header_len + 4].try_into().unwrap());
let count = (cl_hash >> 16) as usize;
let mut chosen_slot = 0usize;
for slot in 1..count {
let off = header_len + slot * 8;
let slot_hash = u32::from_le_bytes(buf[off..off + 4].try_into().unwrap());
if slot_hash <= target {
chosen_slot = slot;
} else {
break;
}
}
let block_off = header_len + chosen_slot * 8 + 4;
u32::from_le_bytes(buf[block_off..block_off + 4].try_into().unwrap())
}
#[cfg(test)]
mod tests {
use super::*;
use crate::block::MemoryBackend;
#[test]
fn format_creates_clean_filesystem() {
let mut dev = MemoryBackend::new(1024 * 1024);
let opts = FormatOpts::default();
let ext = Ext::format_with(&mut dev, &opts).expect("format");
assert_eq!(ext.sb.magic, constants::EXT2_MAGIC);
assert_eq!(ext.sb.blocks_count, 1024);
assert_eq!(ext.sb.inodes_count, 16);
assert_eq!(ext.sb.block_size(), 1024);
}
#[test]
fn flex_bg_off_by_default() {
// The default FormatOpts must not enable flex_bg, preserving the
// pre-flex_bg byte-exact ext2 layout.
let mut dev = MemoryBackend::new(1024 * 1024);
let opts = FormatOpts::default();
let ext = Ext::format_with(&mut dev, &opts).expect("format");
assert_eq!(ext.sb.log_groups_per_flex, 0);
assert_eq!(
ext.sb.feature_incompat & constants::feature::INCOMPAT_FLEX_BG,
0
);
assert_eq!(ext.layout.log_groups_per_flex, 0);
}
#[test]
fn flex_bg_sets_feature_and_log() {
// bs=4096, 64 MiB FS → 2 groups of 32768 blocks. log_groups_per_flex = 1.
let total_bytes = 64u64 * 1024 * 1024;
let mut dev = MemoryBackend::new(total_bytes);
let opts = FormatOpts {
kind: FsKind::Ext4,
block_size: 4096,
blocks_count: 16 * 1024,
inodes_count: 1024,
log_groups_per_flex: 1,
sparse_super: true,
..FormatOpts::default()
};
let ext = Ext::format_with(&mut dev, &opts).expect("format flex_bg");
assert_eq!(ext.sb.log_groups_per_flex, 1);
assert!(
ext.sb.feature_incompat & constants::feature::INCOMPAT_FLEX_BG != 0,
"INCOMPAT_FLEX_BG must be set when log_groups_per_flex > 0"
);
// Reopen: the parsed superblock must round-trip the flex value.
let reopened = Ext::open(&mut dev).expect("reopen flex_bg image");
assert_eq!(reopened.sb.log_groups_per_flex, 1);
assert_eq!(reopened.layout.log_groups_per_flex, 1);
}
#[test]
fn flex_bg_rejects_invalid_log() {
let mut dev = MemoryBackend::new(64u64 * 1024 * 1024);
let opts = FormatOpts {
kind: FsKind::Ext4,
block_size: 4096,
blocks_count: 16 * 1024,
inodes_count: 1024,
log_groups_per_flex: 6,
..FormatOpts::default()
};
let err = Ext::format_with(&mut dev, &opts).expect_err("must reject log > 5");
assert!(matches!(err, crate::Error::InvalidArgument(_)));
}
#[test]
fn flex_bg_default_helper_picks_reasonable_log() {
// Small (single-group) → 0 (off). Large → 4.
assert_eq!(FormatOpts::default_log_groups_per_flex(1), 0);
assert_eq!(FormatOpts::default_log_groups_per_flex(15), 0);
assert_eq!(FormatOpts::default_log_groups_per_flex(16), 4);
assert_eq!(FormatOpts::default_log_groups_per_flex(1024), 4);
}
#[test]
fn flex_bg_metadata_packed_in_first_group() {
// 4 groups of 32768 blocks (4 KiB blocks) with log_groups_per_flex=2
// packs every group's bitmap + inode-table into group 0. Reopen the
// image and assert that *every* non-leader group's bitmap_block and
// inode_table fall strictly inside the leader's metadata extent.
let mut dev = MemoryBackend::new(768u64 * 1024 * 1024);
let blocks_per_group = 8 * 4096u32;
let opts = FormatOpts {
kind: FsKind::Ext4,
block_size: 4096,
blocks_count: 4 * blocks_per_group,
inodes_count: 4096,
log_groups_per_flex: 2,
sparse_super: true,
..FormatOpts::default()
};
let ext = Ext::format_with(&mut dev, &opts).expect("format flex_bg");
assert_eq!(ext.layout.num_groups(), 4, "test setup must yield 4 groups");
let g0 = ext.layout.groups[0];
// Leader's metadata range: [start_block + sb+gdt, data_start).
let leader_meta_start = g0.start_block
+ if g0.has_superblock {
1 + ext.layout.gdt_blocks
} else {
0
};
let leader_meta_end = g0.data_start;
for gi in 1..ext.layout.num_groups() as usize {
let g = ext.layout.groups[gi];
assert!(
g.block_bitmap >= leader_meta_start && g.block_bitmap < leader_meta_end,
"group {gi} block_bitmap {} not inside leader metadata [{}, {})",
g.block_bitmap,
leader_meta_start,
leader_meta_end,
);
assert!(
g.inode_bitmap >= leader_meta_start && g.inode_bitmap < leader_meta_end,
"group {gi} inode_bitmap {} not inside leader metadata [{}, {})",
g.inode_bitmap,
leader_meta_start,
leader_meta_end,
);
assert!(
g.inode_table >= leader_meta_start
&& g.inode_table + ext.layout.inode_table_blocks <= leader_meta_end,
"group {gi} inode_table {} (+{} blocks) not inside leader metadata [{}, {})",
g.inode_table,
ext.layout.inode_table_blocks,
leader_meta_start,
leader_meta_end,
);
}
// Reopen and verify the same property survives an Ext::open
// (i.e. the on-disk group-descriptor pointers, not just the planner).
let reopened = Ext::open(&mut dev).expect("reopen flex_bg image");
assert!(
reopened.sb.feature_incompat & constants::feature::INCOMPAT_FLEX_BG != 0,
"INCOMPAT_FLEX_BG must round-trip through the superblock"
);
for gi in 1..reopened.layout.num_groups() as usize {
let g = reopened.layout.groups[gi];
assert!(
g.block_bitmap >= leader_meta_start && g.block_bitmap < leader_meta_end,
"reopened: group {gi} block_bitmap {} not in leader metadata",
g.block_bitmap,
);
assert!(
g.inode_table >= leader_meta_start
&& g.inode_table + reopened.layout.inode_table_blocks <= leader_meta_end,
"reopened: group {gi} inode_table {} not in leader metadata",
g.inode_table,
);
}
}
/// Format a small ext4 image with flex_bg enabled and run `e2fsck -fn`
/// on it. Skipped silently when e2fsck isn't installed on the host —
/// the in-memory checks above already pin the layout invariants.
#[test]
fn flex_bg_image_passes_e2fsck() {
use std::process::Command;
let e2fsck = match Command::new("sh")
.arg("-c")
.arg("command -v e2fsck")
.output()
{
Ok(o) if o.status.success() && !o.stdout.is_empty() => {
String::from_utf8(o.stdout).unwrap().trim().to_string()
}
_ => {
eprintln!("skipping flex_bg_image_passes_e2fsck: e2fsck not installed");
return;
}
};
let blocks_per_group = 8 * 4096u32;
let opts = FormatOpts {
kind: FsKind::Ext4,
block_size: 4096,
blocks_count: 2 * blocks_per_group,
inodes_count: 2048,
log_groups_per_flex: 1,
sparse_super: true,
journal_blocks: 1024,
..FormatOpts::default()
};
let size = opts.blocks_count as u64 * opts.block_size as u64;
let tmp = tempfile::NamedTempFile::new().expect("tempfile");
let mut dev =
crate::block::FileBackend::create(tmp.path(), size).expect("create FileBackend");
let mut ext = Ext::format_with(&mut dev, &opts).expect("format flex_bg");
// Plant a couple of files so e2fsck exercises the bitmaps + inode
// table in *both* flex members (not just the leader's slot 0).
let body = vec![b'A'; 8 * 1024];
ext.add_file_to_streaming(
&mut dev,
constants::INO_ROOT_DIR,
b"a.bin",
&mut body.as_slice(),
body.len() as u64,
FileMeta {
mode: 0o644,
uid: 0,
gid: 0,
mtime: 0,
atime: 0,
ctime: 0,
},
)
.expect("add file a.bin");
ext.add_file_to_streaming(
&mut dev,
constants::INO_ROOT_DIR,
b"b.bin",
&mut body.as_slice(),
body.len() as u64,
FileMeta {
mode: 0o644,
uid: 0,
gid: 0,
mtime: 0,
atime: 0,
ctime: 0,
},
)
.expect("add file b.bin");
ext.flush(&mut dev).expect("flush");
BlockDevice::sync(&mut dev).expect("sync");
drop(dev);
let out = Command::new(&e2fsck)
.arg("-fn")
.arg(tmp.path())
.output()
.expect("run e2fsck");
assert!(
out.status.success(),
"e2fsck failed on flex_bg image:\nstdout:\n{}\nstderr:\n{}",
String::from_utf8_lossy(&out.stdout),
String::from_utf8_lossy(&out.stderr),
);
}
#[test]
fn flex_bg_add_and_readback_file() {
// Format a flex_bg image, add a file, reopen, read it back.
let mut dev = MemoryBackend::new(64u64 * 1024 * 1024);
let opts = FormatOpts {
kind: FsKind::Ext4,
block_size: 4096,
blocks_count: 16 * 1024,
inodes_count: 1024,
log_groups_per_flex: 1,
sparse_super: true,
..FormatOpts::default()
};
let mut ext = Ext::format_with(&mut dev, &opts).expect("format flex_bg");
let payload = b"hello flex_bg".to_vec();
ext.add_file_to_streaming(
&mut dev,
constants::INO_ROOT_DIR,
b"greet.txt",
&mut payload.as_slice(),
payload.len() as u64,
FileMeta {
mode: 0o644,
uid: 0,
gid: 0,
mtime: 0,
atime: 0,
ctime: 0,
},
)
.expect("add file");
ext.flush(&mut dev).expect("flush");
// Reopen and read back.
let reopened = Ext::open(&mut dev).expect("reopen");
let ino = reopened
.path_to_inode(&mut dev, "/greet.txt")
.expect("path lookup");
use std::io::Read as _;
let mut buf = Vec::new();
reopened
.open_file_reader(&mut dev, ino)
.expect("open reader")
.read_to_end(&mut buf)
.expect("read");
assert_eq!(&buf, &payload);
}
#[test]
fn use_64bit_sets_feature_and_desc_size() {
// With `use_64bit` the writer must advertise INCOMPAT_64BIT +
// INCOMPAT_META_BG and emit 64-byte descriptors.
let mut dev = MemoryBackend::new(64u64 * 1024 * 1024);
let opts = FormatOpts {
kind: FsKind::Ext4,
block_size: 4096,
blocks_count: 16 * 1024,
inodes_count: 1024,
use_64bit: true,
sparse_super: true,
..FormatOpts::default()
};
let ext = Ext::format_with(&mut dev, &opts).expect("format 64bit");
assert_eq!(ext.sb.desc_size, constants::GROUP_DESC_SIZE_64 as u16);
assert!(
ext.sb.feature_incompat & constants::feature::INCOMPAT_64BIT != 0,
"INCOMPAT_64BIT must be set"
);
assert!(
ext.sb.feature_incompat & constants::feature::INCOMPAT_META_BG != 0,
"INCOMPAT_META_BG must be set (the kernel pair with 64BIT)"
);
assert_eq!(
ext.layout.desc_size,
constants::GROUP_DESC_SIZE_64,
"layout planner must widen desc_size when use_64bit is on"
);
}
#[test]
fn use_64bit_round_trip_add_and_read() {
// Round-trip: format with 64-byte descriptors, add a file, reopen,
// verify the reopened image keeps the same feature set + reads back.
let mut dev = MemoryBackend::new(64u64 * 1024 * 1024);
let opts = FormatOpts {
kind: FsKind::Ext4,
block_size: 4096,
blocks_count: 16 * 1024,
inodes_count: 1024,
use_64bit: true,
sparse_super: true,
..FormatOpts::default()
};
let mut ext = Ext::format_with(&mut dev, &opts).expect("format 64bit");
let payload = b"hello 64-bit".to_vec();
ext.add_file_to_streaming(
&mut dev,
constants::INO_ROOT_DIR,
b"big.txt",
&mut payload.as_slice(),
payload.len() as u64,
FileMeta {
mode: 0o644,
uid: 0,
gid: 0,
mtime: 0,
atime: 0,
ctime: 0,
},
)
.expect("add file");
ext.flush(&mut dev).expect("flush");
let reopened = Ext::open(&mut dev).expect("reopen 64bit");
assert_eq!(reopened.sb.desc_size, constants::GROUP_DESC_SIZE_64 as u16);
assert!(
reopened.sb.feature_incompat & constants::feature::INCOMPAT_64BIT != 0,
"round-tripped image must keep INCOMPAT_64BIT"
);
assert_eq!(reopened.layout.desc_size, constants::GROUP_DESC_SIZE_64);
let ino = reopened
.path_to_inode(&mut dev, "/big.txt")
.expect("path lookup");
use std::io::Read as _;
let mut buf = Vec::new();
reopened
.open_file_reader(&mut dev, ino)
.expect("open reader")
.read_to_end(&mut buf)
.expect("read");
assert_eq!(&buf, &payload);
}
#[test]
fn sparse_super2_off_by_default() {
// Default opts must keep sparse_super2 off (COMPAT_SPARSE_SUPER2 = 0).
let mut dev = MemoryBackend::new(1024 * 1024);
let ext = Ext::format_with(&mut dev, &FormatOpts::default()).expect("format default");
assert_eq!(
ext.sb.feature_compat & constants::feature::COMPAT_SPARSE_SUPER2,
0
);
assert_eq!(ext.sb.backup_bgs, [0, 0]);
}
#[test]
fn sparse_super2_records_backup_bgs_and_skips_other_groups() {
// 4 groups at 4 KiB blocks. With sparse_super2 only groups [1,
// last=3] hold SB+GDT backups; group 2 must not.
let mut dev = MemoryBackend::new(512u64 * 1024 * 1024);
let blocks_per_group = 8 * 4096u32;
let opts = FormatOpts {
kind: FsKind::Ext4,
block_size: 4096,
blocks_count: 4 * blocks_per_group,
inodes_count: 4096,
sparse_super2: true,
..FormatOpts::default()
};
let ext = Ext::format_with(&mut dev, &opts).expect("format sparse_super2");
assert_eq!(ext.layout.num_groups(), 4);
assert!(
ext.sb.feature_compat & constants::feature::COMPAT_SPARSE_SUPER2 != 0,
"COMPAT_SPARSE_SUPER2 must be set"
);
assert_eq!(ext.sb.backup_bgs, [1, 3]);
// Group 0 is always implicit (it holds the primary SB). Group 1
// and group 3 (the two listed) carry backups; group 2 must not.
assert!(ext.layout.groups[0].has_superblock);
assert!(ext.layout.groups[1].has_superblock);
assert!(!ext.layout.groups[2].has_superblock);
assert!(ext.layout.groups[3].has_superblock);
// Round-trip: reopen and verify the on-disk superblock parses the
// same way (backup_bgs decoded, sparse_super2 honoured).
let reopened = Ext::open(&mut dev).expect("reopen sparse_super2");
assert_eq!(reopened.sb.backup_bgs, [1, 3]);
assert!(reopened.sb.feature_compat & constants::feature::COMPAT_SPARSE_SUPER2 != 0);
assert!(!reopened.layout.groups[2].has_superblock);
}
#[test]
fn xattrs_round_trip_on_ext4_image() {
// End-to-end: format an ext4 image (so metadata_csum is on),
// add a regular file, attach a mix of xattrs spanning every
// supported namespace, flush, reopen, and verify
// `read_xattrs` returns the same set the writer was handed.
//
// This exercises the full `set_xattrs` → block alloc →
// CRC32C-stamped block write → `decode_block` path that the
// unit-level encode/decode tests in `xattr.rs` don't cover,
// and pins the `COMPAT_EXT_ATTR` feature bit as a side effect.
let mut dev = MemoryBackend::new(64u64 * 1024 * 1024);
let opts = FormatOpts {
kind: FsKind::Ext4,
block_size: 4096,
blocks_count: 16 * 1024,
inodes_count: 1024,
sparse_super: true,
..FormatOpts::default()
};
let mut ext = Ext::format_with(&mut dev, &opts).expect("format ext4");
let payload = b"hello xattrs".to_vec();
let ino = ext
.add_file_to_streaming(
&mut dev,
constants::INO_ROOT_DIR,
b"labelled.txt",
&mut payload.as_slice(),
payload.len() as u64,
FileMeta {
mode: 0o644,
uid: 0,
gid: 0,
mtime: 0,
atime: 0,
ctime: 0,
},
)
.expect("add file");
// One xattr per supported namespace prefix so the index-encoding
// path is fully covered by a single round-trip.
let xs = vec![
xattr::Xattr::new("user.greeting", b"hello".to_vec()),
xattr::Xattr::new(
"security.selinux",
b"system_u:object_r:unlabeled_t:s0\0".to_vec(),
),
xattr::Xattr::new("trusted.opaque", vec![0u8, 1, 2, 3, 4]),
xattr::Xattr::new("system.foo", b"bar".to_vec()),
];
ext.set_xattrs(&mut dev, ino, &xs).expect("set_xattrs");
ext.flush(&mut dev).expect("flush");
// `COMPAT_EXT_ATTR` must be advertised after attaching xattrs.
assert!(
ext.sb.feature_compat & constants::feature::COMPAT_EXT_ATTR != 0,
"COMPAT_EXT_ATTR must be set once xattrs are attached"
);
let reopened = Ext::open(&mut dev).expect("reopen ext4");
assert!(
reopened.sb.feature_compat & constants::feature::COMPAT_EXT_ATTR != 0,
"round-tripped image must keep COMPAT_EXT_ATTR"
);
let ino2 = reopened
.path_to_inode(&mut dev, "/labelled.txt")
.expect("path lookup");
let mut back = reopened.read_xattrs(&mut dev, ino2).expect("read_xattrs");
// `read_xattrs` returns entries in the kernel's sort order
// (name_index ASC, suffix ASC), so sort the expected set the
// same way before comparing.
let mut want = xs.clone();
let key = |x: &xattr::Xattr| {
let (idx, suffix) = xattr::name_index_and_suffix(&x.name);
(idx, suffix.to_string())
};
back.sort_by_key(&key);
want.sort_by_key(&key);
assert_eq!(back, want);
}
// ───────────────────── open_file_rw (ext2 only) ─────────────────────
use crate::fs::{Filesystem, OpenFlags};
use std::io::{Seek as _, SeekFrom, Write as _};
/// Build a fresh ext2 image, write one regular file via the populate
/// API, flush, and return the live `Ext` + backing device. Block size
/// is fixed at 1 KiB so most data lives in direct pointers; tests
/// that want to exercise indirect blocks size the file accordingly.
fn ext2_with_file(name: &[u8], payload: &[u8]) -> (Ext, MemoryBackend) {
let mut dev = MemoryBackend::new(8 * 1024 * 1024);
let opts = FormatOpts {
kind: FsKind::Ext2,
block_size: 1024,
blocks_count: 8192,
inodes_count: 256,
..FormatOpts::default()
};
let mut ext = Ext::format_with(&mut dev, &opts).expect("format ext2");
if !payload.is_empty() {
ext.add_file_to_streaming(
&mut dev,
constants::INO_ROOT_DIR,
name,
&mut std::io::Cursor::new(payload.to_vec()),
payload.len() as u64,
FileMeta::default(),
)
.expect("add file");
}
ext.flush(&mut dev).expect("flush");
(ext, dev)
}
fn read_full_via_handle(ext: &mut Ext, dev: &mut MemoryBackend, path: &str) -> Vec<u8> {
let p = std::path::Path::new(path);
let mut h = ext
.open_file_rw(dev, p, OpenFlags::default(), None)
.expect("open_file_rw");
let mut out = Vec::new();
h.read_to_end(&mut out).expect("read");
out
}
#[test]
fn open_file_rw_partial_write_round_trip_ext2() {
let payload = vec![b'a'; 4096]; // 4 blocks at 1 KiB
let (mut ext, mut dev) = ext2_with_file(b"hello.bin", &payload);
{
let mut h = ext
.open_file_rw(
&mut dev,
std::path::Path::new("/hello.bin"),
OpenFlags::default(),
None,
)
.expect("open_file_rw");
assert_eq!(h.len(), 4096);
// Patch 4 bytes at offset 1000 (block 0) and 4 bytes at
// offset 2500 (block 2).
h.seek(SeekFrom::Start(1000)).unwrap();
h.write_all(b"XXXX").unwrap();
h.seek(SeekFrom::Start(2500)).unwrap();
h.write_all(b"YYYY").unwrap();
h.sync().expect("sync");
}
// Reopen the FS from disk to verify the writes survived flush.
let mut reopened = Ext::open(&mut dev).expect("reopen");
let got = read_full_via_handle(&mut reopened, &mut dev, "/hello.bin");
assert_eq!(got.len(), 4096);
for (i, b) in got.iter().enumerate() {
let expected = if (1000..1004).contains(&i) {
b'X'
} else if (2500..2504).contains(&i) {
b'Y'
} else {
b'a'
};
assert_eq!(*b, expected, "mismatch at {i}");
}
}
#[test]
fn open_file_rw_extends_file_ext2() {
let payload = b"abcd".to_vec();
let (mut ext, mut dev) = ext2_with_file(b"grow.bin", &payload);
{
let mut h = ext
.open_file_rw(
&mut dev,
std::path::Path::new("/grow.bin"),
OpenFlags::default(),
None,
)
.expect("open");
h.seek(SeekFrom::End(0)).unwrap();
h.write_all(b"EFGH").unwrap();
h.sync().unwrap();
assert_eq!(h.len(), 8);
}
let mut reopened = Ext::open(&mut dev).expect("reopen");
let got = read_full_via_handle(&mut reopened, &mut dev, "/grow.bin");
assert_eq!(got, b"abcdEFGH");
}
#[test]
fn open_file_rw_set_len_grow_and_shrink_ext2() {
// Big enough to spill into the single-indirect range (>12 KiB at
// 1 KiB blocks). Start with a 4 KiB payload, then grow well past
// 12 blocks, then shrink back to 100 bytes.
let payload = vec![b'q'; 4096];
let (mut ext, mut dev) = ext2_with_file(b"flex.bin", &payload);
{
let mut h = ext
.open_file_rw(
&mut dev,
std::path::Path::new("/flex.bin"),
OpenFlags::default(),
None,
)
.unwrap();
// Grow to 20 KiB (forces indirect-block allocation).
h.set_len(20 * 1024).unwrap();
assert_eq!(h.len(), 20 * 1024);
// Bytes beyond the original 4 KiB must read as zero.
let mut buf = vec![0u8; 16 * 1024];
h.seek(SeekFrom::Start(4096)).unwrap();
h.read_exact(&mut buf).unwrap();
assert!(buf.iter().all(|&b| b == 0), "grown region must be zero");
// Now shrink to 100 bytes.
h.set_len(100).unwrap();
assert_eq!(h.len(), 100);
h.sync().unwrap();
}
let mut reopened = Ext::open(&mut dev).expect("reopen");
let got = read_full_via_handle(&mut reopened, &mut dev, "/flex.bin");
assert_eq!(got.len(), 100);
assert!(got.iter().all(|&b| b == b'q'));
// The indirect block should be freed too — free count must be
// back where it was before the grow (or higher, since shrinking
// past the original size also frees the data blocks we just
// allocated). Sanity-check: at least one free block exists.
assert!(reopened.sb.free_blocks_count > 0);
}
#[test]
fn open_file_rw_append_ext2() {
let payload = b"first".to_vec();
let (mut ext, mut dev) = ext2_with_file(b"app.bin", &payload);
{
let mut h = ext
.open_file_rw(
&mut dev,
std::path::Path::new("/app.bin"),
OpenFlags {
append: true,
..OpenFlags::default()
},
None,
)
.unwrap();
h.write_all(b"-second").unwrap();
h.sync().unwrap();
}
let mut reopened = Ext::open(&mut dev).expect("reopen");
let got = read_full_via_handle(&mut reopened, &mut dev, "/app.bin");
assert_eq!(got, b"first-second");
}
#[test]
fn open_file_rw_create_new_ext2() {
let (mut ext, mut dev) = ext2_with_file(b"_unused.bin", b"x");
{
let mut h = ext
.open_file_rw(
&mut dev,
std::path::Path::new("/fresh.txt"),
OpenFlags {
create: true,
..OpenFlags::default()
},
Some(FileMeta::with_mode(0o644)),
)
.expect("open create");
h.write_all(b"hello world").unwrap();
h.sync().unwrap();
}
let mut reopened = Ext::open(&mut dev).expect("reopen");
let got = read_full_via_handle(&mut reopened, &mut dev, "/fresh.txt");
assert_eq!(got, b"hello world");
}
#[test]
fn open_file_rw_truncate_ext2() {
let payload = vec![b'k'; 4096];
let (mut ext, mut dev) = ext2_with_file(b"trunc.bin", &payload);
{
let mut h = ext
.open_file_rw(
&mut dev,
std::path::Path::new("/trunc.bin"),
OpenFlags {
truncate: true,
..OpenFlags::default()
},
None,
)
.unwrap();
assert_eq!(h.len(), 0);
h.write_all(b"short").unwrap();
h.sync().unwrap();
}
let mut reopened = Ext::open(&mut dev).expect("reopen");
let got = read_full_via_handle(&mut reopened, &mut dev, "/trunc.bin");
assert_eq!(got, b"short");
}
/// Build a fresh ext3 image (1 KiB blocks, indirect-tree files) with a
/// 1024-block clean JBD2 journal, write one regular file via the
/// populate API, flush, and return the live `Ext` + backing device.
/// Used by the clean-journal round-trip + dirty-journal refusal tests.
fn ext3_with_file(name: &[u8], payload: &[u8]) -> (Ext, MemoryBackend) {
let mut dev = MemoryBackend::new(8 * 1024 * 1024);
let opts = FormatOpts {
kind: FsKind::Ext3,
block_size: 1024,
blocks_count: 8192,
inodes_count: 256,
journal_blocks: 1024,
sparse_super: true,
..FormatOpts::default()
};
let mut ext = Ext::format_with(&mut dev, &opts).expect("format ext3");
if !payload.is_empty() {
ext.add_file_to_streaming(
&mut dev,
constants::INO_ROOT_DIR,
name,
&mut std::io::Cursor::new(payload.to_vec()),
payload.len() as u64,
FileMeta::default(),
)
.expect("add file");
}
ext.flush(&mut dev).expect("flush");
(ext, dev)
}
#[test]
fn open_file_rw_round_trip_ext3_clean_journal() {
// ext3 has a JBD2 journal; freshly-formatted images have
// s_start = 0 (clean). open_file_rw must accept the image,
// perform the partial write in place, and on sync produce a
// filesystem that round-trips through a fresh `Ext::open`.
let payload = vec![b'a'; 4096];
let (mut ext, mut dev) = ext3_with_file(b"hello.bin", &payload);
{
let mut h = ext
.open_file_rw(
&mut dev,
std::path::Path::new("/hello.bin"),
OpenFlags::default(),
None,
)
.expect("open_file_rw on clean-journal ext3");
assert_eq!(h.len(), 4096);
h.seek(SeekFrom::Start(1000)).unwrap();
h.write_all(b"ZZZZ").unwrap();
h.sync().unwrap();
}
let mut reopened = Ext::open(&mut dev).expect("reopen");
let got = read_full_via_handle(&mut reopened, &mut dev, "/hello.bin");
let mut expect = payload.clone();
expect[1000..1004].copy_from_slice(b"ZZZZ");
assert_eq!(got, expect);
}
/// Format an ext3 image, run `e2fsck -fn` on it after an in-place
/// partial-write through `open_file_rw`. Skipped silently when
/// e2fsck isn't installed.
#[test]
fn open_file_rw_ext3_clean_journal_passes_e2fsck() {
use std::process::Command;
let e2fsck = match Command::new("sh")
.arg("-c")
.arg("command -v e2fsck")
.output()
{
Ok(o) if o.status.success() && !o.stdout.is_empty() => {
String::from_utf8(o.stdout).unwrap().trim().to_string()
}
_ => {
eprintln!(
"skipping open_file_rw_ext3_clean_journal_passes_e2fsck: e2fsck not installed"
);
return;
}
};
let opts = FormatOpts {
kind: FsKind::Ext3,
block_size: 1024,
blocks_count: 8192,
inodes_count: 256,
journal_blocks: 1024,
sparse_super: true,
..FormatOpts::default()
};
let size = opts.blocks_count as u64 * opts.block_size as u64;
let tmp = tempfile::NamedTempFile::new().expect("tempfile");
let mut dev =
crate::block::FileBackend::create(tmp.path(), size).expect("create FileBackend");
let mut ext = Ext::format_with(&mut dev, &opts).expect("format ext3");
let payload = vec![b'a'; 4096];
ext.add_file_to_streaming(
&mut dev,
constants::INO_ROOT_DIR,
b"hello.bin",
&mut std::io::Cursor::new(payload.clone()),
payload.len() as u64,
FileMeta::default(),
)
.expect("add file");
ext.flush(&mut dev).expect("flush");
{
let mut h = ext
.open_file_rw(
&mut dev,
std::path::Path::new("/hello.bin"),
OpenFlags::default(),
None,
)
.expect("open_file_rw on clean-journal ext3");
h.seek(SeekFrom::Start(1000)).unwrap();
h.write_all(b"ZZZZ").unwrap();
h.sync().unwrap();
}
BlockDevice::sync(&mut dev).expect("sync");
drop(dev);
let out = Command::new(&e2fsck)
.arg("-fn")
.arg(tmp.path())
.output()
.expect("run e2fsck");
assert!(
out.status.success(),
"e2fsck failed on ext3 image after rw:\nstdout:\n{}\nstderr:\n{}",
String::from_utf8_lossy(&out.stdout),
String::from_utf8_lossy(&out.stderr),
);
}
#[test]
fn open_file_rw_replays_dirty_journal_on_open() {
// Synthesize a "crash between commit and checkpoint":
// 1) Format ext3, snapshot the pre-write image (clean journal).
// 2) Run an open_file_rw `set_len` that extends the file —
// this updates the inode (size, i_blocks) and the block
// bitmap, both of which ride the journal.
// 3) The sync's journal-commit phase lands descriptor+data+
// commit in the log, then the checkpoint phase writes the
// same blocks to their FS homes and marks the journal
// clean. We snapshot the journal *log* blocks at that
// point — they still hold the committed transaction even
// though the on-disk SB now says s_start=0.
// 4) Restore the pre-write image (rolls back the inode-table
// and bitmaps), restore the journal log blocks (so the
// committed transaction is back on disk), and stamp
// s_start != 0 in the journal SB.
// 5) Open the image and confirm replay re-applies the
// metadata: the extended file size is visible.
let payload = vec![b'a'; 1024];
let (mut ext, mut dev) = ext3_with_file(b"foo.bin", &payload);
let bs = ext.layout.block_size as usize;
let bs64 = ext.layout.block_size as u64;
let nblocks = ext.layout.blocks_count;
// Snapshot the pre-write on-disk image (all rolled-back metadata
// will come from here).
let mut pre_image = vec![0u8; bs * nblocks as usize];
dev.read_at(0, &mut pre_image).expect("snapshot pre-image");
// Note the journal block layout. Journal blocks were allocated
// at format time and don't move; mapping indices to physical
// blocks once is sufficient. Only the leading log slots get
// touched by a small transaction, so iterate to the lower of
// (journal size, 64 — well within the direct-block range for
// 1 KiB indirect-tree inodes the reader can resolve).
let jino = ext.sb.journal_inum;
let jinode = ext.read_inode(&mut dev, jino).expect("journal inode");
let n_journal_blocks = (jinode.size as u64 / bs64) as u32;
let probe = n_journal_blocks.min(64);
let mut journal_phys: Vec<u32> = Vec::with_capacity(probe as usize);
for i in 0..probe {
let phys = ext.file_block(&mut dev, &jinode, i).expect("file_block");
journal_phys.push(phys);
}
// Extend the file via the rw handle — purely a metadata
// operation as far as the journal is concerned (inode-table,
// bitmap, GDT).
{
let mut h = ext
.open_file_rw(
&mut dev,
std::path::Path::new("/foo.bin"),
OpenFlags::default(),
None,
)
.expect("open_file_rw");
h.set_len(4096).expect("set_len");
h.sync().unwrap();
}
// Snapshot the journal log blocks (descriptor + data + commit).
// Even though the on-disk journal SB now reads s_start=0 (clean),
// the log payload from the just-finished commit is still on disk
// because the post-checkpoint cleanup only rewrites the SB.
let mut post_journal: Vec<(u32, Vec<u8>)> = Vec::new();
for phys in &journal_phys {
if *phys == 0 {
continue;
}
let mut buf = vec![0u8; bs];
dev.read_at(*phys as u64 * bs64, &mut buf).expect("read");
post_journal.push((*phys, buf));
}
// Roll the entire image back to the pre-write snapshot.
dev.write_at(0, &pre_image).expect("restore pre-image");
// Restore the journal *log* blocks from the post-write snapshot.
// Skip index 0 (the journal SB itself): pre_image already holds
// the clean (s_sequence=1, s_start=0) journal SB, and that's the
// baseline we need replay to use.
let jsb_phys = journal_phys[0];
for (phys, buf) in &post_journal {
if *phys == jsb_phys {
continue;
}
dev.write_at(*phys as u64 * bs64, buf)
.expect("restore journal");
}
// Dirty the journal SB: set s_start to `s_first` so replay
// walks the log starting at the descriptor we just restored.
// s_sequence is already the tid the transaction was committed
// with (the post-format value), so descriptor.tid will match.
let mut jsb_buf = vec![0u8; bs];
dev.read_at(jsb_phys as u64 * bs64, &mut jsb_buf)
.expect("read jsb");
let first = u32::from_be_bytes(jsb_buf[20..24].try_into().unwrap());
jsb_buf[28..32].copy_from_slice(&first.to_be_bytes());
dev.write_at(jsb_phys as u64 * bs64, &jsb_buf)
.expect("write jsb dirty");
BlockDevice::sync(&mut dev).expect("sync");
// Sanity: a plain read (no replay) still sees the pre-write
// file size — the rollback worked.
{
let reopened = Ext::open(&mut dev).expect("reopen pre-replay");
let ino = reopened
.path_to_inode(&mut dev, "/foo.bin")
.expect("path_to_inode");
let inode = reopened.read_inode(&mut dev, ino).expect("inode");
assert_eq!(
inode.size, 1024,
"pre-replay inode should still show original size"
);
}
// Open for writing: replay must apply the committed transaction
// before the handle attaches. After replay the inode size is
// the extended 4096.
{
let mut ext2 = Ext::open(&mut dev).expect("reopen");
let _ = ext2
.open_file_rw(
&mut dev,
std::path::Path::new("/foo.bin"),
OpenFlags::default(),
None,
)
.expect("open_file_rw triggers replay");
}
let reopened = Ext::open(&mut dev).expect("reopen after replay");
let ino = reopened
.path_to_inode(&mut dev, "/foo.bin")
.expect("path_to_inode");
let inode = reopened.read_inode(&mut dev, ino).expect("inode");
assert_eq!(
inode.size, 4096,
"replay should have applied the journaled inode-table block"
);
// And the journal is now clean.
let mut jsb_after = vec![0u8; bs];
dev.read_at(jsb_phys as u64 * bs64, &mut jsb_after)
.expect("read jsb");
let s_start_after = u32::from_be_bytes(jsb_after[28..32].try_into().unwrap());
assert_eq!(s_start_after, 0, "journal SB s_start must be cleared");
}
/// Build a fresh ext4 image (4 KiB blocks, depth-0 inline extents) with
/// a clean JBD2 journal and one regular file written via the populate
/// API. Used by the ext4 extent-write tests below.
fn ext4_with_file(name: &[u8], payload: &[u8]) -> (Ext, MemoryBackend) {
let mut dev = MemoryBackend::new(64u64 * 1024 * 1024);
let opts = FormatOpts {
kind: FsKind::Ext4,
block_size: 4096,
blocks_count: 16 * 1024,
inodes_count: 1024,
sparse_super: true,
..FormatOpts::default()
};
let mut ext = Ext::format_with(&mut dev, &opts).expect("format ext4");
if !payload.is_empty() {
ext.add_file_to_streaming(
&mut dev,
constants::INO_ROOT_DIR,
name,
&mut std::io::Cursor::new(payload.to_vec()),
payload.len() as u64,
FileMeta::default(),
)
.expect("add file");
}
ext.flush(&mut dev).expect("flush");
(ext, dev)
}
#[test]
fn open_file_rw_round_trip_ext4_extents() {
// Write at an offset inside an existing extent, reopen the FS,
// and verify the modification persists. The image is built on a
// file-backed device so we can hand it to `e2fsck -fn` at the
// end (skipped when e2fsck isn't installed).
use std::process::Command;
let e2fsck = match Command::new("sh")
.arg("-c")
.arg("command -v e2fsck")
.output()
{
Ok(o) if o.status.success() && !o.stdout.is_empty() => {
Some(String::from_utf8(o.stdout).unwrap().trim().to_string())
}
_ => {
eprintln!(
"open_file_rw_round_trip_ext4_extents: e2fsck not installed; skipping fsck check"
);
None
}
};
let opts = FormatOpts {
kind: FsKind::Ext4,
block_size: 4096,
blocks_count: 16 * 1024,
inodes_count: 1024,
sparse_super: true,
..FormatOpts::default()
};
let size = opts.blocks_count as u64 * opts.block_size as u64;
let tmp = tempfile::NamedTempFile::new().expect("tempfile");
let mut dev =
crate::block::FileBackend::create(tmp.path(), size).expect("create FileBackend");
let mut ext = Ext::format_with(&mut dev, &opts).expect("format ext4");
let payload = vec![b'a'; 16 * 1024]; // 4 blocks at 4 KiB
ext.add_file_to_streaming(
&mut dev,
constants::INO_ROOT_DIR,
b"hello.bin",
&mut std::io::Cursor::new(payload.clone()),
payload.len() as u64,
FileMeta::default(),
)
.expect("add file");
ext.flush(&mut dev).expect("flush");
{
let mut h = ext
.open_file_rw(
&mut dev,
std::path::Path::new("/hello.bin"),
OpenFlags::default(),
None,
)
.expect("open_file_rw on ext4 extents");
assert_eq!(h.len(), payload.len() as u64);
// Patch 4 bytes inside block 0 and 4 bytes inside block 2.
h.seek(SeekFrom::Start(1000)).unwrap();
h.write_all(b"XXXX").unwrap();
h.seek(SeekFrom::Start(8500)).unwrap();
h.write_all(b"YYYY").unwrap();
h.sync().expect("sync");
}
let mut reopened = Ext::open(&mut dev).expect("reopen");
let got = {
let mut h = reopened
.open_file_rw(
&mut dev,
std::path::Path::new("/hello.bin"),
OpenFlags::default(),
None,
)
.expect("open_file_rw");
let mut out = Vec::new();
h.read_to_end(&mut out).expect("read");
out
};
assert_eq!(got.len(), payload.len());
for (i, b) in got.iter().enumerate() {
let expected = if (1000..1004).contains(&i) {
b'X'
} else if (8500..8504).contains(&i) {
b'Y'
} else {
b'a'
};
assert_eq!(*b, expected, "mismatch at byte {i}");
}
// Hand the on-disk image to e2fsck if available. `-fn` forces a
// full check in read-only mode.
if let Some(e2fsck) = e2fsck {
BlockDevice::sync(&mut dev).expect("sync");
drop(dev);
let out = Command::new(&e2fsck)
.arg("-fn")
.arg(tmp.path())
.output()
.expect("run e2fsck");
assert!(
out.status.success(),
"e2fsck failed on ext4 image after rw:\nstdout:\n{}\nstderr:\n{}",
String::from_utf8_lossy(&out.stdout),
String::from_utf8_lossy(&out.stderr),
);
}
}
#[test]
fn open_file_rw_extends_ext4_file() {
// Append past EOF; this must allocate a new physical block and
// (depending on contiguity with the existing tail extent) either
// grow that extent or add a new one.
let payload = vec![b'a'; 4096]; // exactly one block
let (mut ext, mut dev) = ext4_with_file(b"grow.bin", &payload);
{
let mut h = ext
.open_file_rw(
&mut dev,
std::path::Path::new("/grow.bin"),
OpenFlags::default(),
None,
)
.expect("open");
h.seek(SeekFrom::End(0)).unwrap();
// Write 5 KiB past EOF — spans into a new block.
let extra = vec![b'b'; 5000];
h.write_all(&extra).unwrap();
h.sync().unwrap();
assert_eq!(h.len(), 4096 + 5000);
}
let mut reopened = Ext::open(&mut dev).expect("reopen");
let got = read_full_via_handle(&mut reopened, &mut dev, "/grow.bin");
assert_eq!(got.len(), 4096 + 5000);
assert!(got[..4096].iter().all(|&b| b == b'a'));
assert!(got[4096..].iter().all(|&b| b == b'b'));
}
#[test]
fn open_file_rw_set_len_grow_and_shrink_ext4() {
// Exercise grow + shrink via set_len on an extent inode.
let payload = vec![b'q'; 4096]; // one block
let (mut ext, mut dev) = ext4_with_file(b"flex.bin", &payload);
{
let mut h = ext
.open_file_rw(
&mut dev,
std::path::Path::new("/flex.bin"),
OpenFlags::default(),
None,
)
.unwrap();
// Grow to 5 blocks. New region must read as zero.
h.set_len(5 * 4096).unwrap();
assert_eq!(h.len(), 5 * 4096);
let mut buf = vec![0u8; 4 * 4096];
h.seek(SeekFrom::Start(4096)).unwrap();
h.read_exact(&mut buf).unwrap();
assert!(buf.iter().all(|&b| b == 0), "grown region must be zero");
// Shrink back to 100 bytes.
h.set_len(100).unwrap();
assert_eq!(h.len(), 100);
h.sync().unwrap();
}
let mut reopened = Ext::open(&mut dev).expect("reopen");
let got = read_full_via_handle(&mut reopened, &mut dev, "/flex.bin");
assert_eq!(got.len(), 100);
assert!(got.iter().all(|&b| b == b'q'));
// The trailing data blocks should have been returned to the
// bitmap — sanity-check the FS still reports free space.
assert!(reopened.sb.free_blocks_count > 0);
}
#[test]
fn open_file_rw_refused_ext4_when_extent_depth_too_deep() {
// Synthesise an inode whose extent header claims depth > 0. The
// writer must refuse cleanly at open time rather than trying to
// walk an index it can't allocate.
let (ext, mut dev) = ext4_with_file(b"deep.bin", b"hello");
// Locate the file's inode and patch its i_block header so eh_depth = 2.
// Depth 0 (inline) and depth 1 (one level of idx → leaf) are both
// supported by the writer; depth 2+ still needs a second level of
// idx-block allocation and is refused.
let ino = ext
.path_to_inode(&mut dev, "/deep.bin")
.expect("path lookup");
let mut inode = ext.read_inode(&mut dev, ino).expect("read inode");
let mut bytes = extent::iblock_to_bytes(&inode.block);
// eh_depth lives at bytes 6..8 (little-endian).
bytes[6..8].copy_from_slice(&2u16.to_le_bytes());
inode.block = extent::bytes_to_iblock(&bytes);
// Write the patched inode straight to disk; we want the
// subsequent open_file_rw to see the on-disk state, not anything
// cached by `ext`.
let (group, idx) = ext.inode_location(ino);
let table_block = ext.layout.groups[group as usize].inode_table;
let bs = ext.layout.block_size as u64;
let off = table_block as u64 * bs + idx as u64 * ext.layout.inode_size as u64;
let mut enc = inode.encode().to_vec();
if ext.layout.inode_size as usize > enc.len() {
enc.resize(ext.layout.inode_size as usize, 0);
}
dev.write_at(off, &enc).expect("write patched inode");
// Reopen the FS so the staged-inode cache is empty.
let mut ext = Ext::open(&mut dev).expect("reopen");
let res = ext.open_file_rw(
&mut dev,
std::path::Path::new("/deep.bin"),
OpenFlags::default(),
None,
);
match res {
Ok(_) => panic!("must refuse on deeper extent tree"),
Err(crate::Error::Unsupported(msg)) => {
assert!(msg.contains("depth"), "unexpected message: {msg}");
}
Err(other) => panic!("expected Unsupported, got {other}"),
}
}
/// Build an ext4 file whose extent tree must spill into depth-1
/// (more than 4 leaf extents). We force fragmentation by writing
/// individual blocks at logically-discontiguous offsets, so each
/// block sits in its own extent run rather than merging into a
/// single run.
#[test]
fn open_file_rw_depth1_extent_round_trip_ext4() {
let mut dev = MemoryBackend::new(64u64 * 1024 * 1024);
let opts = FormatOpts {
kind: FsKind::Ext4,
block_size: 4096,
blocks_count: 16 * 1024,
inodes_count: 1024,
sparse_super: true,
..FormatOpts::default()
};
let mut ext = Ext::format_with(&mut dev, &opts).expect("format ext4");
// Start from an empty file so every alloc lands somewhere
// chosen by the bitmap walker rather than continuing a tail.
ext.add_file_to_streaming(
&mut dev,
constants::INO_ROOT_DIR,
b"deep.bin",
&mut std::io::Cursor::new(Vec::<u8>::new()),
0,
FileMeta::default(),
)
.expect("add empty file");
ext.flush(&mut dev).expect("flush");
// Six distinct sparse offsets → six logically-discontiguous
// extents (depth-0 caps at 4, so the tree must promote to
// depth-1).
let offsets: &[u64] = &[0, 40_000, 80_000, 120_000, 160_000, 200_000];
let mark = b"DEPTH1!"; // 7 bytes, well under a block
{
let mut h = ext
.open_file_rw(
&mut dev,
std::path::Path::new("/deep.bin"),
OpenFlags::default(),
None,
)
.expect("open_file_rw on empty extent file");
for off in offsets {
h.seek(SeekFrom::Start(*off)).unwrap();
h.write_all(mark).unwrap();
}
h.sync().expect("sync");
assert_eq!(h.len(), 200_000 + mark.len() as u64);
}
// Walk the on-disk inode to verify the tree is in fact depth-1.
let ino = ext.path_to_inode(&mut dev, "/deep.bin").expect("ino");
let inode = ext.read_inode(&mut dev, ino).expect("read inode");
let iblock = extent::iblock_to_bytes(&inode.block);
let header = extent::decode_header(&iblock[..12]).expect("header");
assert_eq!(
header.depth, 1,
"expected depth-1 extent tree, got depth {}",
header.depth
);
assert!(
header.entries >= 1 && header.entries <= 4,
"expected 1..=4 idx entries, got {}",
header.entries
);
// Reopen and verify the contents survive. Each marked offset
// must read back its bytes; everything else must read as zero.
let mut reopened = Ext::open(&mut dev).expect("reopen");
let mut h = reopened
.open_file_rw(
&mut dev,
std::path::Path::new("/deep.bin"),
OpenFlags::default(),
None,
)
.expect("reopen rw on depth-1 file");
for off in offsets {
h.seek(SeekFrom::Start(*off)).unwrap();
let mut buf = vec![0u8; mark.len()];
h.read_exact(&mut buf).unwrap();
assert_eq!(&buf[..], mark, "marker mismatch at offset {off}");
}
// Pick a block we never wrote and verify it's zero (hole).
h.seek(SeekFrom::Start(20_000)).unwrap();
let mut zero = vec![0u8; 4096];
h.read_exact(&mut zero).unwrap();
assert!(
zero.iter().all(|&b| b == 0),
"untouched region must be zero"
);
}
/// Round-trip a depth-1 tree through shrink: write enough extents to
/// promote to depth-1, then shrink past EOF and confirm the tree
/// drops back to depth-0 and any leaf blocks are returned to the
/// bitmap.
#[test]
fn open_file_rw_depth1_shrink_back_to_depth0() {
let mut dev = MemoryBackend::new(64u64 * 1024 * 1024);
let opts = FormatOpts {
kind: FsKind::Ext4,
block_size: 4096,
blocks_count: 16 * 1024,
inodes_count: 1024,
sparse_super: true,
..FormatOpts::default()
};
let mut ext = Ext::format_with(&mut dev, &opts).expect("format ext4");
ext.add_file_to_streaming(
&mut dev,
constants::INO_ROOT_DIR,
b"shrink.bin",
&mut std::io::Cursor::new(Vec::<u8>::new()),
0,
FileMeta::default(),
)
.unwrap();
ext.flush(&mut dev).expect("flush");
// Snapshot free-block count before any depth-1 work.
let free_before = ext.sb.free_blocks_count;
{
let mut h = ext
.open_file_rw(
&mut dev,
std::path::Path::new("/shrink.bin"),
OpenFlags::default(),
None,
)
.expect("open empty");
for &off in &[0u64, 40_000, 80_000, 120_000, 160_000] {
h.seek(SeekFrom::Start(off)).unwrap();
h.write_all(b"x").unwrap();
}
h.sync().unwrap();
// Confirm we hit depth-1 mid-sequence.
let ino_now = h.len(); // not used; the assert below uses inode lookup
let _ = ino_now;
}
{
// Walk the inode to confirm depth-1 reached.
let ino = ext.path_to_inode(&mut dev, "/shrink.bin").unwrap();
let inode = ext.read_inode(&mut dev, ino).unwrap();
let iblock = extent::iblock_to_bytes(&inode.block);
let header = extent::decode_header(&iblock[..12]).expect("header");
assert_eq!(header.depth, 1, "should be depth-1 mid-shrink");
}
// Now truncate to 100 bytes — drops back to a single block, well
// within depth-0.
{
let mut h = ext
.open_file_rw(
&mut dev,
std::path::Path::new("/shrink.bin"),
OpenFlags::default(),
None,
)
.expect("reopen");
h.set_len(100).unwrap();
h.sync().unwrap();
}
{
let ino = ext.path_to_inode(&mut dev, "/shrink.bin").unwrap();
let inode = ext.read_inode(&mut dev, ino).unwrap();
let iblock = extent::iblock_to_bytes(&inode.block);
let header = extent::decode_header(&iblock[..12]).expect("header");
assert_eq!(header.depth, 0, "should drop back to depth-0 after shrink");
}
// The leaf block(s) and any freed data blocks must be back in the
// bitmap — free-blocks should be ≥ free_before − 1 (we still have
// the one data block holding the surviving 100 bytes).
let free_after = ext.sb.free_blocks_count;
assert!(
free_after + 2 >= free_before,
"shrink leaked blocks: free was {free_before}, now {free_after}",
);
}
#[test]
fn open_file_ro_random_seek_ext() {
// open_file_ro must work for both ext2 (indirect blocks) and ext4
// (extents); the file_block walker handles both formats. Test on
// ext4 to lock in the case open_file_rw can't satisfy.
use crate::fs::Filesystem;
use std::io::{Read, Seek, SeekFrom};
let mut dev = MemoryBackend::new(64u64 * 1024 * 1024);
let opts = FormatOpts {
kind: FsKind::Ext4,
block_size: 4096,
blocks_count: 16 * 1024,
inodes_count: 1024,
sparse_super: true,
..FormatOpts::default()
};
let mut ext = Ext::format_with(&mut dev, &opts).expect("format ext4");
// Multi-block file to exercise the extent walker.
let data: Vec<u8> = (0..15_000u32).map(|i| (i & 0xFF) as u8).collect();
ext.add_file_to_streaming(
&mut dev,
constants::INO_ROOT_DIR,
b"ro.bin",
&mut std::io::Cursor::new(data.clone()),
data.len() as u64,
FileMeta::default(),
)
.unwrap();
ext.flush(&mut dev).unwrap();
// Reopen and exercise the read-only path through the trait.
let mut ext = Ext::open(&mut dev).expect("reopen ext4");
let mut h = ext
.open_file_ro(&mut dev, std::path::Path::new("/ro.bin"))
.expect("open_file_ro on ext4 extent file");
assert_eq!(h.len(), data.len() as u64);
assert!(!h.is_empty());
h.seek(SeekFrom::Start(9876)).unwrap();
let mut buf = [0u8; 200];
h.read_exact(&mut buf).unwrap();
assert_eq!(&buf[..], &data[9876..10076]);
h.seek(SeekFrom::Start(42)).unwrap();
let mut buf2 = [0u8; 64];
h.read_exact(&mut buf2).unwrap();
assert_eq!(&buf2[..], &data[42..106]);
}
}