btrfs-cli 0.12.0

User-space command-line tool for inspecting and managing Btrfs filesystems
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
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
//! Tests that create and mutate real btrfs filesystems.
//!
//! Some tests use assertion-based checks (mutating commands, round-trips),
//! others use snapshot testing for output verification.

use super::{btrfs, btrfs_ok, common, redact};
use btrfs_uapi::{
    device::device_info_all,
    filesystem::filesystem_info,
    subvolume::{self, SubvolumeFlags, subvolume_flags_get},
};
use common::{
    BackingFile, LoopbackDevice, Mount, our_mkfs_bin, single_mount,
    verify_test_data, write_compressible_data, write_test_data,
};
use nix::sys::stat;
use regex_lite::Regex;
use std::{
    fs,
    io::{Read as _, Seek, SeekFrom},
    os::unix::{
        fs::{FileTypeExt, MetadataExt, symlink},
        io::AsFd,
    },
    path::{Path, PathBuf},
    process::Command,
};
use tempfile::tempdir;

// ── filesystem (assertions) ──────────────────────────────────────────

#[test]
#[ignore = "requires elevated privileges"]
fn filesystem_sync() {
    let (_td, mnt) = single_mount();
    let (_, _, code) =
        btrfs(&["filesystem", "sync", mnt.path().to_str().unwrap()]);
    assert_eq!(code, 0);
}

#[test]
#[ignore = "requires elevated privileges"]
fn filesystem_label_get_set() {
    let (_td, mnt) = single_mount();
    let mp = mnt.path().to_str().unwrap();

    btrfs_ok(&["filesystem", "label", mp, "test-label"]);

    let out = btrfs_ok(&["filesystem", "label", mp]);
    assert!(
        out.contains("test-label"),
        "expected label in output:\n{out}"
    );

    // Verify via uapi
    let label = btrfs_uapi::filesystem::label_get(mnt.fd()).unwrap();
    assert_eq!(label.to_str().unwrap(), "test-label");
}

#[test]
#[ignore = "requires elevated privileges"]
fn filesystem_resize_grow_shrink() {
    let (_td, mnt) = single_mount();
    let mp = mnt.path().to_str().unwrap();

    mnt.loopback().backing_file().unwrap().resize(768_000_000);
    mnt.loopback().refresh_size();
    btrfs_ok(&["filesystem", "resize", "max", mp]);

    let out = btrfs_ok(&["filesystem", "usage", mp]);
    assert!(
        out.contains("Device size:"),
        "expected usage output:\n{out}"
    );

    // Verify via uapi: after resize max, device should be close to 768MB
    let fs_info = filesystem_info(mnt.fd()).unwrap();
    let devices = device_info_all(mnt.fd(), &fs_info).unwrap();
    let total: u64 = devices.iter().map(|d| d.total_bytes).sum();
    assert!(
        total > 700_000_000,
        "expected >700MB after resize max, got {total}"
    );

    btrfs_ok(&["filesystem", "resize", "512m", mp]);

    // Verify via uapi: after resize 512m
    let fs_info = filesystem_info(mnt.fd()).unwrap();
    let devices = device_info_all(mnt.fd(), &fs_info).unwrap();
    let total: u64 = devices.iter().map(|d| d.total_bytes).sum();
    assert!(
        total <= 512 * 1024 * 1024,
        "expected <=512MiB after resize 512m, got {total}"
    );
}

#[test]
#[ignore = "requires elevated privileges"]
fn filesystem_du_shared() {
    let (_td, mnt) = single_mount();
    let mp = mnt.path().to_str().unwrap();

    // Create a directory structure with reflinked and exclusive files.
    let dir = format!("{mp}/testdir");
    fs::create_dir(&dir).unwrap();
    write_test_data(Path::new(&dir), "original.bin", 256 * 1024);
    // Reflink copy: shares extents with the original.
    Command::new("cp")
        .args([
            "--reflink=always",
            &format!("{dir}/original.bin"),
            &format!("{dir}/clone.bin"),
        ])
        .status()
        .expect("cp --reflink failed");
    // A non-reflinked file: all bytes are exclusive.
    write_test_data(Path::new(&dir), "unique.bin", 128 * 1024);
    btrfs_ok(&["filesystem", "sync", mp]);

    snap!(
        "btrfs filesystem du <MOUNT>/testdir",
        redact(&btrfs_ok(&["filesystem", "du", &dir]), &mnt)
    );
}

#[test]
#[ignore = "requires elevated privileges"]
fn filesystem_defrag() {
    let (_td, mnt) = single_mount();
    let mp = mnt.path().to_str().unwrap();

    write_test_data(Path::new(mp), "fragmented.bin", 65536);
    btrfs_ok(&["filesystem", "sync", mp]);

    btrfs_ok(&["filesystem", "defragment", &format!("{mp}/fragmented.bin")]);

    verify_test_data(Path::new(mp), "fragmented.bin", 65536);
}

#[test]
#[ignore = "requires elevated privileges"]
fn filesystem_defrag_compress() {
    let (_td, mnt) = single_mount();
    let mp = mnt.path().to_str().unwrap();

    common::write_compressible_data(Path::new(mp), "compressible.bin", 131072);
    btrfs_ok(&["filesystem", "sync", mp]);

    btrfs_ok(&[
        "filesystem",
        "defragment",
        "-czstd",
        &format!("{mp}/compressible.bin"),
    ]);
}

#[test]
#[ignore = "requires elevated privileges"]
fn filesystem_commit_stats() {
    let (_td, mnt) = single_mount();
    let mp = mnt.path().to_str().unwrap();
    btrfs_ok(&["filesystem", "sync", mp]);

    let out = btrfs_ok(&["filesystem", "commit-stats", mp]);
    assert!(
        out.contains("Total commits"),
        "expected commit count:\n{out}"
    );
    assert!(
        out.contains("Max commit duration"),
        "expected max duration:\n{out}"
    );
}

#[test]
#[ignore = "requires elevated privileges"]
fn filesystem_mkswapfile() {
    let (_td, mnt) = single_mount();
    let mp = mnt.path().to_str().unwrap();
    let swapfile = format!("{mp}/swapfile");

    btrfs_ok(&["filesystem", "mkswapfile", "-s", "16m", &swapfile]);
    assert!(Path::new(&swapfile).exists(), "swapfile not created");

    let meta = fs::metadata(&swapfile).unwrap();
    assert!(
        meta.len() >= 16 * 1024 * 1024,
        "swapfile too small: {} bytes",
        meta.len()
    );
}

#[test]
#[ignore = "requires elevated privileges"]
fn filesystem_resize_offline_grow() {
    // Start with a 256 MiB image, grow the backing file to 512 MiB,
    // and use `filesystem resize --offline max` to enlarge the
    // filesystem in place. btrfs check must then pass.
    let td = tempdir().unwrap();
    let file = BackingFile::new(td.path(), "disk.img", 256 * 1024 * 1024);
    file.mkfs_with_args(&["-O", "^block-group-tree"]);

    // Grow the backing file to 512 MiB.
    {
        let f = std::fs::OpenOptions::new()
            .write(true)
            .open(file.path())
            .unwrap();
        f.set_len(512 * 1024 * 1024).unwrap();
    }

    let dev = file.path().to_str().unwrap();
    btrfs_ok(&["filesystem", "resize", "--offline", "max", dev]);

    let check = Command::new("btrfs")
        .args(["check", "--readonly", dev])
        .output()
        .expect("failed to run btrfs check");
    if !check.status.success() {
        panic!(
            "btrfs check failed:\nstdout:\n{}\nstderr:\n{}",
            String::from_utf8_lossy(&check.stdout),
            String::from_utf8_lossy(&check.stderr)
        );
    }

    // Running it again at the same size is a no-op.
    btrfs_ok(&["filesystem", "resize", "--offline", "max", dev]);
}

#[test]
#[ignore = "requires elevated privileges"]
fn filesystem_resize_offline_rejects_shrink() {
    let td = tempdir().unwrap();
    let file = BackingFile::new(td.path(), "disk.img", 256 * 1024 * 1024);
    file.mkfs_with_args(&["-O", "^block-group-tree"]);

    let dev = file.path().to_str().unwrap();
    let (_, _, code) =
        btrfs(&["filesystem", "resize", "--offline", "-64m", dev]);
    assert_ne!(code, 0, "shrink should be rejected");

    let (_, _, code2) =
        btrfs(&["filesystem", "resize", "--offline", "128m", dev]);
    assert_ne!(code2, 0, "absolute shrink should be rejected");
}

#[test]
#[ignore = "requires elevated privileges"]
fn tune_convert_to_free_space_tree() {
    // mkfs without the free-space-tree feature, then run
    // `btrfs tune --convert-to-free-space-tree` and assert btrfs
    // check is clean and the FREE_SPACE_TREE compat_ro bit is set.
    let td = tempdir().unwrap();
    let file = BackingFile::new(td.path(), "disk.img", 256 * 1024 * 1024);
    file.mkfs_with_args(&["-O", "^free-space-tree,^block-group-tree"]);

    let dev = file.path().to_str().unwrap();

    // Run the conversion via the tune subcommand.
    btrfs_ok(&["tune", "--convert-to-free-space-tree", dev]);

    // btrfs check must pass.
    let check = Command::new("btrfs")
        .args(["check", "--readonly", dev])
        .output()
        .expect("failed to run btrfs check");
    if !check.status.success() {
        panic!(
            "btrfs check failed:\nstdout:\n{}\nstderr:\n{}",
            String::from_utf8_lossy(&check.stdout),
            String::from_utf8_lossy(&check.stderr)
        );
    }

    // Verify the bit is set in the superblock.
    let dump = btrfs_ok(&["inspect-internal", "dump-super", dev]);
    assert!(
        dump.contains("FREE_SPACE_TREE")
            && dump.contains("FREE_SPACE_TREE_VALID"),
        "expected FREE_SPACE_TREE + _VALID in dump-super, got:\n{dump}"
    );

    // Idempotency: a second invocation must fail with the
    // already-enabled error.
    let (_, _, code) = btrfs(&["tune", "--convert-to-free-space-tree", dev]);
    assert_ne!(code, 0, "second conversion should be rejected");
}

#[test]
#[ignore = "requires elevated privileges"]
fn tune_convert_to_block_group_tree() {
    // mkfs without the block-group-tree feature (FST is on by
    // default in modern mkfs), then run
    // `btrfs tune --convert-to-block-group-tree` and assert btrfs
    // check is clean and the BLOCK_GROUP_TREE compat_ro bit is set.
    let td = tempdir().unwrap();
    let file = BackingFile::new(td.path(), "disk.img", 256 * 1024 * 1024);
    file.mkfs_with_args(&["-O", "^block-group-tree"]);

    let dev = file.path().to_str().unwrap();

    btrfs_ok(&["tune", "--convert-to-block-group-tree", dev]);

    let check = Command::new("btrfs")
        .args(["check", "--readonly", dev])
        .output()
        .expect("failed to run btrfs check");
    if !check.status.success() {
        panic!(
            "btrfs check failed:\nstdout:\n{}\nstderr:\n{}",
            String::from_utf8_lossy(&check.stdout),
            String::from_utf8_lossy(&check.stderr)
        );
    }

    let dump = btrfs_ok(&["inspect-internal", "dump-super", dev]);
    assert!(
        dump.contains("BLOCK_GROUP_TREE"),
        "expected BLOCK_GROUP_TREE in dump-super, got:\n{dump}"
    );

    // Idempotency: a second invocation must fail.
    let (_, _, code) = btrfs(&["tune", "--convert-to-block-group-tree", dev]);
    assert_ne!(code, 0, "second conversion should be rejected");
}

#[test]
#[ignore = "requires elevated privileges"]
fn tune_convert_to_bgt_requires_fst() {
    // BGT depends on FST. mkfs without either, then attempt the
    // BGT conversion: should be rejected.
    let td = tempdir().unwrap();
    let file = BackingFile::new(td.path(), "disk.img", 256 * 1024 * 1024);
    file.mkfs_with_args(&["-O", "^block-group-tree,^free-space-tree"]);

    let dev = file.path().to_str().unwrap();
    let (_, _, code) = btrfs(&["tune", "--convert-to-block-group-tree", dev]);
    assert_ne!(code, 0, "BGT without FST should be rejected");
}

// ── filesystem resize error cases ────────────────────────────────────

#[test]
#[ignore = "requires elevated privileges"]
fn filesystem_resize_missing_args() {
    // resize with no arguments should fail.
    let (_, _, code) = btrfs(&["filesystem", "resize"]);
    assert_ne!(code, 0);
}

#[test]
#[ignore = "requires elevated privileges"]
fn filesystem_resize_invalid_size() {
    let (_td, mnt) = single_mount();
    let mp = mnt.path().to_str().unwrap();
    // Bogus size string should fail.
    let (_, _, code) = btrfs(&["filesystem", "resize", "banana", mp]);
    assert_ne!(code, 0);
}

// ── filesystem defrag compression variants ──────────────────────────

#[test]
#[ignore = "requires elevated privileges"]
fn filesystem_defrag_compress_lzo() {
    let (_td, mnt) = single_mount();
    let mp = mnt.path().to_str().unwrap();
    common::write_compressible_data(Path::new(mp), "lzo.bin", 131072);
    btrfs_ok(&["filesystem", "sync", mp]);
    btrfs_ok(&[
        "filesystem",
        "defragment",
        "-clzo",
        &format!("{mp}/lzo.bin"),
    ]);
}

#[test]
#[ignore = "requires elevated privileges"]
fn filesystem_defrag_compress_zlib() {
    let (_td, mnt) = single_mount();
    let mp = mnt.path().to_str().unwrap();
    common::write_compressible_data(Path::new(mp), "zlib.bin", 131072);
    btrfs_ok(&["filesystem", "sync", mp]);
    btrfs_ok(&[
        "filesystem",
        "defragment",
        "-czlib",
        &format!("{mp}/zlib.bin"),
    ]);
}

// ── filesystem defrag recursion ─────────────────────────────────────

#[test]
#[ignore = "requires elevated privileges"]
fn filesystem_defrag_recursion_with_subvol() {
    let (_td, mnt) = single_mount();
    let mp = mnt.path().to_str().unwrap();

    // Create a file in the root volume.
    write_test_data(Path::new(mp), "root_file.bin", 65536);
    // Create a subvolume with its own file.
    let subvol = format!("{mp}/subvol");
    btrfs_ok(&["subvolume", "create", &subvol]);
    write_test_data(Path::new(&subvol), "subvol_file.bin", 65536);
    btrfs_ok(&["filesystem", "sync", mp]);

    // Recursive defrag from the root should complete without errors,
    // stopping at the subvolume boundary.
    btrfs_ok(&["filesystem", "defragment", "-r", mp]);

    // Both files should still be intact.
    verify_test_data(Path::new(mp), "root_file.bin", 65536);
    verify_test_data(Path::new(&subvol), "subvol_file.bin", 65536);
}

// ── filesystem df unit suffixes ─────────────────────────────────────

#[test]
#[ignore = "requires elevated privileges"]
fn filesystem_df_raw() {
    let (_td, mnt) = single_mount();
    let mp = mnt.path().to_str().unwrap();
    let out = btrfs_ok(&["filesystem", "df", "--raw", mp]);
    // Raw mode should output plain numbers (no KiB/MiB suffixes).
    assert!(out.contains("total="), "expected raw output:\n{out}");
    assert!(!out.contains("MiB"), "raw mode should not use MiB:\n{out}");
}

#[test]
#[ignore = "requires elevated privileges"]
fn filesystem_df_kbytes() {
    let (_td, mnt) = single_mount();
    let mp = mnt.path().to_str().unwrap();
    let raw = btrfs_ok(&["filesystem", "df", "--raw", mp]);
    let kb = btrfs_ok(&["filesystem", "df", "--kbytes", mp]);
    // --kbytes divides values by 1024 (no suffix). The numbers should
    // be smaller than --raw output.
    assert_ne!(raw, kb, "--kbytes should differ from --raw");
}

#[test]
#[ignore = "requires elevated privileges"]
fn filesystem_df_mbytes() {
    let (_td, mnt) = single_mount();
    let mp = mnt.path().to_str().unwrap();
    let raw = btrfs_ok(&["filesystem", "df", "--raw", mp]);
    let mb = btrfs_ok(&["filesystem", "df", "--mbytes", mp]);
    assert_ne!(raw, mb, "--mbytes should differ from --raw");
}

#[test]
#[ignore = "requires elevated privileges"]
fn filesystem_df_si() {
    let (_td, mnt) = single_mount();
    let mp = mnt.path().to_str().unwrap();
    let out = btrfs_ok(&["filesystem", "df", "--si", mp]);
    // SI mode uses base-1000 suffixes (kB, MB, GB).
    assert!(
        out.contains('B'),
        "expected size suffix in --si output:\n{out}"
    );
}

// ── subvolume ────────────────────────────────────────────────────────

#[test]
#[ignore = "requires elevated privileges"]
fn subvolume_create_show_delete() {
    let (_td, mnt) = single_mount();
    let mp = mnt.path().to_str().unwrap();
    let subvol = format!("{mp}/testvol");

    btrfs_ok(&["subvolume", "create", &subvol]);
    assert!(Path::new(&subvol).is_dir());

    // Verify via uapi: subvolume appears in list
    let list = subvolume::subvolume_list(mnt.fd()).unwrap();
    assert!(
        list.iter().any(|s| s.name.contains("testvol")),
        "subvolume should appear in uapi list"
    );

    let out = btrfs_ok(&["subvolume", "show", &subvol]);
    assert!(
        out.contains("testvol"),
        "expected name in show output:\n{out}"
    );

    btrfs_ok(&["subvolume", "delete", &subvol]);
    assert!(!Path::new(&subvol).exists());

    // Verify via uapi: subvolume gone from list
    let list = subvolume::subvolume_list(mnt.fd()).unwrap();
    assert!(
        !list.iter().any(|s| s.name.contains("testvol")),
        "subvolume should not appear in uapi list after delete"
    );
}

#[test]
#[ignore = "requires elevated privileges"]
fn subvolume_list() {
    let (_td, mnt) = single_mount();
    let mp = mnt.path().to_str().unwrap();

    btrfs_ok(&["subvolume", "create", &format!("{mp}/alpha")]);
    btrfs_ok(&["subvolume", "create", &format!("{mp}/beta")]);

    let out = btrfs_ok(&["subvolume", "list", mp]);
    assert!(out.contains("alpha"), "expected alpha in list:\n{out}");
    assert!(out.contains("beta"), "expected beta in list:\n{out}");
}

#[test]
#[ignore = "requires elevated privileges"]
fn subvolume_list_snapshot_parent_id() {
    let (_td, mnt) = single_mount();
    let mp = mnt.path().to_str().unwrap();

    // Create a subvolume and a snapshot of it.
    btrfs_ok(&["subvolume", "create", &format!("{mp}/parent_sv")]);
    btrfs_ok(&[
        "subvolume",
        "snapshot",
        &format!("{mp}/parent_sv"),
        &format!("{mp}/snap_of_parent"),
    ]);

    // The snapshot should appear with correct parent and name.
    let out = btrfs_ok(&["subvolume", "list", mp]);
    let lines: Vec<&str> = out.lines().collect();
    // We expect two subvolumes: parent_sv and snap_of_parent.
    assert_eq!(lines.len(), 2, "expected 2 subvolumes:\n{out}");

    // Find the snapshot line (ID 257, the second subvolume created).
    // Parse "ID NNN gen NNN top level NNN path NAME"
    let snap_line = lines
        .iter()
        .find(|l| !l.contains("parent_sv"))
        .expect("expected a snapshot line");
    assert!(
        snap_line.contains("snap_of_parent"),
        "snapshot should have name 'snap_of_parent':\n{out}"
    );
    assert!(
        snap_line.contains("top level 5"),
        "snapshot top level should be 5 (FS_TREE):\n{out}"
    );
}

#[test]
#[ignore = "requires elevated privileges"]
fn subvolume_snapshot() {
    let (_td, mnt) = single_mount();
    let mp = mnt.path().to_str().unwrap();
    let src = format!("{mp}/src");
    let snap = format!("{mp}/snap");

    btrfs_ok(&["subvolume", "create", &src]);
    write_test_data(Path::new(&src), "data.bin", 4096);

    btrfs_ok(&["subvolume", "snapshot", "-r", &src, &snap]);

    verify_test_data(Path::new(&snap), "data.bin", 4096);

    let out = btrfs_ok(&["property", "get", "-t", "subvol", &snap, "ro"]);
    assert!(out.contains("true"), "expected ro=true:\n{out}");
}

#[test]
#[ignore = "requires elevated privileges"]
fn subvolume_get_set_default() {
    let (_td, mnt) = single_mount();
    let mp = mnt.path().to_str().unwrap();

    let out = btrfs_ok(&["subvolume", "get-default", mp]);
    assert!(out.contains("5"), "expected ID 5:\n{out}");

    btrfs_ok(&["subvolume", "create", &format!("{mp}/newdefault")]);
    btrfs_ok(&["subvolume", "set-default", &format!("{mp}/newdefault")]);

    let out = btrfs_ok(&["subvolume", "get-default", mp]);
    assert!(!out.contains("ID 5"), "expected non-5 default:\n{out}");

    // Verify via uapi: default should no longer be 5
    let default_id =
        btrfs_uapi::subvolume::subvolume_default_get(mnt.fd()).unwrap();
    assert_ne!(
        default_id, 5,
        "default subvol should not be 5 after set-default"
    );

    btrfs_ok(&["subvolume", "set-default", "5", mp]);
    let out = btrfs_ok(&["subvolume", "get-default", mp]);
    assert!(out.contains("5"), "expected ID 5 restored:\n{out}");

    // Verify via uapi: default restored to 5
    let default_id =
        btrfs_uapi::subvolume::subvolume_default_get(mnt.fd()).unwrap();
    assert_eq!(default_id, 5, "default subvol should be 5 after restore");
}

#[test]
#[ignore = "requires elevated privileges"]
fn subvolume_get_set_flags() {
    let (_td, mnt) = single_mount();
    let mp = mnt.path().to_str().unwrap();
    let subvol = format!("{mp}/flagtest");

    btrfs_ok(&["subvolume", "create", &subvol]);

    let out = btrfs_ok(&["subvolume", "get-flags", &subvol]);
    assert!(
        !out.contains("readonly"),
        "expected no readonly flag:\n{out}"
    );

    btrfs_ok(&["subvolume", "set-flags", "readonly", &subvol]);
    let out = btrfs_ok(&["subvolume", "get-flags", &subvol]);
    assert!(out.contains("readonly"), "expected readonly flag:\n{out}");

    btrfs_ok(&["subvolume", "set-flags", "-", &subvol]);
    let out = btrfs_ok(&["subvolume", "get-flags", &subvol]);
    assert!(
        !out.contains("readonly"),
        "expected no readonly flag:\n{out}"
    );
}

// ── subvolume create -p (parent creation) ───────────────────────────

#[test]
#[ignore = "requires elevated privileges"]
fn subvolume_create_parents() {
    let (_td, mnt) = single_mount();
    let mp = mnt.path().to_str().unwrap();

    // Without -p, creating in a non-existent parent directory should fail.
    let deep = format!("{mp}/dir1/dir2/subvol");
    let (_, _, code) = btrfs(&["subvolume", "create", &deep]);
    assert_ne!(code, 0, "create without -p in missing dir should fail");

    // With -p, parent directories are created automatically.
    btrfs_ok(&["subvolume", "create", "-p", &deep]);
    assert!(Path::new(&deep).is_dir());

    // Verify the parent directories exist and the subvolume is listed.
    let out = btrfs_ok(&["subvolume", "list", mp]);
    assert!(
        out.contains("dir1/dir2/subvol"),
        "expected nested subvol in list:\n{out}"
    );
}

// ── subvolume create failures ───────────────────────────────────────

#[test]
#[ignore = "requires elevated privileges"]
fn subvolume_create_existing_path_fails() {
    let (_td, mnt) = single_mount();
    let mp = mnt.path().to_str().unwrap();

    let subvol = format!("{mp}/existing");
    btrfs_ok(&["subvolume", "create", &subvol]);

    // Creating the same subvolume again should fail.
    let (_, _, code) = btrfs(&["subvolume", "create", &subvol]);
    assert_ne!(code, 0, "create over existing subvolume should fail");
}

#[test]
#[ignore = "requires elevated privileges"]
fn subvolume_create_over_file_fails() {
    let (_td, mnt) = single_mount();
    let mp = mnt.path().to_str().unwrap();

    let file = format!("{mp}/afile");
    fs::write(&file, b"hello").unwrap();

    // Creating a subvolume where a regular file exists should fail.
    let (_, _, code) = btrfs(&["subvolume", "create", &file]);
    assert_ne!(code, 0, "create over existing file should fail");
}

// ── subvolume create with mixed valid/invalid paths ─────────────────

#[test]
#[ignore = "requires elevated privileges"]
fn subvolume_create_mixed_paths() {
    let (_td, mnt) = single_mount();
    let mp = mnt.path().to_str().unwrap();

    // One invalid path (parent doesn't exist) and two valid paths.
    // The command should fail overall, but the valid subvolumes should
    // still be created.
    let invalid = format!("{mp}/no-such-dir/sub0");
    let valid1 = format!("{mp}/sub1");
    let valid2 = format!("{mp}/sub2");

    let (_, _, code) =
        btrfs(&["subvolume", "create", &invalid, &valid1, &valid2]);
    assert_ne!(code, 0, "should fail due to invalid path");

    // The valid subvolumes should exist despite the overall failure.
    assert!(Path::new(&valid1).is_dir(), "sub1 should have been created");
    assert!(Path::new(&valid2).is_dir(), "sub2 should have been created");
    assert!(
        !Path::new(&invalid).exists(),
        "invalid path should not exist"
    );
}

#[test]
#[ignore = "requires elevated privileges"]
fn subvolume_create_parents_mixed() {
    let (_td, mnt) = single_mount();
    let mp = mnt.path().to_str().unwrap();

    // With -p, all paths should succeed (parents created as needed).
    let deep1 = format!("{mp}/dir1/deep/sub1");
    let deep2 = format!("{mp}/dir2/sub2");
    let flat = format!("{mp}/sub3");

    btrfs_ok(&["subvolume", "create", "-p", &deep1, &deep2, &flat]);

    assert!(Path::new(&deep1).is_dir(), "deep1 should exist");
    assert!(Path::new(&deep2).is_dir(), "deep2 should exist");
    assert!(Path::new(&flat).is_dir(), "flat should exist");

    let out = btrfs_ok(&["subvolume", "list", mp]);
    assert!(
        out.contains("dir1/deep/sub1"),
        "expected deep1 in list:\n{out}"
    );
    assert!(out.contains("dir2/sub2"), "expected deep2 in list:\n{out}");
    assert!(out.contains("sub3"), "expected flat in list:\n{out}");
}

// ── dry-run ─────────────────────────────────────────────────────────

#[test]
#[ignore = "requires elevated privileges"]
fn dry_run_subvolume_delete() {
    let (_td, mnt) = single_mount();
    let mp = mnt.path().to_str().unwrap();

    let subvol = format!("{mp}/dry_target");
    btrfs_ok(&["subvolume", "create", &subvol]);
    assert!(Path::new(&subvol).is_dir());

    // --dry-run should not actually delete.
    btrfs_ok(&["--dry-run", "subvolume", "delete", &subvol]);
    assert!(
        Path::new(&subvol).is_dir(),
        "subvolume should still exist after --dry-run delete"
    );

    // Without --dry-run, it should actually delete.
    btrfs_ok(&["subvolume", "delete", &subvol]);
    assert!(
        !Path::new(&subvol).exists(),
        "subvolume should be gone after real delete"
    );
}

// ── property ─────────────────────────────────────────────────────────

#[test]
#[ignore = "requires elevated privileges"]
fn property_get_set_ro() {
    let (_td, mnt) = single_mount();
    let mp = mnt.path().to_str().unwrap();
    let subvol = format!("{mp}/proptest");

    btrfs_ok(&["subvolume", "create", &subvol]);

    let out = btrfs_ok(&["property", "get", "-t", "subvol", &subvol, "ro"]);
    assert!(out.contains("false"), "expected ro=false:\n{out}");

    btrfs_ok(&["property", "set", "-t", "subvol", &subvol, "ro", "true"]);
    let out = btrfs_ok(&["property", "get", "-t", "subvol", &subvol, "ro"]);
    assert!(out.contains("true"), "expected ro=true:\n{out}");

    // Verify via uapi: RDONLY flag should be set
    let subvol_file = fs::File::open(&subvol).unwrap();
    let flags = subvolume_flags_get(subvol_file.as_fd()).unwrap();
    assert!(flags.contains(SubvolumeFlags::RDONLY));

    btrfs_ok(&["property", "set", "-t", "subvol", &subvol, "ro", "false"]);
    let out = btrfs_ok(&["property", "get", "-t", "subvol", &subvol, "ro"]);
    assert!(out.contains("false"), "expected ro=false:\n{out}");

    // Verify via uapi: RDONLY flag should be cleared
    let flags = subvolume_flags_get(subvol_file.as_fd()).unwrap();
    assert!(!flags.contains(SubvolumeFlags::RDONLY));
}

#[test]
#[ignore = "requires elevated privileges"]
fn property_set_compression() {
    let (_td, mnt) = single_mount();
    let mp = mnt.path().to_str().unwrap();

    let file = format!("{mp}/comptest.txt");
    fs::write(&file, "hello").unwrap();

    // Set compression to zlib
    btrfs_ok(&["property", "set", &file, "compression", "zlib"]);
    let out = btrfs_ok(&["property", "get", &file, "compression"]);
    assert!(out.contains("zlib"), "expected compression=zlib:\n{out}");

    // Set compression to lzo
    btrfs_ok(&["property", "set", &file, "compression", "lzo"]);
    let out = btrfs_ok(&["property", "get", &file, "compression"]);
    assert!(out.contains("lzo"), "expected compression=lzo:\n{out}");

    // Clear compression
    btrfs_ok(&["property", "set", &file, "compression", ""]);
    let out = btrfs_ok(&["property", "get", &file, "compression"]);
    assert!(
        !out.contains("compression="),
        "expected no compression:\n{out}"
    );
}

#[test]
#[ignore = "requires elevated privileges"]
fn property_set_label() {
    let (_td, mnt) = single_mount();
    let mp = mnt.path().to_str().unwrap();

    btrfs_ok(&[
        "property",
        "set",
        "-t",
        "filesystem",
        mp,
        "label",
        "newlabel",
    ]);
    let out = btrfs_ok(&["property", "get", "-t", "filesystem", mp, "label"]);
    assert!(out.contains("newlabel"), "expected label=newlabel:\n{out}");
}

#[test]
#[ignore = "requires elevated privileges"]
fn property_set_ro_invalid_value() {
    let (_td, mnt) = single_mount();
    let mp = mnt.path().to_str().unwrap();
    let subvol = format!("{mp}/badval");

    btrfs_ok(&["subvolume", "create", &subvol]);
    let (_stdout, stderr, code) =
        btrfs(&["property", "set", "-t", "subvol", &subvol, "ro", "yes"]);
    assert_ne!(code, 0, "expected failure for invalid ro value");
    assert!(
        stderr.contains("invalid value"),
        "expected 'invalid value' in stderr:\n{stderr}"
    );
}

#[test]
#[ignore = "requires elevated privileges"]
fn property_wrong_property_for_type() {
    let (_td, mnt) = single_mount();
    let mp = mnt.path().to_str().unwrap();

    let file = format!("{mp}/wrongprop.txt");
    fs::write(&file, "test").unwrap();

    // "ro" is not valid on an inode
    let (_stdout, stderr, code) = btrfs(&["property", "get", &file, "ro"]);
    assert_ne!(code, 0, "expected failure for wrong property type");
    assert!(
        stderr.contains("not applicable"),
        "expected 'not applicable' in stderr:\n{stderr}"
    );
}

#[test]
#[ignore = "requires elevated privileges"]
fn property_ro_no_change_when_already_set() {
    let (_td, mnt) = single_mount();
    let mp = mnt.path().to_str().unwrap();
    let subvol = format!("{mp}/nochange");

    btrfs_ok(&["subvolume", "create", &subvol]);

    // Setting ro=false on an already-rw subvolume should succeed (no-op)
    btrfs_ok(&["property", "set", "-t", "subvol", &subvol, "ro", "false"]);
    let out = btrfs_ok(&["property", "get", "-t", "subvol", &subvol, "ro"]);
    assert!(out.contains("false"), "expected ro=false:\n{out}");
}

// ── receive --chroot ─────────────────────────────────────────────────

#[test]
#[ignore = "requires elevated privileges"]
fn receive_chroot() {
    let (_td1, mnt1) = single_mount();
    let (_td2, mnt2) = single_mount();
    let mp1 = mnt1.path().to_str().unwrap();
    let mp2 = mnt2.path().to_str().unwrap();
    let stream_file = format!("{}/chroot.bin", _td1.path().to_str().unwrap());

    // Create and send a subvolume.
    let src = format!("{mp1}/chroot_test");
    btrfs_ok(&["subvolume", "create", &src]);
    write_test_data(Path::new(&src), "data.bin", 8192);
    btrfs_ok(&["property", "set", "-t", "subvol", &src, "ro", "true"]);
    btrfs_ok(&["send", "-f", &stream_file, &src]);

    // Receive with --chroot. The -f path is opened before chroot, so
    // it uses the real filesystem path.
    btrfs_ok(&["receive", "-C", "-f", &stream_file, mp2]);

    // Verify the received subvolume.
    let received = format!("{mp2}/chroot_test");
    assert!(Path::new(&received).is_dir(), "received subvol not found");
    verify_test_data(Path::new(&received), "data.bin", 8192);
}

// ── property force clear received_uuid ───────────────────────────────

#[test]
#[ignore = "requires elevated privileges"]
fn property_force_clear_received_uuid() {
    let (_td1, mnt1) = single_mount();
    let (_td2, mnt2) = single_mount();
    let mp1 = mnt1.path().to_str().unwrap();
    let mp2 = mnt2.path().to_str().unwrap();
    let stream_file = format!("{}/force.bin", _td1.path().to_str().unwrap());

    // Create a subvolume, send it, and receive it.
    let src = format!("{mp1}/src");
    btrfs_ok(&["subvolume", "create", &src]);
    write_test_data(Path::new(&src), "file.bin", 4096);
    btrfs_ok(&["property", "set", "-t", "subvol", &src, "ro", "true"]);
    btrfs_ok(&["send", "-f", &stream_file, &src]);
    btrfs_ok(&["receive", "-f", &stream_file, mp2]);

    // The received subvolume should be read-only with a received_uuid.
    let received = format!("{mp2}/src");
    let out = btrfs_ok(&["subvolume", "show", &received]);
    assert!(
        out.contains("Received UUID:"),
        "expected Received UUID field:\n{out}"
    );
    // The received UUID should not be "-" (nil).
    assert!(
        !out.lines()
            .any(|l| l.contains("Received UUID:") && l.contains("-\n")),
        "expected non-nil received UUID"
    );

    // Without -f, flipping ro→rw should fail.
    let (_, stderr, code) =
        btrfs(&["property", "set", "-t", "subvol", &received, "ro", "false"]);
    assert_ne!(code, 0, "expected failure without -f");
    assert!(
        stderr.contains("received_uuid"),
        "expected received_uuid error:\n{stderr}"
    );

    // With -f, it should succeed and clear the received_uuid.
    btrfs_ok(&[
        "property", "set", "-t", "subvol", "-f", &received, "ro", "false",
    ]);

    // Verify: subvolume is now writable.
    let out = btrfs_ok(&["property", "get", "-t", "subvol", &received, "ro"]);
    assert!(out.contains("false"), "expected ro=false:\n{out}");

    // Verify: received_uuid is now nil.
    let out = btrfs_ok(&["subvolume", "show", &received]);
    let recv_line = out.lines().find(|l| l.contains("Received UUID:")).unwrap();
    assert!(
        recv_line.contains("\t-") || recv_line.contains(" -"),
        "expected nil received UUID after force, got: {recv_line}"
    );
}

// ── send / receive ───────────────────────────────────────────────────

#[test]
#[ignore = "requires elevated privileges"]
fn send_receive_dump() {
    let (_td, mnt) = common::deterministic_mount();
    let mp = mnt.path().to_str().unwrap();
    let subvol = format!("{mp}/dumptest");
    let stream_file = format!("{}/dump.bin", _td.path().to_str().unwrap());

    btrfs_ok(&["subvolume", "create", &subvol]);
    write_test_data(Path::new(&subvol), "file.bin", 4096);
    btrfs_ok(&["property", "set", "-t", "subvol", &subvol, "ro", "true"]);
    btrfs_ok(&["send", "-f", &stream_file, &subvol]);

    let out = btrfs_ok(&["receive", "--dump", "-f", &stream_file]);

    let re_uuid = Regex::new(
        r"[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}",
    )
    .unwrap();
    let re_offset = Regex::new(r"offset=\d+").unwrap();
    let re_len = Regex::new(r"len=\d+").unwrap();
    let re_mode = Regex::new(r"mode=\d+").unwrap();
    let re_uid = Regex::new(r"uid=\d+").unwrap();
    let re_gid = Regex::new(r"gid=\d+").unwrap();

    let mut redacted = redact(&out, &mnt);
    redacted = re_uuid.replace_all(&redacted, "<UUID>").into_owned();
    redacted = re_offset.replace_all(&redacted, "offset=<N>").into_owned();
    redacted = re_len.replace_all(&redacted, "len=<N>").into_owned();
    redacted = re_mode.replace_all(&redacted, "mode=<N>").into_owned();
    redacted = re_uid.replace_all(&redacted, "uid=<N>").into_owned();
    redacted = re_gid.replace_all(&redacted, "gid=<N>").into_owned();
    snap!("btrfs receive --dump -f <STREAM>", redacted);
}

#[test]
#[ignore = "requires elevated privileges"]
fn send_receive_roundtrip() {
    let (_td1, mnt1) = single_mount();
    let (_td2, mnt2) = single_mount();
    let mp1 = mnt1.path().to_str().unwrap();
    let mp2 = mnt2.path().to_str().unwrap();
    let stream_file =
        format!("{}/roundtrip.bin", _td1.path().to_str().unwrap());

    let src = format!("{mp1}/origin");
    btrfs_ok(&["subvolume", "create", &src]);

    write_test_data(Path::new(&src), "file1.bin", 65536);
    write_test_data(Path::new(&src), "file2.bin", 1024);
    fs::create_dir(format!("{src}/dir")).unwrap();
    write_test_data(Path::new(&format!("{src}/dir")), "file3.bin", 32768);

    btrfs_ok(&["property", "set", "-t", "subvol", &src, "ro", "true"]);
    btrfs_ok(&["send", "-f", &stream_file, &src]);

    btrfs_ok(&["receive", "-f", &stream_file, mp2]);

    let received = format!("{mp2}/origin");
    assert!(Path::new(&received).is_dir(), "received subvol not found");

    verify_test_data(Path::new(&received), "file1.bin", 65536);
    verify_test_data(Path::new(&received), "file2.bin", 1024);
    verify_test_data(Path::new(&format!("{received}/dir")), "file3.bin", 32768);
}

#[test]
#[ignore = "requires elevated privileges"]
fn send_receive_incremental() {
    let (_td1, mnt1) = single_mount();
    let (_td2, mnt2) = single_mount();
    let mp1 = mnt1.path().to_str().unwrap();
    let mp2 = mnt2.path().to_str().unwrap();
    let base_stream = format!("{}/base.bin", _td1.path().to_str().unwrap());
    let incr_stream = format!("{}/incr.bin", _td1.path().to_str().unwrap());

    // Create a subvolume with initial content.
    let src = format!("{mp1}/data");
    btrfs_ok(&["subvolume", "create", &src]);
    write_test_data(Path::new(&src), "unchanged.bin", 8192);
    write_test_data(Path::new(&src), "modified.bin", 4096);
    write_test_data(Path::new(&src), "deleted.bin", 2048);
    fs::create_dir(format!("{src}/subdir")).unwrap();
    write_test_data(Path::new(&format!("{src}/subdir")), "nested.bin", 1024);

    // Take a read-only snapshot as the base.
    let base_snap = format!("{mp1}/snap_base");
    btrfs_ok(&["subvolume", "snapshot", "-r", &src, &base_snap]);

    // Modify the subvolume: add, change, and delete files.
    write_test_data(Path::new(&src), "added.bin", 16384);
    // Overwrite modified.bin with different size.
    write_test_data(Path::new(&src), "modified.bin", 32768);
    fs::remove_file(format!("{src}/deleted.bin")).unwrap();
    fs::create_dir(format!("{src}/newdir")).unwrap();
    write_test_data(Path::new(&format!("{src}/newdir")), "fresh.bin", 4096);

    // Take a second read-only snapshot.
    let incr_snap = format!("{mp1}/snap_incr");
    btrfs_ok(&["subvolume", "snapshot", "-r", &src, &incr_snap]);

    // Full send the base snapshot to the second mount.
    btrfs_ok(&["send", "-f", &base_stream, &base_snap]);
    btrfs_ok(&["receive", "-f", &base_stream, mp2]);

    // Verify the base was received correctly.
    let recv_base = format!("{mp2}/snap_base");
    verify_test_data(Path::new(&recv_base), "unchanged.bin", 8192);
    verify_test_data(Path::new(&recv_base), "modified.bin", 4096);
    verify_test_data(Path::new(&recv_base), "deleted.bin", 2048);
    verify_test_data(
        Path::new(&format!("{recv_base}/subdir")),
        "nested.bin",
        1024,
    );

    // Incremental send: only the changes since base.
    btrfs_ok(&["send", "-p", &base_snap, "-f", &incr_stream, &incr_snap]);

    // The incremental stream should be non-empty.
    let incr_size = fs::metadata(&incr_stream).unwrap().len();
    assert!(incr_size > 0, "incremental stream is empty");

    // Receive the incremental stream.
    btrfs_ok(&["receive", "-f", &incr_stream, mp2]);

    // Verify the incremental snapshot has the correct final state.
    let recv_incr = format!("{mp2}/snap_incr");
    assert!(
        Path::new(&recv_incr).is_dir(),
        "incremental snapshot not found"
    );

    // Unchanged file should be intact.
    verify_test_data(Path::new(&recv_incr), "unchanged.bin", 8192);

    // Modified file should have the new content and size.
    verify_test_data(Path::new(&recv_incr), "modified.bin", 32768);

    // Deleted file should be gone.
    assert!(
        !Path::new(&format!("{recv_incr}/deleted.bin")).exists(),
        "deleted.bin should not exist in incremental snapshot"
    );

    // Added file should be present.
    verify_test_data(Path::new(&recv_incr), "added.bin", 16384);

    // Original nested file should still be there.
    verify_test_data(
        Path::new(&format!("{recv_incr}/subdir")),
        "nested.bin",
        1024,
    );

    // New directory and file should be present.
    verify_test_data(
        Path::new(&format!("{recv_incr}/newdir")),
        "fresh.bin",
        4096,
    );
}

#[test]
#[ignore = "requires elevated privileges"]
fn send_receive_v2_compressed() {
    // Source: mount with zstd compression so writes produce compressed extents.
    let td1 = tempdir().unwrap();
    let file1 = BackingFile::new(td1.path(), "disk.img", 512_000_000);
    file1.mkfs();
    let lo1 = LoopbackDevice::new(file1);
    let mnt1 = common::Mount::with_options(lo1, td1.path(), &["compress=zstd"]);
    let mp1 = mnt1.path().to_str().unwrap();

    // Destination: plain mount (no compression).
    let (_td2, mnt2) = single_mount();
    let mp2 = mnt2.path().to_str().unwrap();

    let stream_file = format!("{}/v2.bin", td1.path().to_str().unwrap());

    // Create a subvolume and write compressible data. The compress mount
    // option ensures the kernel stores these extents compressed on disk.
    let src = format!("{mp1}/v2test");
    btrfs_ok(&["subvolume", "create", &src]);
    common::write_compressible_data(Path::new(&src), "zeros.bin", 256 * 1024);
    write_test_data(Path::new(&src), "pattern.bin", 64 * 1024);
    btrfs_ok(&["filesystem", "sync", mp1]);

    // Make read-only and send with --compressed-data (forces v2 protocol).
    btrfs_ok(&["property", "set", "-t", "subvol", &src, "ro", "true"]);
    btrfs_ok(&["send", "--compressed-data", "-f", &stream_file, &src]);

    // Verify the stream contains encoded_write commands via --dump.
    let dump = btrfs_ok(&["receive", "--dump", "-f", &stream_file]);
    assert!(
        dump.contains("encoded_write"),
        "expected encoded_write in v2 stream dump:\n{dump}"
    );

    // Receive on the second mount.
    btrfs_ok(&["receive", "-f", &stream_file, mp2]);

    // Verify data integrity.
    let received = format!("{mp2}/v2test");
    assert!(Path::new(&received).is_dir(), "received subvol not found");

    // zeros.bin: 256KB of all zeros.
    let zeros = fs::read(format!("{received}/zeros.bin")).unwrap();
    assert_eq!(zeros.len(), 256 * 1024);
    assert!(
        zeros.iter().all(|&b| b == 0),
        "zeros.bin contains non-zero data"
    );

    // pattern.bin: deterministic test data.
    verify_test_data(Path::new(&received), "pattern.bin", 64 * 1024);
}

// ── send with parent and multiple subvolumes ────────────────────────

#[test]
#[ignore = "requires elevated privileges"]
fn send_parent_multi_subvol() {
    let (_td, mnt) = single_mount();
    let mp = mnt.path().to_str().unwrap();
    let stream = format!("{}/multi.bin", _td.path().to_str().unwrap());

    // Create a parent subvolume with data that changes between snapshots.
    let parent = format!("{mp}/parent");
    btrfs_ok(&["subvolume", "create", &parent]);
    write_test_data(Path::new(&parent), "base.bin", 8192);

    let snap1 = format!("{mp}/snap1");
    btrfs_ok(&["subvolume", "snapshot", "-r", &parent, &snap1]);

    write_test_data(Path::new(&parent), "added1.bin", 4096);
    let snap2 = format!("{mp}/snap2");
    btrfs_ok(&["subvolume", "snapshot", "-r", &parent, &snap2]);

    write_test_data(Path::new(&parent), "added2.bin", 4096);
    let snap3 = format!("{mp}/snap3");
    btrfs_ok(&["subvolume", "snapshot", "-r", &parent, &snap3]);

    // Send snap2 and snap3 incrementally using snap1 as the parent.
    btrfs_ok(&["send", "-f", &stream, "-p", &snap1, &snap2, &snap3]);

    // Receive on a second mount.
    let (_td2, mnt2) = single_mount();
    let mp2 = mnt2.path().to_str().unwrap();

    // Must receive the parent snapshot first.
    let base_stream = format!("{}/base.bin", _td.path().to_str().unwrap());
    btrfs_ok(&["send", "-f", &base_stream, &snap1]);
    btrfs_ok(&["receive", "-f", &base_stream, mp2]);

    // Then receive the incremental stream with both snap2 and snap3.
    btrfs_ok(&["receive", "-f", &stream, mp2]);

    // Verify received subvolumes exist and have the right content.
    verify_test_data(Path::new(&format!("{mp2}/snap2")), "base.bin", 8192);
    verify_test_data(Path::new(&format!("{mp2}/snap2")), "added1.bin", 4096);
    verify_test_data(Path::new(&format!("{mp2}/snap3")), "base.bin", 8192);
    verify_test_data(Path::new(&format!("{mp2}/snap3")), "added2.bin", 4096);
}

// ── scrub ────────────────────────────────────────────────────────────

#[test]
#[ignore = "requires elevated privileges"]
fn scrub_start_status() {
    let (_td, mnt) = single_mount();
    let mp = mnt.path().to_str().unwrap();

    btrfs_ok(&["scrub", "start", mp]);

    let (out, _, code) = btrfs(&["scrub", "status", mp]);
    assert_eq!(code, 0);
    assert!(
        out.contains("scrub") || out.contains("UUID"),
        "expected scrub status output:\n{out}"
    );
}

// ── device ───────────────────────────────────────────────────────────

#[test]
#[ignore = "requires elevated privileges"]
fn device_add_remove() {
    let (_td, mnt) = single_mount();
    let mp = mnt.path().to_str().unwrap();

    let dev2_file = BackingFile::new(_td.path(), "disk2.img", 512_000_000);
    let dev2 = LoopbackDevice::new(dev2_file);
    let dev2_path = dev2.path().to_str().unwrap();

    btrfs_ok(&["device", "add", dev2_path, mp]);

    let out = btrfs_ok(&["filesystem", "show", mp]);
    assert!(
        out.contains(dev2_path),
        "expected new device in show output:\n{out}"
    );

    // Verify via uapi: should have 2 devices
    let fs_info = filesystem_info(mnt.fd()).unwrap();
    assert_eq!(fs_info.num_devices, 2, "expected 2 devices after add");

    btrfs_ok(&["device", "remove", dev2_path, mp]);

    let out = btrfs_ok(&["filesystem", "show", mp]);
    assert!(!out.contains(dev2_path), "device should be removed:\n{out}");

    // Verify via uapi: should be back to 1 device
    let fs_info = filesystem_info(mnt.fd()).unwrap();
    assert_eq!(fs_info.num_devices, 1, "expected 1 device after remove");
}

#[test]
#[ignore = "requires elevated privileges"]
fn device_add_force() {
    let (_td, mnt) = single_mount();
    let mp = mnt.path().to_str().unwrap();

    // Create a second device and format it as btrfs so it has a superblock.
    let dev2_file = BackingFile::new(_td.path(), "disk2.img", 512_000_000);
    let dev2 = LoopbackDevice::new(dev2_file);
    let dev2_path = dev2.path().to_str().unwrap();

    Command::new("mkfs.btrfs")
        .args(["-f", dev2_path])
        .output()
        .expect("mkfs.btrfs failed");

    // Without --force, adding a device with an existing btrfs superblock should fail.
    let (_stdout, stderr, code) = btrfs(&["device", "add", dev2_path, mp]);
    assert_ne!(code, 0, "expected failure without --force:\n{stderr}");
    assert!(
        stderr.contains("already contains a btrfs filesystem"),
        "expected btrfs superblock error:\n{stderr}"
    );

    // With --force, it should succeed.
    btrfs_ok(&["device", "add", "-f", dev2_path, mp]);

    let out = btrfs_ok(&["filesystem", "show", mp]);
    assert!(
        out.contains(dev2_path),
        "expected new device in show output:\n{out}"
    );

    // Verify via uapi: should have 2 devices.
    let fs_info = filesystem_info(mnt.fd()).unwrap();
    assert_eq!(fs_info.num_devices, 2, "expected 2 devices after force add");
}

#[test]
#[ignore = "requires elevated privileges"]
fn device_add_nodiscard() {
    let (_td, mnt) = single_mount();
    let mp = mnt.path().to_str().unwrap();

    let dev2_file = BackingFile::new(_td.path(), "disk2.img", 512_000_000);
    let dev2 = LoopbackDevice::new(dev2_file);
    let dev2_path = dev2.path().to_str().unwrap();

    // -K should skip TRIM and still add the device successfully.
    btrfs_ok(&["device", "add", "-K", dev2_path, mp]);

    let out = btrfs_ok(&["filesystem", "show", mp]);
    assert!(
        out.contains(dev2_path),
        "expected new device in show output:\n{out}"
    );

    // Verify via uapi.
    let fs_info = filesystem_info(mnt.fd()).unwrap();
    assert_eq!(
        fs_info.num_devices, 2,
        "expected 2 devices after nodiscard add"
    );
}

#[test]
#[ignore = "requires elevated privileges"]
fn device_add_enqueue() {
    let (_td, mnt) = single_mount();
    let mp = mnt.path().to_str().unwrap();

    let dev2_file = BackingFile::new(_td.path(), "disk2.img", 512_000_000);
    let dev2 = LoopbackDevice::new(dev2_file);
    let dev2_path = dev2.path().to_str().unwrap();

    // --enqueue should work even when no exclusive operation is running.
    btrfs_ok(&["device", "add", "--enqueue", dev2_path, mp]);

    let out = btrfs_ok(&["filesystem", "show", mp]);
    assert!(
        out.contains(dev2_path),
        "expected new device in show output:\n{out}"
    );

    // Verify via uapi.
    let fs_info = filesystem_info(mnt.fd()).unwrap();
    assert_eq!(
        fs_info.num_devices, 2,
        "expected 2 devices after enqueue add"
    );
}

// ── device scan / ready ──────────────────────────────────────────────

#[test]
#[ignore = "requires elevated privileges"]
fn device_scan() {
    let (_td, mnt) = single_mount();
    let dev = mnt.loopback().path().to_str().unwrap();

    let out = btrfs_ok(&["device", "scan", dev]);
    assert!(
        out.contains("registered"),
        "expected registered message:\n{out}"
    );
}

#[test]
#[ignore = "requires elevated privileges"]
fn device_ready() {
    let (_td, mnt) = single_mount();
    let dev = mnt.loopback().path().to_str().unwrap();

    let out = btrfs_ok(&["device", "ready", dev]);
    assert!(out.contains("ready"), "expected ready message:\n{out}");
}

// ── balance ──────────────────────────────────────────────────────────

#[test]
#[ignore = "requires elevated privileges"]
fn balance_start_status() {
    let (_td, mnt) = single_mount();
    let mp = mnt.path().to_str().unwrap();

    btrfs_ok(&["balance", "start", "--full-balance", mp]);

    let (stdout, stderr, _) = btrfs(&["balance", "status", mp]);
    let combined = format!("{stdout}{stderr}");
    assert!(
        combined.contains("balance") || combined.contains("No"),
        "unexpected status output:\n{combined}"
    );
}

#[test]
#[ignore = "requires elevated privileges"]
fn balance_cancel_not_running() {
    let (_td, mnt) = single_mount();
    let mp = mnt.path().to_str().unwrap();

    // Cancel when nothing is running should fail gracefully.
    let (_, stderr, code) = btrfs(&["balance", "cancel", mp]);
    assert_ne!(code, 0);
    assert!(
        stderr.contains("Not in progress") || stderr.contains("balance"),
        "expected not-in-progress error:\n{stderr}"
    );
}

#[test]
#[ignore = "requires elevated privileges"]
fn balance_pause_not_running() {
    let (_td, mnt) = single_mount();
    let mp = mnt.path().to_str().unwrap();

    let (_, stderr, code) = btrfs(&["balance", "pause", mp]);
    assert_ne!(code, 0);
    assert!(
        stderr.contains("Not in progress") || stderr.contains("balance"),
        "expected not-in-progress error:\n{stderr}"
    );
}

// ── balance without filters ──────────────────────────────────────────

#[test]
#[ignore = "requires elevated privileges"]
fn balance_without_filters_warns() {
    let (_td, mnt) = single_mount();
    let mp = mnt.path().to_str().unwrap();

    // Balance start without --full-balance and without filters should
    // warn the user about a full balance. On a small filesystem it
    // completes immediately, but the warning should still appear.
    let (stdout, stderr, _code) = btrfs(&["balance", "start", mp]);
    let combined = format!("{stdout}{stderr}");
    assert!(
        combined.contains("Full balance")
            || combined.contains("full balance")
            || combined.contains("without filters"),
        "expected full-balance warning:\n{combined}"
    );
}

#[test]
#[ignore = "requires elevated privileges"]
fn balance_full_balance_flag() {
    let (_td, mnt) = single_mount();
    let mp = mnt.path().to_str().unwrap();

    // --full-balance should succeed without a warning.
    btrfs_ok(&["balance", "start", "--full-balance", mp]);
}

// ── inspect-internal ─────────────────────────────────────────────────

#[test]
#[ignore = "requires elevated privileges"]
fn inspect_rootid() {
    let (_td, mnt) = single_mount();
    let mp = mnt.path().to_str().unwrap();
    let out = btrfs_ok(&["inspect-internal", "rootid", mp]);
    assert!(out.trim() == "5", "expected rootid 5, got: {out}");
}

#[test]
#[ignore = "requires elevated privileges"]
fn inspect_dump_super() {
    let (_td, mnt) = single_mount();
    let dev = mnt.loopback().path().to_str().unwrap();
    let out = btrfs_ok(&["inspect-internal", "dump-super", dev]);
    assert!(out.contains("magic"), "expected magic field:\n{out}");
    assert!(out.contains("[match]"), "expected magic match:\n{out}");
    assert!(out.contains("nodesize"), "expected nodesize:\n{out}");
}

// ── quota / qgroup ───────────────────────────────────────────────────

#[test]
#[ignore = "requires elevated privileges"]
fn quota_enable_disable() {
    let (_td, mnt) = single_mount();
    let mp = mnt.path().to_str().unwrap();

    btrfs_ok(&["quota", "enable", mp]);

    let out = btrfs_ok(&["quota", "status", mp]);
    assert!(
        out.contains("enabled") || out.contains("Quota"),
        "expected enabled status:\n{out}"
    );

    // Verify via uapi/sysfs
    let fs_info = filesystem_info(mnt.fd()).unwrap();
    let sysfs = btrfs_uapi::sysfs::SysfsBtrfs::new(&fs_info.uuid);
    let status = sysfs.quota_status().unwrap();
    assert!(status.enabled, "quota should be enabled via sysfs");

    btrfs_ok(&["quota", "disable", mp]);

    // Verify disabled via uapi/sysfs
    let status = sysfs.quota_status().unwrap();
    assert!(!status.enabled, "quota should be disabled via sysfs");
}

#[test]
#[ignore = "requires elevated privileges"]
fn qgroup_show() {
    let (_td, mnt) = single_mount();
    let mp = mnt.path().to_str().unwrap();

    btrfs_ok(&["quota", "enable", mp]);
    btrfs_ok(&["subvolume", "create", &format!("{mp}/sub1")]);
    write_test_data(Path::new(&format!("{mp}/sub1")), "data.bin", 65536);
    btrfs_ok(&["filesystem", "sync", mp]);

    let out = btrfs_ok(&["qgroup", "show", mp]);
    assert!(out.contains("qgroupid"), "expected header:\n{out}");
    assert!(out.contains("rfer"), "expected rfer column:\n{out}");
    assert!(out.contains("excl"), "expected excl column:\n{out}");
    assert!(
        out.contains("0/"),
        "expected level-0 qgroup entries:\n{out}"
    );

    btrfs_ok(&["quota", "disable", mp]);
}

#[test]
#[ignore = "requires elevated privileges"]
fn qgroup_show_with_columns() {
    let (_td, mnt) = single_mount();
    let mp = mnt.path().to_str().unwrap();

    btrfs_ok(&["quota", "enable", mp]);

    let out = btrfs_ok(&["qgroup", "show", "-pcre", mp]);
    assert!(out.contains("max_rfer"), "expected max_rfer column:\n{out}");
    assert!(out.contains("max_excl"), "expected max_excl column:\n{out}");
    assert!(out.contains("parent"), "expected parent column:\n{out}");
    assert!(out.contains("child"), "expected child column:\n{out}");

    btrfs_ok(&["quota", "disable", mp]);
}

#[test]
#[ignore = "requires elevated privileges"]
fn qgroup_create_destroy() {
    let (_td, mnt) = single_mount();
    let mp = mnt.path().to_str().unwrap();

    btrfs_ok(&["quota", "enable", mp]);
    btrfs_ok(&["qgroup", "create", "1/100", mp]);

    let out = btrfs_ok(&["qgroup", "show", mp]);
    assert!(out.contains("1/100"), "expected created qgroup:\n{out}");

    btrfs_ok(&["qgroup", "destroy", "1/100", mp]);
    btrfs_ok(&["quota", "disable", mp]);
}

#[test]
#[ignore = "requires elevated privileges"]
fn qgroup_assign_remove() {
    let (_td, mnt) = single_mount();
    let mp = mnt.path().to_str().unwrap();

    btrfs_ok(&["quota", "enable", mp]);
    btrfs_ok(&["subvolume", "create", &format!("{mp}/sub1")]);
    btrfs_ok(&["qgroup", "create", "1/100", mp]);

    // Assign the level-0 qgroup for sub1 to the level-1 group.
    // sub1 is the first subvolume, so its qgroup is 0/256.
    btrfs_ok(&["qgroup", "assign", "--no-rescan", "0/256", "1/100", mp]);

    let out = btrfs_ok(&["qgroup", "show", "-pc", mp]);
    assert!(
        out.contains("1/100"),
        "expected parent group in show:\n{out}"
    );

    // Remove the assignment.
    btrfs_ok(&["qgroup", "remove", "--no-rescan", "0/256", "1/100", mp]);

    btrfs_ok(&["qgroup", "destroy", "1/100", mp]);
    btrfs_ok(&["quota", "disable", mp]);
}

#[test]
#[ignore = "requires elevated privileges"]
fn qgroup_limit() {
    let (_td, mnt) = single_mount();
    let mp = mnt.path().to_str().unwrap();

    btrfs_ok(&["quota", "enable", mp]);

    // Set a referenced limit on the top-level qgroup.
    btrfs_ok(&["qgroup", "limit", "1G", "0/5", mp]);

    let out = btrfs_ok(&["qgroup", "show", "-re", mp]);
    assert!(out.contains("0/5"), "expected qgroup entry:\n{out}");

    // Verify via uapi: qgroup 0/5 should have a max_rfer limit
    let qlist = btrfs_uapi::quota::qgroup_list(mnt.fd()).unwrap();
    let qg = qlist.qgroups.iter().find(|g| g.qgroupid == 5).unwrap();
    assert!(
        qg.max_rfer > 0 && qg.max_rfer != u64::MAX,
        "expected max_rfer limit to be set, got {}",
        qg.max_rfer
    );

    // Remove the limit.
    btrfs_ok(&["qgroup", "limit", "none", "0/5", mp]);

    btrfs_ok(&["quota", "disable", mp]);
}

// ── subvolume show with qgroup limits ────────────────────────────────

#[test]
#[ignore = "requires elevated privileges"]
fn subvolume_show_qgroup_limit() {
    let (_td, mnt) = single_mount();
    let mp = mnt.path().to_str().unwrap();

    // Create a subvolume before quotas are enabled.
    let subv_no_quota = format!("{mp}/no_quota");
    btrfs_ok(&["subvolume", "create", &subv_no_quota]);

    // subvolume show should work without quotas.
    btrfs_ok(&["subvolume", "show", &subv_no_quota]);

    // Enable quotas.
    btrfs_ok(&["quota", "enable", mp]);

    // Create a subvolume with quotas active (auto-creates qgroup).
    let subv_with_limit = format!("{mp}/with_limit");
    btrfs_ok(&["subvolume", "create", &subv_with_limit]);

    // Get the rootid and set an exclusive limit on it.
    let rootid_out =
        btrfs_ok(&["inspect-internal", "rootid", &subv_with_limit]);
    let rootid = rootid_out.trim();
    btrfs_ok(&["qgroup", "limit", "-e", "1G", &format!("0/{rootid}"), mp]);

    // subvolume show should succeed for both subvolumes even with
    // quotas and limits active.
    btrfs_ok(&["subvolume", "show", &subv_no_quota]);
    btrfs_ok(&["subvolume", "show", &subv_with_limit]);

    // Verify the qgroup limit is visible via qgroup show.
    let out = btrfs_ok(&["qgroup", "show", "-re", mp]);
    assert!(
        out.contains(&format!("0/{rootid}")),
        "expected qgroup entry for subvol:\n{out}"
    );

    btrfs_ok(&["quota", "disable", mp]);
}

// ── quota rescan ─────────────────────────────────────────────────────

#[test]
#[ignore = "requires elevated privileges"]
fn quota_rescan() {
    let (_td, mnt) = single_mount();
    let mp = mnt.path().to_str().unwrap();

    btrfs_ok(&["quota", "enable", mp]);

    // Start a rescan and wait for completion.
    btrfs_ok(&["quota", "rescan", "-w", mp]);

    // Query rescan status — should report no rescan in progress.
    let out = btrfs_ok(&["quota", "rescan", "-s", mp]);
    assert!(
        out.contains("rescan") || out.contains("quota"),
        "expected rescan status:\n{out}"
    );

    btrfs_ok(&["quota", "disable", mp]);
}

// ── scrub limit / resume ─────────────────────────────────────────────

#[test]
#[ignore = "requires elevated privileges"]
fn scrub_limit() {
    let (_td, mnt) = single_mount();
    let mp = mnt.path().to_str().unwrap();

    // Read the current limit (should show a table).
    let out = btrfs_ok(&["scrub", "limit", mp]);
    assert!(
        out.contains("devid") || out.contains("limit"),
        "expected limit table:\n{out}"
    );

    // Set a limit on all devices.
    btrfs_ok(&["scrub", "limit", "-a", "-l", "100m", mp]);

    // Read it back.
    let out = btrfs_ok(&["scrub", "limit", mp]);
    assert!(
        out.contains("100") || out.contains("104857600"),
        "expected limit value in output:\n{out}"
    );

    // Clear the limit (set to 0 = unlimited).
    btrfs_ok(&["scrub", "limit", "-a", "-l", "0", mp]);
}

#[test]
#[ignore = "requires elevated privileges"]
fn scrub_resume_no_scrub() {
    let (_td, mnt) = single_mount();
    let mp = mnt.path().to_str().unwrap();

    // Resume when no scrub has been started — may succeed (starts a new
    // scrub) or fail gracefully depending on kernel state. Either way it
    // should not crash.
    let (_, _, code) = btrfs(&["scrub", "resume", mp]);
    assert!(code == 0 || code == 1, "unexpected exit code: {code}");
}

// ── balance resume ───────────────────────────────────────────────────

#[test]
#[ignore = "requires elevated privileges"]
fn balance_resume_not_running() {
    let (_td, mnt) = single_mount();
    let mp = mnt.path().to_str().unwrap();

    let (_, stderr, code) = btrfs(&["balance", "resume", mp]);
    assert_ne!(code, 0);
    assert!(
        stderr.contains("Not in progress") || stderr.contains("balance"),
        "expected not-in-progress error:\n{stderr}"
    );
}

// ── replace status (never started) ──────────────────────────────────

#[test]
#[ignore = "requires elevated privileges"]
fn replace_status_never_started() {
    let (_td, mnt) = single_mount();
    let mp = mnt.path().to_str().unwrap();

    let out = btrfs_ok(&["replace", "status", mp]);
    assert!(
        out.contains("no device replace")
            || out.contains("Never")
            || out.contains("started"),
        "expected never-started status:\n{out}"
    );
}

// ── device scan --forget ─────────────────────────────────────────────

#[test]
#[ignore = "requires elevated privileges"]
fn device_scan_forget_stale() {
    let (_td, _mnt) = single_mount();

    // Forget all stale (unmounted) devices. On a test system this may or
    // may not find anything to forget, but the command should succeed.
    let out = btrfs_ok(&["device", "scan", "--forget"]);
    assert!(
        out.contains("unregistered"),
        "expected unregistered message:\n{out}"
    );
}

// ── subvolume create/delete with multiple paths ──────────────────────

#[test]
#[ignore = "requires elevated privileges"]
fn subvolume_create_multiple() {
    let (_td, mnt) = single_mount();
    let mp = mnt.path().to_str().unwrap();

    btrfs_ok(&[
        "subvolume",
        "create",
        &format!("{mp}/multi1"),
        &format!("{mp}/multi2"),
        &format!("{mp}/multi3"),
    ]);

    assert!(Path::new(&format!("{mp}/multi1")).is_dir());
    assert!(Path::new(&format!("{mp}/multi2")).is_dir());
    assert!(Path::new(&format!("{mp}/multi3")).is_dir());

    let out = btrfs_ok(&["subvolume", "list", mp]);
    assert!(out.contains("multi1"), "expected multi1:\n{out}");
    assert!(out.contains("multi2"), "expected multi2:\n{out}");
    assert!(out.contains("multi3"), "expected multi3:\n{out}");
}

// ── subvolume delete flags ───────────────────────────────────────────

#[test]
#[ignore = "requires elevated privileges"]
fn subvolume_delete_commit_after() {
    let (_td, mnt) = single_mount();
    let mp = mnt.path().to_str().unwrap();
    let subvol = format!("{mp}/commitvol");

    btrfs_ok(&["subvolume", "create", &subvol]);
    btrfs_ok(&["subvolume", "delete", "-c", &subvol]);
    assert!(!Path::new(&subvol).exists());
}

#[test]
#[ignore = "requires elevated privileges"]
fn subvolume_delete_commit_each() {
    let (_td, mnt) = single_mount();
    let mp = mnt.path().to_str().unwrap();

    btrfs_ok(&["subvolume", "create", &format!("{mp}/each1")]);
    btrfs_ok(&["subvolume", "create", &format!("{mp}/each2")]);

    btrfs_ok(&[
        "subvolume",
        "delete",
        "-C",
        &format!("{mp}/each1"),
        &format!("{mp}/each2"),
    ]);
    assert!(!Path::new(&format!("{mp}/each1")).exists());
    assert!(!Path::new(&format!("{mp}/each2")).exists());

    // Verify via uapi: no user subvolumes should remain.
    let list = subvolume::subvolume_list(mnt.fd()).unwrap();
    assert!(
        list.is_empty(),
        "expected no subvolumes after delete, got {}",
        list.len()
    );
}

#[test]
#[ignore = "requires elevated privileges"]
fn subvolume_delete_by_subvolid() {
    let (_td, mnt) = single_mount();
    let mp = mnt.path().to_str().unwrap();
    let subvol = format!("{mp}/idvol");

    btrfs_ok(&["subvolume", "create", &subvol]);

    // Get the subvolume ID from `subvolume show`.
    let out = btrfs_ok(&["subvolume", "show", &subvol]);
    let id = out
        .lines()
        .find(|l| l.trim().starts_with("Subvolume ID:"))
        .expect("expected Subvolume ID line")
        .split(':')
        .nth(1)
        .unwrap()
        .trim();

    btrfs_ok(&["subvolume", "delete", "-i", id, mp]);
    assert!(!Path::new(&subvol).exists());
}

#[test]
#[ignore = "requires elevated privileges"]
fn subvolume_delete_recursive() {
    let (_td, mnt) = single_mount();
    let mp = mnt.path().to_str().unwrap();
    let parent = format!("{mp}/parent");
    let child = format!("{parent}/child");
    let grandchild = format!("{child}/grandchild");

    btrfs_ok(&["subvolume", "create", &parent]);
    btrfs_ok(&["subvolume", "create", &child]);
    btrfs_ok(&["subvolume", "create", &grandchild]);

    // Without --recursive, deleting parent should fail (has nested subvols).
    let (_stdout, _stderr, code) = btrfs(&["subvolume", "delete", &parent]);
    assert_ne!(code, 0, "expected failure without --recursive");

    // With --recursive, it should succeed.
    btrfs_ok(&["subvolume", "delete", "-R", &parent]);
    assert!(!Path::new(&parent).exists());
}

#[test]
#[ignore = "requires elevated privileges"]
fn subvolume_delete_verbose() {
    let (_td, mnt) = single_mount();
    let mp = mnt.path().to_str().unwrap();
    let subvol = format!("{mp}/verbvol");

    btrfs_ok(&["subvolume", "create", &subvol]);

    let out = btrfs_ok(&["subvolume", "delete", "-v", &subvol]);
    assert!(
        out.contains("Delete subvolume"),
        "expected verbose delete message:\n{out}"
    );
}

// ── replace start/status/cancel ─────────────────────────────────────

#[test]
#[ignore = "requires elevated privileges"]
fn replace_start_and_status() {
    let (_td, mnt) = single_mount();
    let mp = mnt.path().to_str().unwrap();

    // Write some data so the replace has something to copy.
    write_test_data(Path::new(mp), "testdata", 1024 * 1024);

    // Create target device.
    let target_file =
        BackingFile::new(_td.path(), "replace-target.img", 512_000_000);
    let target_dev = LoopbackDevice::new(target_file);
    let target_path = target_dev.path().to_str().unwrap();

    // Replace devid 1 with the target device; -B waits for completion.
    btrfs_ok(&["replace", "start", "-B", "-f", "1", target_path, mp]);

    // After completion, status should show finished/completed.
    let out = btrfs_ok(&["replace", "status", mp]);
    assert!(
        out.contains("finished")
            || out.contains("completed")
            || out.contains("Started")
            || out.contains("no device replace"),
        "unexpected replace status after completion:\n{out}"
    );

    // Verify data is still accessible.
    verify_test_data(Path::new(mp), "testdata", 1024 * 1024);
}

#[test]
#[ignore = "requires elevated privileges"]
fn replace_cancel_not_running() {
    let (_td, mnt) = single_mount();
    let mp = mnt.path().to_str().unwrap();

    // Cancel with no replace running should succeed and report it.
    let out = btrfs_ok(&["replace", "cancel", mp]);
    assert!(
        out.contains("no replace") || out.contains("not in progress"),
        "expected no-op cancel message:\n{out}"
    );
}

// ── send/receive: special files ─────────────────────────────────────

#[test]
#[ignore = "requires elevated privileges"]
fn send_receive_special_files() {
    let (_td1, mnt1) = single_mount();
    let (_td2, mnt2) = single_mount();
    let mp1 = mnt1.path().to_str().unwrap();
    let mp2 = mnt2.path().to_str().unwrap();
    let stream_file = format!("{}/special.bin", _td1.path().to_str().unwrap());

    let src = format!("{mp1}/special");
    btrfs_ok(&["subvolume", "create", &src]);

    // Create various special files.
    write_test_data(Path::new(&src), "regular.bin", 4096);
    symlink("regular.bin", format!("{src}/link.sym")).unwrap();
    fs::hard_link(format!("{src}/regular.bin"), format!("{src}/hardlink.bin"))
        .unwrap();
    // FIFO (named pipe).
    nix::unistd::mkfifo(
        &PathBuf::from(format!("{src}/pipe")),
        stat::Mode::from_bits_truncate(0o644),
    )
    .unwrap();

    btrfs_ok(&["property", "set", "-t", "subvol", &src, "ro", "true"]);
    btrfs_ok(&["send", "-f", &stream_file, &src]);
    btrfs_ok(&["receive", "-f", &stream_file, mp2]);

    let recv = format!("{mp2}/special");

    // Regular file.
    verify_test_data(Path::new(&recv), "regular.bin", 4096);

    // Symlink.
    let link_target = fs::read_link(format!("{recv}/link.sym")).unwrap();
    assert_eq!(link_target.to_str().unwrap(), "regular.bin");

    // Hard link (should share inode with regular.bin).
    let meta_orig = fs::metadata(format!("{recv}/regular.bin")).unwrap();
    let meta_hard = fs::metadata(format!("{recv}/hardlink.bin")).unwrap();
    assert_eq!(meta_orig.ino(), meta_hard.ino());

    // FIFO.
    let fifo_meta = fs::symlink_metadata(format!("{recv}/pipe")).unwrap();
    assert!(
        fifo_meta.file_type().is_fifo(),
        "expected FIFO, got {:?}",
        fifo_meta.file_type()
    );
}

#[test]
#[ignore = "requires elevated privileges"]
fn send_receive_xattrs() {
    let (_td1, mnt1) = single_mount();
    let (_td2, mnt2) = single_mount();
    let mp1 = mnt1.path().to_str().unwrap();
    let mp2 = mnt2.path().to_str().unwrap();
    let stream_file = format!("{}/xattr.bin", _td1.path().to_str().unwrap());

    let src = format!("{mp1}/xattr_test");
    btrfs_ok(&["subvolume", "create", &src]);

    let file_path = format!("{src}/testfile");
    fs::write(&file_path, b"xattr test content").unwrap();

    // Set xattrs using the setfattr command.
    let status = Command::new("setfattr")
        .args(["-n", "user.myattr", "-v", "hello", &file_path])
        .status()
        .expect("setfattr not found");
    assert!(status.success(), "setfattr failed");

    btrfs_ok(&["property", "set", "-t", "subvol", &src, "ro", "true"]);
    btrfs_ok(&["send", "-f", &stream_file, &src]);
    btrfs_ok(&["receive", "-f", &stream_file, mp2]);

    // Verify xattr was preserved.
    let recv_file = format!("{mp2}/xattr_test/testfile");
    let output = Command::new("getfattr")
        .args(["--only-values", "-n", "user.myattr", &recv_file])
        .output()
        .expect("getfattr not found");
    assert!(output.status.success(), "getfattr failed");
    assert_eq!(
        String::from_utf8_lossy(&output.stdout).trim(),
        "hello",
        "xattr value mismatch"
    );
}

#[test]
#[ignore = "requires elevated privileges"]
fn send_receive_force_decompress() {
    // Source: mount with zstd compression.
    let td1 = tempdir().unwrap();
    let file1 = BackingFile::new(td1.path(), "disk.img", 512_000_000);
    file1.mkfs();
    let lo1 = LoopbackDevice::new(file1);
    let mnt1 = common::Mount::with_options(lo1, td1.path(), &["compress=zstd"]);
    let mp1 = mnt1.path().to_str().unwrap();

    let (_td2, mnt2) = single_mount();
    let mp2 = mnt2.path().to_str().unwrap();
    let stream_file = format!("{}/decomp.bin", td1.path().to_str().unwrap());

    let src = format!("{mp1}/decomp_test");
    btrfs_ok(&["subvolume", "create", &src]);
    common::write_compressible_data(Path::new(&src), "data.bin", 128 * 1024);
    write_test_data(Path::new(&src), "pattern.bin", 64 * 1024);
    btrfs_ok(&["filesystem", "sync", mp1]);

    btrfs_ok(&["property", "set", "-t", "subvol", &src, "ro", "true"]);
    btrfs_ok(&["send", "--compressed-data", "-f", &stream_file, &src]);

    // Receive with --force-decompress to exercise the decompression fallback.
    btrfs_ok(&["receive", "--force-decompress", "-f", &stream_file, mp2]);

    let recv = format!("{mp2}/decomp_test");
    assert!(Path::new(&recv).is_dir(), "received subvol not found");

    let data = fs::read(format!("{recv}/data.bin")).unwrap();
    assert_eq!(data.len(), 128 * 1024);
    assert!(data.iter().all(|&b| b == 0), "data.bin should be all zeros");
    verify_test_data(Path::new(&recv), "pattern.bin", 64 * 1024);
}

#[test]
#[ignore = "requires elevated privileges"]
fn send_receive_truncate() {
    let (_td1, mnt1) = single_mount();
    let (_td2, mnt2) = single_mount();
    let mp1 = mnt1.path().to_str().unwrap();
    let mp2 = mnt2.path().to_str().unwrap();
    let base_stream =
        format!("{}/trunc_base.bin", _td1.path().to_str().unwrap());
    let incr_stream =
        format!("{}/trunc_incr.bin", _td1.path().to_str().unwrap());

    let src = format!("{mp1}/trunc_src");
    btrfs_ok(&["subvolume", "create", &src]);
    write_test_data(Path::new(&src), "shrink.bin", 65536);

    let snap1 = format!("{mp1}/trunc_snap1");
    btrfs_ok(&["subvolume", "snapshot", "-r", &src, &snap1]);

    // Truncate the file to a smaller size.
    let f = fs::OpenOptions::new()
        .write(true)
        .open(format!("{src}/shrink.bin"))
        .unwrap();
    f.set_len(1024).unwrap();
    drop(f);

    let snap2 = format!("{mp1}/trunc_snap2");
    btrfs_ok(&["subvolume", "snapshot", "-r", &src, &snap2]);

    btrfs_ok(&["send", "-f", &base_stream, &snap1]);
    btrfs_ok(&["receive", "-f", &base_stream, mp2]);
    btrfs_ok(&["send", "-p", &snap1, "-f", &incr_stream, &snap2]);
    btrfs_ok(&["receive", "-f", &incr_stream, mp2]);

    let recv = format!("{mp2}/trunc_snap2/shrink.bin");
    let meta = fs::metadata(&recv).unwrap();
    assert_eq!(meta.len(), 1024, "truncated file should be 1024 bytes");
}

#[test]
#[ignore = "requires elevated privileges"]
fn send_receive_mknod_mksock() {
    let (_td1, mnt1) = single_mount();
    let (_td2, mnt2) = single_mount();
    let mp1 = mnt1.path().to_str().unwrap();
    let mp2 = mnt2.path().to_str().unwrap();
    let stream_file = format!("{}/mknod.bin", _td1.path().to_str().unwrap());

    let src = format!("{mp1}/devnodes");
    btrfs_ok(&["subvolume", "create", &src]);

    // Create a character device node (null device: 1,3) and a unix socket.
    stat::mknod(
        &PathBuf::from(format!("{src}/chardev")),
        stat::SFlag::S_IFCHR,
        stat::Mode::from_bits_truncate(0o666),
        stat::makedev(1, 3),
    )
    .unwrap();

    // Unix socket.
    let sock_path = format!("{src}/mysock");
    let sock = std::os::unix::net::UnixListener::bind(&sock_path).unwrap();
    drop(sock);

    btrfs_ok(&["property", "set", "-t", "subvol", &src, "ro", "true"]);
    btrfs_ok(&["send", "-f", &stream_file, &src]);
    btrfs_ok(&["receive", "-f", &stream_file, mp2]);

    let recv = format!("{mp2}/devnodes");

    // Verify character device.
    let chardev_meta = fs::symlink_metadata(format!("{recv}/chardev")).unwrap();
    assert!(
        chardev_meta.file_type().is_char_device(),
        "expected char device"
    );

    // Verify socket.
    let sock_meta = fs::symlink_metadata(format!("{recv}/mysock")).unwrap();
    assert!(sock_meta.file_type().is_socket(), "expected socket");
}

#[test]
#[ignore = "requires elevated privileges"]
fn send_receive_rmdir() {
    let (_td1, mnt1) = single_mount();
    let (_td2, mnt2) = single_mount();
    let mp1 = mnt1.path().to_str().unwrap();
    let mp2 = mnt2.path().to_str().unwrap();
    let base_stream =
        format!("{}/rmdir_base.bin", _td1.path().to_str().unwrap());
    let incr_stream =
        format!("{}/rmdir_incr.bin", _td1.path().to_str().unwrap());

    let src = format!("{mp1}/rmdir_src");
    btrfs_ok(&["subvolume", "create", &src]);
    fs::create_dir(format!("{src}/mydir")).unwrap();
    write_test_data(Path::new(&format!("{src}/mydir")), "file.bin", 1024);

    let snap1 = format!("{mp1}/rmdir_snap1");
    btrfs_ok(&["subvolume", "snapshot", "-r", &src, &snap1]);

    // Remove the directory and its contents.
    fs::remove_file(format!("{src}/mydir/file.bin")).unwrap();
    fs::remove_dir(format!("{src}/mydir")).unwrap();

    let snap2 = format!("{mp1}/rmdir_snap2");
    btrfs_ok(&["subvolume", "snapshot", "-r", &src, &snap2]);

    btrfs_ok(&["send", "-f", &base_stream, &snap1]);
    btrfs_ok(&["receive", "-f", &base_stream, mp2]);
    btrfs_ok(&["send", "-p", &snap1, "-f", &incr_stream, &snap2]);
    btrfs_ok(&["receive", "-f", &incr_stream, mp2]);

    let recv = format!("{mp2}/rmdir_snap2");
    assert!(
        !Path::new(&format!("{recv}/mydir")).exists(),
        "mydir should have been removed"
    );
}

#[test]
#[ignore = "requires elevated privileges"]
fn send_receive_remove_xattr() {
    let (_td1, mnt1) = single_mount();
    let (_td2, mnt2) = single_mount();
    let mp1 = mnt1.path().to_str().unwrap();
    let mp2 = mnt2.path().to_str().unwrap();
    let base_stream =
        format!("{}/xattr_base.bin", _td1.path().to_str().unwrap());
    let incr_stream =
        format!("{}/xattr_incr.bin", _td1.path().to_str().unwrap());

    let src = format!("{mp1}/xattr_rm_src");
    btrfs_ok(&["subvolume", "create", &src]);
    let file_path = format!("{src}/testfile");
    fs::write(&file_path, b"content").unwrap();

    // Set an xattr, then take a snapshot.
    let status = Command::new("setfattr")
        .args(["-n", "user.remove_me", "-v", "val", &file_path])
        .status()
        .expect("setfattr not found");
    assert!(status.success());

    let snap1 = format!("{mp1}/xattr_snap1");
    btrfs_ok(&["subvolume", "snapshot", "-r", &src, &snap1]);

    // Remove the xattr and take another snapshot.
    let status = Command::new("setfattr")
        .args(["-x", "user.remove_me", &file_path])
        .status()
        .expect("setfattr not found");
    assert!(status.success());

    let snap2 = format!("{mp1}/xattr_snap2");
    btrfs_ok(&["subvolume", "snapshot", "-r", &src, &snap2]);

    btrfs_ok(&["send", "-f", &base_stream, &snap1]);
    btrfs_ok(&["receive", "-f", &base_stream, mp2]);
    btrfs_ok(&["send", "-p", &snap1, "-f", &incr_stream, &snap2]);

    // Verify the incremental stream contains remove_xattr.
    let dump = btrfs_ok(&["receive", "--dump", "-f", &incr_stream]);
    assert!(
        dump.contains("remove_xattr"),
        "expected remove_xattr in stream:\n{dump}"
    );

    btrfs_ok(&["receive", "-f", &incr_stream, mp2]);

    // Verify the xattr is gone on the received side.
    let recv_file = format!("{mp2}/xattr_snap2/testfile");
    let output = Command::new("getfattr")
        .args(["-n", "user.remove_me", &recv_file])
        .output()
        .expect("getfattr not found");
    assert!(!output.status.success(), "xattr should have been removed");
}

#[test]
#[ignore = "requires elevated privileges"]
fn send_receive_fallocate() {
    let (_td1, mnt1) = single_mount();
    let (_td2, mnt2) = single_mount();
    let mp1 = mnt1.path().to_str().unwrap();
    let mp2 = mnt2.path().to_str().unwrap();
    let base_stream =
        format!("{}/falloc_base.bin", _td1.path().to_str().unwrap());
    let incr_stream =
        format!("{}/falloc_incr.bin", _td1.path().to_str().unwrap());

    let src = format!("{mp1}/falloc_src");
    btrfs_ok(&["subvolume", "create", &src]);

    // Write a file, then take a base snapshot.
    write_test_data(Path::new(&src), "holey.bin", 256 * 1024);

    let snap1 = format!("{mp1}/falloc_snap1");
    btrfs_ok(&["subvolume", "snapshot", "-r", &src, &snap1]);

    // Punch a hole in the middle of the file.
    let file_path = format!("{src}/holey.bin");
    let status = Command::new("fallocate")
        .args([
            "--punch-hole",
            "--offset",
            "65536",
            "--length",
            "65536",
            &file_path,
        ])
        .status()
        .expect("fallocate not found");
    assert!(status.success(), "fallocate --punch-hole failed");

    let snap2 = format!("{mp1}/falloc_snap2");
    btrfs_ok(&["subvolume", "snapshot", "-r", &src, &snap2]);

    btrfs_ok(&["send", "-f", &base_stream, &snap1]);
    btrfs_ok(&["receive", "-f", &base_stream, mp2]);
    // Use --proto 2 to get v2 stream with fallocate commands.
    btrfs_ok(&[
        "send",
        "--proto",
        "2",
        "-p",
        &snap1,
        "-f",
        &incr_stream,
        &snap2,
    ]);
    btrfs_ok(&["receive", "-f", &incr_stream, mp2]);

    // Verify the file size is preserved but the hole exists.
    let recv_file = format!("{mp2}/falloc_snap2/holey.bin");
    let meta = fs::metadata(&recv_file).unwrap();
    assert_eq!(meta.len(), 256 * 1024);

    // Read the hole region — should be zeros.
    let mut f = fs::File::open(&recv_file).unwrap();
    f.seek(SeekFrom::Start(65536)).unwrap();
    let mut hole = vec![0u8; 65536];
    f.read_exact(&mut hole).unwrap();
    assert!(hole.iter().all(|&b| b == 0), "punched hole should be zeros");
}

// ── mkfs --rootdir (end-to-end) ─────────────────────────────────────

/// Create a directory with various file types, run our mkfs --rootdir,
/// mount the resulting image, and verify all data is intact.
#[test]
#[ignore = "requires elevated privileges"]
fn mkfs_rootdir_end_to_end() {
    let td = tempdir().unwrap();
    let rootdir = td.path().join("rootdir");
    fs::create_dir_all(&rootdir).unwrap();

    // Regular files: small (inline) and large (regular extent).
    write_test_data(&rootdir, "small.bin", 100);
    write_test_data(&rootdir, "large.bin", 2 * 1024 * 1024);

    // Subdirectory with a file.
    let sub = rootdir.join("subdir");
    fs::create_dir_all(&sub).unwrap();
    write_test_data(&sub, "nested.bin", 8192);

    // Symlink.
    symlink("small.bin", rootdir.join("link.txt")).unwrap();

    // Empty file.
    fs::File::create(rootdir.join("empty")).unwrap();

    // Create image, format with --rootdir, mount.
    let file = BackingFile::new(td.path(), "disk.img", 512_000_000);
    file.mkfs_rootdir(&our_mkfs_bin(), &rootdir, &[]);
    let lo = LoopbackDevice::new(file);
    let mnt = Mount::new(lo, td.path());
    let mp = mnt.path();

    // Verify data integrity.
    verify_test_data(mp, "small.bin", 100);
    verify_test_data(mp, "large.bin", 2 * 1024 * 1024);
    verify_test_data(&mp.join("subdir"), "nested.bin", 8192);

    // Verify symlink.
    let link_target = fs::read_link(mp.join("link.txt")).unwrap();
    assert_eq!(link_target.to_str().unwrap(), "small.bin");

    // Verify empty file exists and is empty.
    let empty_meta = fs::metadata(mp.join("empty")).unwrap();
    assert_eq!(empty_meta.len(), 0);

    // Verify subdirectory exists.
    assert!(mp.join("subdir").is_dir());
}

/// Test --rootdir with zstd compression: data should still be readable.
#[test]
#[ignore = "requires elevated privileges"]
fn mkfs_rootdir_compressed() {
    let td = tempdir().unwrap();
    let rootdir = td.path().join("rootdir");
    fs::create_dir_all(&rootdir).unwrap();

    // Compressible data (zeros compress well).
    write_compressible_data(&rootdir, "zeros.bin", 1024 * 1024);
    // Incompressible data (random pattern).
    write_test_data(&rootdir, "random.bin", 64 * 1024);

    let file = BackingFile::new(td.path(), "disk.img", 512_000_000);
    file.mkfs_rootdir(&our_mkfs_bin(), &rootdir, &["--compress", "zstd"]);
    let lo = LoopbackDevice::new(file);
    let mnt = Mount::new(lo, td.path());
    let mp = mnt.path();

    // Verify data reads back correctly (kernel handles decompression).
    let zeros = fs::read(mp.join("zeros.bin")).unwrap();
    assert_eq!(zeros.len(), 1024 * 1024);
    assert!(zeros.iter().all(|&b| b == 0), "decompressed zeros mismatch");

    verify_test_data(mp, "random.bin", 64 * 1024);
}

/// Test --rootdir with --shrink: image should be smaller than the full device size.
#[test]
#[ignore = "requires elevated privileges"]
fn mkfs_rootdir_shrink() {
    let td = tempdir().unwrap();
    let rootdir = td.path().join("rootdir");
    fs::create_dir_all(&rootdir).unwrap();

    write_test_data(&rootdir, "data.bin", 4096);

    let file = BackingFile::new(td.path(), "disk.img", 512_000_000);
    file.mkfs_rootdir(&our_mkfs_bin(), &rootdir, &["--shrink"]);

    // Image should be much smaller than 512 MB.
    let img_size = fs::metadata(td.path().join("disk.img")).unwrap().len();
    assert!(
        img_size < 200_000_000,
        "shrunk image should be < 200 MB, got {img_size}"
    );

    // Should still mount and have the data.
    let lo = LoopbackDevice::new(file);
    let mnt = Mount::new(lo, td.path());
    verify_test_data(mnt.path(), "data.bin", 4096);
}

/// Test --rootdir with LZO compression: data should still be readable.
/// LZO uses a per-sector framing format that differs from zlib/zstd.
#[test]
#[ignore = "requires elevated privileges"]
fn mkfs_rootdir_lzo_compressed() {
    let td = tempdir().unwrap();
    let rootdir = td.path().join("rootdir");
    fs::create_dir_all(&rootdir).unwrap();

    // Compressible data (zeros compress well with LZO).
    write_compressible_data(&rootdir, "zeros.bin", 1024 * 1024);
    // Small inline file (uses single-segment LZO format).
    fs::write(rootdir.join("small.txt"), "hello LZO compression test").unwrap();
    // Incompressible data (pseudo-random pattern).
    write_test_data(&rootdir, "random.bin", 64 * 1024);

    let file = BackingFile::new(td.path(), "disk.img", 512_000_000);
    file.mkfs_rootdir(&our_mkfs_bin(), &rootdir, &["--compress", "lzo"]);
    let lo = LoopbackDevice::new(file);
    let mnt = Mount::new(lo, td.path());
    let mp = mnt.path();

    // Verify data reads back correctly (kernel handles LZO decompression).
    let zeros = fs::read(mp.join("zeros.bin")).unwrap();
    assert_eq!(zeros.len(), 1024 * 1024);
    assert!(zeros.iter().all(|&b| b == 0), "decompressed zeros mismatch");

    let small = fs::read_to_string(mp.join("small.txt")).unwrap();
    assert_eq!(small, "hello LZO compression test");

    verify_test_data(mp, "random.bin", 64 * 1024);
}

/// Test --rootdir hardlink and xattr handling end-to-end.
///
/// Hardlinks exercise the post-walk `set_inode_nlink` fixup path; xattrs
/// exercise the inline `set_xattr` calls. Mount and verify both
/// inode-number equality (for hardlinks) and the xattr round-trip.
///
/// Hardlinks are placed in *different* parent directories — multiple
/// hardlinks under the same parent need a single appended `INODE_REF`
/// item (or `INODE_EXTREF` spill), which neither the legacy mkfs walker
/// nor the new transactional walker supports today. The cross-parent
/// case is the common one and is what this test covers.
#[test]
#[ignore = "requires elevated privileges"]
fn mkfs_rootdir_hardlinks_and_xattrs() {
    let td = tempdir().unwrap();
    let rootdir = td.path().join("rootdir");
    std::fs::create_dir_all(&rootdir).unwrap();

    // Hardlink across directories: original at root, second + third
    // links in two distinct subdirs. Each link lives under a different
    // parent inode, so each emits a separate INODE_REF item and the
    // duplicate-key path is never hit.
    std::fs::write(rootdir.join("orig.bin"), b"hardlink content").unwrap();
    let sub1 = rootdir.join("sub1");
    let sub2 = rootdir.join("sub2");
    std::fs::create_dir_all(&sub1).unwrap();
    std::fs::create_dir_all(&sub2).unwrap();
    std::fs::hard_link(rootdir.join("orig.bin"), sub1.join("second.bin"))
        .unwrap();
    std::fs::hard_link(rootdir.join("orig.bin"), sub2.join("third.bin"))
        .unwrap();

    // A separate file with extended attributes.
    let xfile = rootdir.join("xattr.bin");
    std::fs::write(&xfile, b"file with xattrs").unwrap();
    set_user_xattr(&xfile, "user.note", b"hello xattr value");
    set_user_xattr(&xfile, "user.color", b"chartreuse");

    let file = BackingFile::new(td.path(), "disk.img", 512_000_000);
    file.mkfs_rootdir(&our_mkfs_bin(), &rootdir, &[]);
    let lo = LoopbackDevice::new(file);
    let mnt = Mount::new(lo, td.path());
    let mp = mnt.path();

    // All three hardlinked paths point at the same inode with nlink=3.
    let m_orig = std::fs::metadata(mp.join("orig.bin")).unwrap();
    let m_second = std::fs::metadata(mp.join("sub1/second.bin")).unwrap();
    let m_third = std::fs::metadata(mp.join("sub2/third.bin")).unwrap();
    assert_eq!(m_orig.ino(), m_second.ino());
    assert_eq!(m_orig.ino(), m_third.ino());
    assert_eq!(m_orig.nlink(), 3);

    // Xattrs round-trip.
    let note = get_user_xattr(&mp.join("xattr.bin"), "user.note");
    assert_eq!(note.as_slice(), b"hello xattr value");
    let color = get_user_xattr(&mp.join("xattr.bin"), "user.color");
    assert_eq!(color.as_slice(), b"chartreuse");
}

/// Test --rootdir --subvol end-to-end: rw, ro, and nested subvols
/// land as real kernel subvolumes after mount.
///
/// Verifies: each declared subvol appears in `btrfs subvolume list`
/// (real subvol, not just a plain directory); files inside the
/// subvol are readable; the ro subvol rejects writes; nested
/// subvols nest correctly.
#[test]
#[ignore = "requires elevated privileges"]
fn mkfs_rootdir_subvols() {
    let td = tempdir().unwrap();
    let rootdir = td.path().join("rootdir");
    std::fs::create_dir_all(&rootdir).unwrap();

    // rw subvol with a file.
    let rwsub = rootdir.join("rwsub");
    std::fs::create_dir_all(&rwsub).unwrap();
    std::fs::write(rwsub.join("rw-file.txt"), b"rw subvol content").unwrap();

    // ro subvol with a file.
    let rosub = rootdir.join("rosub");
    std::fs::create_dir_all(&rosub).unwrap();
    std::fs::write(rosub.join("ro-file.txt"), b"ro subvol content").unwrap();

    // Nested subvol: rwsub/inner is its own subvol.
    let nested = rwsub.join("inner");
    std::fs::create_dir_all(&nested).unwrap();
    std::fs::write(nested.join("nested-file.txt"), b"nested content").unwrap();

    let file = BackingFile::new(td.path(), "disk.img", 512_000_000);
    file.mkfs_rootdir(
        &our_mkfs_bin(),
        &rootdir,
        &[
            "--subvol",
            "rw:rwsub",
            "--subvol",
            "ro:rosub",
            "--subvol",
            "rw:rwsub/inner",
        ],
    );
    let lo = LoopbackDevice::new(file);
    let mnt = Mount::new(lo, td.path());
    let mp = mnt.path();

    // List subvols and verify all three appear.
    let listing = btrfs_ok(&["subvolume", "list", mp.to_str().unwrap()]);
    assert!(
        listing.contains("rwsub"),
        "rwsub not in subvol listing:\n{listing}"
    );
    assert!(
        listing.contains("rosub"),
        "rosub not in subvol listing:\n{listing}"
    );
    assert!(
        listing.contains("inner"),
        "nested 'inner' not in subvol listing:\n{listing}"
    );

    // Verify file contents are readable through each subvol path.
    let rw_data = std::fs::read(mp.join("rwsub/rw-file.txt")).unwrap();
    assert_eq!(rw_data.as_slice(), b"rw subvol content");
    let ro_data = std::fs::read(mp.join("rosub/ro-file.txt")).unwrap();
    assert_eq!(ro_data.as_slice(), b"ro subvol content");
    let nested_data =
        std::fs::read(mp.join("rwsub/inner/nested-file.txt")).unwrap();
    assert_eq!(nested_data.as_slice(), b"nested content");

    // ro subvol rejects writes (kernel enforces ROOT_SUBVOL_RDONLY).
    let write_attempt = std::fs::write(mp.join("rosub/new.txt"), b"nope");
    assert!(
        write_attempt.is_err(),
        "writing into ro subvol should fail (got {write_attempt:?})"
    );
}

/// Test --rootdir --reflink end-to-end on an actual btrfs filesystem.
///
/// FICLONERANGE requires both source and destination on a filesystem
/// that supports it (typically btrfs). To exercise the path for real,
/// this test mounts a btrfs workspace, creates the source rootdir
/// AND the destination image inside it, runs `mkfs --rootdir
/// --reflink`, then mounts the destination and verifies file content
/// reads back correctly.
#[test]
#[ignore = "requires elevated privileges"]
fn mkfs_rootdir_reflink_on_btrfs() {
    let outer = tempdir().unwrap();

    // Mount::new mounts at base_dir.join("mnt"), so each Mount needs
    // a distinct base. Outer btrfs workspace gets `outer/ws`, dest
    // mount gets `outer/dest`.
    let workspace_base = outer.path().join("ws");
    std::fs::create_dir_all(&workspace_base).unwrap();
    let workspace_img =
        BackingFile::new(&workspace_base, "workspace.img", 1024 * 1024 * 1024);
    workspace_img.mkfs();
    let workspace_lo = LoopbackDevice::new(workspace_img);
    let workspace_mnt = Mount::new(workspace_lo, &workspace_base);
    let workspace = workspace_mnt.path();

    // Source rootdir + 1 MB payload (large enough to need a regular
    // extent rather than going inline).
    let rootdir = workspace.join("rootdir");
    std::fs::create_dir_all(&rootdir).unwrap();
    let payload = vec![0xCDu8; 1024 * 1024];
    std::fs::write(rootdir.join("data.bin"), &payload).unwrap();

    // Destination image inside the same btrfs mount so source and
    // dest share a filesystem (FICLONERANGE precondition).
    let dest_img = BackingFile::new(workspace, "dest.img", 512 * 1024 * 1024);
    dest_img.mkfs_rootdir(&our_mkfs_bin(), &rootdir, &["--reflink"]);

    let dest_lo = LoopbackDevice::new(dest_img);
    let dest_base = outer.path().join("dest");
    std::fs::create_dir_all(&dest_base).unwrap();
    let dest_mnt = Mount::new(dest_lo, &dest_base);
    let dest_mp = dest_mnt.path();

    // The cloned file reads back identical to the source.
    let read = std::fs::read(dest_mp.join("data.bin")).unwrap();
    assert_eq!(read.len(), payload.len());
    assert_eq!(read, payload);

    // Drop the inner mount + loop device + image (which lives inside
    // the workspace mount) explicitly, with a `sync` between, so the
    // workspace mount has nothing holding it open by the time the
    // outer Mount RAII guard runs its umount.
    drop(dest_mnt);
    let _ = std::process::Command::new("sync").status();
    // dest_lo drops here, detaching the loop device and removing the
    // backing file (dest.img) from inside the workspace.
}

/// Set a single extended attribute via `setxattr(2)`.
fn set_user_xattr(path: &Path, name: &str, value: &[u8]) {
    let c_path =
        std::ffi::CString::new(path.as_os_str().as_encoded_bytes()).unwrap();
    let c_name = std::ffi::CString::new(name).unwrap();
    let ret = unsafe {
        libc::setxattr(
            c_path.as_ptr(),
            c_name.as_ptr(),
            value.as_ptr().cast::<libc::c_void>(),
            value.len(),
            0,
        )
    };
    assert_eq!(ret, 0, "setxattr({path:?}, {name:?}) failed");
}

/// Read a single extended attribute via `getxattr(2)`.
fn get_user_xattr(path: &Path, name: &str) -> Vec<u8> {
    let c_path =
        std::ffi::CString::new(path.as_os_str().as_encoded_bytes()).unwrap();
    let c_name = std::ffi::CString::new(name).unwrap();
    let size = unsafe {
        libc::getxattr(
            c_path.as_ptr(),
            c_name.as_ptr(),
            std::ptr::null_mut(),
            0,
        )
    };
    assert!(size >= 0, "getxattr probe({path:?}, {name:?}) failed");
    let mut buf = vec![0u8; size as usize];
    let n = unsafe {
        libc::getxattr(
            c_path.as_ptr(),
            c_name.as_ptr(),
            buf.as_mut_ptr().cast::<libc::c_void>(),
            buf.len(),
        )
    };
    assert!(n >= 0, "getxattr({path:?}, {name:?}) failed");
    buf.truncate(n as usize);
    buf
}

// ── rescue ──────────────────────────────────────────────────────────

#[test]
#[ignore = "requires elevated privileges"]
fn rescue_clear_uuid_tree() {
    let td = tempdir().unwrap();
    let file = BackingFile::new(td.path(), "disk.img", 512_000_000);
    file.mkfs();
    let lo = LoopbackDevice::new(file);

    // Mount, create subvolumes to populate the UUID tree, then unmount.
    let lo = {
        let mnt = Mount::new(lo, td.path());
        let mp = mnt.path();
        btrfs_ok(&["subvolume", "create", mp.join("sub1").to_str().unwrap()]);
        btrfs_ok(&["subvolume", "create", mp.join("sub2").to_str().unwrap()]);
        btrfs_ok(&[
            "subvolume",
            "snapshot",
            mp.join("sub1").to_str().unwrap(),
            mp.join("snap1").to_str().unwrap(),
        ]);
        mnt.into_loopback()
    };

    let dev = lo.path().to_str().unwrap();
    let out = btrfs_ok(&["rescue", "clear-uuid-tree", dev]);
    assert!(
        out.contains("Cleared uuid tree"),
        "expected success message, got: {out}"
    );

    let check_output = Command::new("btrfs")
        .args(["check", "--readonly", dev])
        .output()
        .expect("failed to run btrfs check");
    if !check_output.status.success() {
        let stderr = String::from_utf8_lossy(&check_output.stderr);
        let stdout = String::from_utf8_lossy(&check_output.stdout);
        panic!(
            "btrfs check failed:\n--- stdout ---\n{stdout}\n--- stderr ---\n{stderr}"
        );
    }

    // Mount read-write to verify the subvolumes survived and the
    // free space tree is consistent enough for the kernel to use it
    // for allocation decisions.
    let mnt = Mount::new(lo, td.path());
    let mp = mnt.path();
    assert!(mp.join("sub1").exists(), "sub1 should still exist");
    assert!(mp.join("sub2").exists(), "sub2 should still exist");
    assert!(mp.join("snap1").exists(), "snap1 should still exist");
}

#[test]
#[ignore = "requires elevated privileges"]
fn rescue_clear_space_cache_v2() {
    let td = tempdir().unwrap();
    let file = BackingFile::new(td.path(), "disk.img", 512_000_000);
    // BLOCK_GROUP_TREE requires FREE_SPACE_TREE, so disable BGT to
    // get a filesystem where clearing FST is actually legal.
    file.mkfs_with_args(&["-O", "^block-group-tree"]);
    let lo = LoopbackDevice::new(file);

    // Mount, write some data so the FST has block-group entries to
    // rebuild later, then unmount.
    let lo = {
        let mnt = Mount::new(lo, td.path());
        let mp = mnt.path();
        std::fs::write(mp.join("hello.txt"), b"hello world").unwrap();
        std::fs::create_dir(mp.join("d")).unwrap();
        std::fs::write(mp.join("d/payload.bin"), vec![0xAB; 256 * 1024])
            .unwrap();
        mnt.into_loopback()
    };

    let dev = lo.path().to_str().unwrap();

    let out = btrfs_ok(&["rescue", "clear-space-cache", "v2", dev]);
    assert!(
        out.contains("cleared free space tree")
            || out.contains("no free space tree"),
        "expected success message, got: {out}"
    );

    let check_output = Command::new("btrfs")
        .args(["check", "--readonly", dev])
        .output()
        .expect("failed to run btrfs check");
    if !check_output.status.success() {
        let stderr = String::from_utf8_lossy(&check_output.stderr);
        let stdout = String::from_utf8_lossy(&check_output.stdout);
        panic!(
            "btrfs check failed:\n--- stdout ---\n{stdout}\n--- stderr ---\n{stderr}"
        );
    }

    // Mount read-write to force the kernel to rebuild the free
    // space tree, then verify the data we wrote earlier is intact.
    let mnt = Mount::new(lo, td.path());
    let mp = mnt.path();
    assert_eq!(std::fs::read(mp.join("hello.txt")).unwrap(), b"hello world");
    assert_eq!(
        std::fs::read(mp.join("d/payload.bin")).unwrap(),
        vec![0xAB; 256 * 1024]
    );
}

#[test]
#[ignore = "requires elevated privileges"]
fn rescue_clear_ino_cache_clean_fs() {
    // The inode_cache mount option was removed from the kernel, so
    // there's no way to produce real ino-cache items on a modern
    // system. The best we can do is verify the command runs cleanly
    // on a fresh filesystem (the common case post-deprecation),
    // walks every fs tree without corrupting anything, and reports
    // the no-op message.
    let td = tempdir().unwrap();
    let file = BackingFile::new(td.path(), "disk.img", 256 * 1024 * 1024);
    file.mkfs_with_args(&["-O", "^block-group-tree"]);
    let lo = LoopbackDevice::new(file);

    // Add a couple of subvolumes so the walk has more than one fs
    // tree to traverse.
    let lo = {
        let mnt = Mount::new(lo, td.path());
        let mp = mnt.path();
        let sv1 = mp.join("sv1");
        let sv2 = mp.join("sv2");
        Command::new("btrfs")
            .args(["subvolume", "create", sv1.to_str().unwrap()])
            .status()
            .expect("btrfs subvolume create failed");
        Command::new("btrfs")
            .args(["subvolume", "create", sv2.to_str().unwrap()])
            .status()
            .expect("btrfs subvolume create failed");
        std::fs::write(sv1.join("file.bin"), vec![0xAA; 4096]).unwrap();
        mnt.into_loopback()
    };

    let dev = lo.path().to_str().unwrap();
    let out = btrfs_ok(&["rescue", "clear-ino-cache", dev]);
    assert!(
        out.contains("no inode cache items found")
            || out.contains("cleared inode cache"),
        "expected ino-cache clear message, got: {out}"
    );

    let check_output = Command::new("btrfs")
        .args(["check", "--readonly", dev])
        .output()
        .expect("failed to run btrfs check");
    if !check_output.status.success() {
        let stderr = String::from_utf8_lossy(&check_output.stderr);
        let stdout = String::from_utf8_lossy(&check_output.stdout);
        panic!(
            "btrfs check failed:\n--- stdout ---\n{stdout}\n--- stderr ---\n{stderr}"
        );
    }
}

#[test]
#[ignore = "requires elevated privileges"]
fn rescue_clear_space_cache_v1() {
    let td = tempdir().unwrap();
    let file = BackingFile::new(td.path(), "disk.img", 512_000_000);
    // Disable both BGT and FST so the kernel uses the v1 space cache.
    file.mkfs_with_args(&["-O", "^block-group-tree", "-O", "^free-space-tree"]);
    let lo = LoopbackDevice::new(file);

    // Mount with space_cache=v1 and write enough to force the kernel
    // to materialize cache files for at least one block group.
    let lo = {
        let mnt = Mount::with_options(lo, td.path(), &["space_cache=v1"]);
        let mp = mnt.path();
        std::fs::write(mp.join("hello.txt"), b"hello world").unwrap();
        std::fs::create_dir(mp.join("d")).unwrap();
        std::fs::write(mp.join("d/payload.bin"), vec![0xCD; 512 * 1024])
            .unwrap();
        mnt.into_loopback()
    };

    let dev = lo.path().to_str().unwrap();
    let out = btrfs_ok(&["rescue", "clear-space-cache", "v1", dev]);
    assert!(
        out.contains("cleared v1 free space cache")
            || out.contains("no v1 free space cache"),
        "expected v1 clear message, got: {out}"
    );

    let check_output = Command::new("btrfs")
        .args(["check", "--readonly", dev])
        .output()
        .expect("failed to run btrfs check");
    if !check_output.status.success() {
        let stderr = String::from_utf8_lossy(&check_output.stderr);
        let stdout = String::from_utf8_lossy(&check_output.stdout);
        panic!(
            "btrfs check failed:\n--- stdout ---\n{stdout}\n--- stderr ---\n{stderr}"
        );
    }

    // Re-mount and verify data is intact.
    let mnt = Mount::with_options(lo, td.path(), &["space_cache=v1"]);
    let mp = mnt.path();
    assert_eq!(std::fs::read(mp.join("hello.txt")).unwrap(), b"hello world");
    assert_eq!(
        std::fs::read(mp.join("d/payload.bin")).unwrap(),
        vec![0xCD; 512 * 1024]
    );
}

#[test]
#[ignore = "requires elevated privileges"]
fn rescue_fix_device_size_shrink() {
    let td = tempdir().unwrap();
    let file = BackingFile::new(td.path(), "disk.img", 512 * 1024 * 1024);
    // Disable BGT to keep the filesystem layout simple. The fresh
    // filesystem only allocates chunks in the first ~250 MiB.
    file.mkfs_with_args(&["-O", "^block-group-tree"]);

    // Truncate the backing file in place. After this, dev_item.total_bytes
    // (still 512 MiB) is larger than the actual file size (256 MiB),
    // and no DEV_EXTENT crosses 256 MiB.
    {
        let f = std::fs::OpenOptions::new()
            .write(true)
            .open(file.path())
            .unwrap();
        f.set_len(256 * 1024 * 1024).unwrap();
    }

    let dev = file.path().to_str().unwrap();
    let out = btrfs_ok(&["rescue", "fix-device-size", dev]);
    assert!(
        out.contains("devid 1: total_bytes")
            && out.contains("superblock total_bytes"),
        "expected fixup messages, got: {out}"
    );

    let check = Command::new("btrfs")
        .args(["check", "--readonly", dev])
        .output()
        .expect("failed to run btrfs check");
    if !check.status.success() {
        panic!(
            "btrfs check failed:\nstdout:\n{}\nstderr:\n{}",
            String::from_utf8_lossy(&check.stdout),
            String::from_utf8_lossy(&check.stderr)
        );
    }

    // Running it again should be a no-op.
    let out2 = btrfs_ok(&["rescue", "fix-device-size", dev]);
    assert!(
        out2.contains("no device size related problem found"),
        "expected no-op message, got: {out2}"
    );
}

#[test]
#[ignore = "requires elevated privileges"]
fn rescue_fix_data_checksum_clean() {
    // Clean filesystem: scan should find no mismatches.
    let td = tempdir().unwrap();
    let file = BackingFile::new(td.path(), "disk.img", 256 * 1024 * 1024);
    file.mkfs_with_args(&["-O", "^block-group-tree"]);
    let lo = LoopbackDevice::new(file);

    let lo = {
        let mnt = Mount::new(lo, td.path());
        let mp = mnt.path();
        std::fs::write(mp.join("a.bin"), vec![0x42u8; 8 * 1024]).unwrap();
        std::fs::write(mp.join("b.bin"), vec![0x99u8; 64 * 1024]).unwrap();
        mnt.into_loopback()
    };

    let dev = lo.path().to_str().unwrap();
    let out = btrfs_ok(&["rescue", "fix-data-checksum", "--readonly", dev]);
    assert!(
        out.contains("no data checksum mismatch found"),
        "expected clean scan, got: {out}"
    );
}

#[test]
#[ignore = "requires elevated privileges"]
fn rescue_fix_data_checksum_repair() {
    use btrfs_disk::{
        reader::filesystem_open,
        tree::{KeyType, TreeBlock},
    };
    use std::io::{Seek, SeekFrom, Write};

    let td = tempdir().unwrap();
    let file = BackingFile::new(td.path(), "disk.img", 256 * 1024 * 1024);
    file.mkfs_with_args(&["-O", "^block-group-tree"]);
    let lo = LoopbackDevice::new(file);

    let lo = {
        let mnt = Mount::new(lo, td.path());
        let mp = mnt.path();
        // A few KiB of distinctive data, large enough to land in a
        // regular (non-inline) extent.
        std::fs::write(mp.join("payload.bin"), vec![0xC3u8; 64 * 1024])
            .unwrap();
        mnt.into_loopback()
    };

    // Walk the csum tree (read-only, via disk crate) to find the
    // first EXTENT_CSUM item and resolve its sector to a physical
    // offset on the backing device.
    let dev_path: PathBuf = lo.path().to_path_buf();
    let (corrupt_logical, corrupt_physical) = {
        let f = std::fs::OpenOptions::new()
            .read(true)
            .open(&dev_path)
            .unwrap();
        let mut open = filesystem_open(f).expect("filesystem_open");
        let csum_root_bytenr = open
            .tree_roots
            .get(&7u64)
            .map(|(b, _)| *b)
            .expect("csum tree root present");

        // DFS until we find a leaf with an EXTENT_CSUM item.
        let mut found: Option<u64> = None;
        let mut stack = vec![csum_root_bytenr];
        while let Some(bytenr) = stack.pop() {
            let block = open
                .reader
                .read_tree_block(bytenr)
                .expect("read tree block");
            match block {
                TreeBlock::Node { ptrs, .. } => {
                    for p in ptrs.into_iter().rev() {
                        stack.push(p.blockptr);
                    }
                }
                TreeBlock::Leaf { items, .. } => {
                    if let Some(item) = items
                        .iter()
                        .find(|i| i.key.key_type == KeyType::ExtentCsum)
                    {
                        found = Some(item.key.offset);
                        break;
                    }
                }
            }
        }
        let logical = found.expect("no EXTENT_CSUM items in csum tree");
        let (_devid, physical) = open
            .reader
            .chunk_cache()
            .resolve(logical)
            .expect("chunk cache should resolve csum'd sector");
        (logical, physical)
    };

    // Overwrite the first 4 KiB at that physical offset with zeros.
    // The original payload (0xC3) won't match the stored csum.
    {
        let mut f = std::fs::OpenOptions::new()
            .write(true)
            .open(&dev_path)
            .unwrap();
        f.seek(SeekFrom::Start(corrupt_physical)).unwrap();
        f.write_all(&[0u8; 4096]).unwrap();
        f.sync_all().unwrap();
    }

    let dev = dev_path.to_str().unwrap();

    // Readonly scan should now flag the corrupted sector.
    let scan = btrfs_ok(&["rescue", "fix-data-checksum", "--readonly", dev]);
    let want = format!("logical={corrupt_logical}");
    assert!(
        scan.contains(&want),
        "expected mismatch report for {want}, got: {scan}"
    );

    // Repair via mirror 1.
    let fix = btrfs_ok(&["rescue", "fix-data-checksum", "--mirror", "1", dev]);
    assert!(
        fix.contains("csum item(s) updated"),
        "expected repair message, got: {fix}"
    );

    // After repair, btrfs check should succeed and a re-scan should
    // be clean.
    let check = Command::new("btrfs")
        .args(["check", "--readonly", dev])
        .output()
        .expect("failed to run btrfs check");
    if !check.status.success() {
        panic!(
            "btrfs check failed:\nstdout:\n{}\nstderr:\n{}",
            String::from_utf8_lossy(&check.stdout),
            String::from_utf8_lossy(&check.stderr)
        );
    }
    let rescan = btrfs_ok(&["rescue", "fix-data-checksum", "--readonly", dev]);
    assert!(
        rescan.contains("no data checksum mismatch found"),
        "expected clean rescan after repair, got: {rescan}"
    );
}