vfsi-c 0.3.5

C API for VFSI vectorized filesystem interfaces
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
//! C API for vfsi, the vectorized filesystem API.
//!
//! The C-facing symbols are intentionally thin: C code works with an opaque
//! `vfsi_fs` handle and byte-oriented `const char *` paths, while all
//! filesystem logic stays in the Rust `vnfs` implementation.
#![allow(unsafe_op_in_unsafe_fn)]
#![allow(non_camel_case_types)]
#![allow(clippy::missing_safety_doc)]

use std::ffi::{CStr, CString, OsString};
use std::os::raw::{c_char, c_int, c_void};
use std::os::unix::ffi::{OsStrExt, OsStringExt};
use std::path::{Component, Path, PathBuf};
use std::sync::atomic::{AtomicI32, Ordering};
use std::sync::{Mutex, MutexGuard};

use vfsi_local::DummyVecFs;
use vfsi_nfs::nfs::NfsVecFs;
use vfsi_smb::SmbVecFs;
use vfsi_sync::{
    AttrMask, ExtentPair, ReadOp, VfAttrs, VfError, VfFile, WriteOp, ERR_EBADF, ERR_NOENT,
    VF_ERR_UNSUPPORTED,
};

/// ABI version implemented by this library.
pub const VFSI_ABI_VERSION: u32 = 3;
/// No error occurred.
pub const VFSI_ERROR_NONE: u32 = 0;
/// A filesystem/backend status was returned.
pub const VFSI_ERROR_FILESYSTEM: u32 = 1;
/// The transport failed without a filesystem status.
pub const VFSI_ERROR_TRANSPORT: u32 = 2;
/// The selected backend does not implement the requested operation.
pub const VFSI_ERROR_UNSUPPORTED: u32 = 3;
/// The C request itself was malformed.
pub const VFSI_ERROR_INVALID_ARGUMENT: u32 = 4;
/// The operation was not submitted because an earlier request was invalid.
pub const VFSI_ERROR_NOT_ATTEMPTED: u32 = 5;
/// The backend batch failed and this element's final state cannot be proven.
pub const VFSI_ERROR_INDETERMINATE: u32 = 6;
/// Fixed capacity of [`vfsi_result::message`], including its trailing NUL.
pub const VFSI_RESULT_MESSAGE_SIZE: usize = 160;
const C_INDEX_UNKNOWN: usize = usize::MAX;
pub const VFSI_ATTR_MODE: u32 = 1 << 0;
pub const VFSI_ATTR_SIZE: u32 = 1 << 1;
pub const VFSI_ATTR_NLINK: u32 = 1 << 2;
pub const VFSI_ATTR_FILEID: u32 = 1 << 3;
pub const VFSI_ATTR_BLOCKS: u32 = 1 << 4;
pub const VFSI_ATTR_UID: u32 = 1 << 5;
pub const VFSI_ATTR_GID: u32 = 1 << 6;
pub const VFSI_ATTR_RDEV: u32 = 1 << 7;
pub const VFSI_ATTR_ATIME: u32 = 1 << 8;
pub const VFSI_ATTR_MTIME: u32 = 1 << 9;
pub const VFSI_ATTR_CTIME: u32 = 1 << 10;
/// The backend will currently attempt server-side COPY.
pub const VFSI_CAP_SERVER_COPY: u64 = 1 << 0;
/// The backend reports and honors Unix metadata such as modes and ownership.
pub const VFSI_CAP_POSIX_METADATA: u64 = 1 << 1;
/// The backend supports symbolic links.
pub const VFSI_CAP_SYMLINKS: u64 = 1 << 2;
/// The backend supports hard links.
pub const VFSI_CAP_HARDLINKS: u64 = 1 << 3;
/// The backend accepts arbitrary non-UTF-8 Unix path bytes.
pub const VFSI_CAP_NON_UTF8_PATHS: u64 = 1 << 4;
/// The backend implements no-follow metadata operations.
pub const VFSI_CAP_LSTAT: u64 = 1 << 5;

const _: () = assert!(VFSI_CAP_POSIX_METADATA == vfsi_sync::VF_CAP_POSIX_METADATA);
const _: () = assert!(VFSI_CAP_SYMLINKS == vfsi_sync::VF_CAP_SYMLINKS);
const _: () = assert!(VFSI_CAP_HARDLINKS == vfsi_sync::VF_CAP_HARDLINKS);
const _: () = assert!(VFSI_CAP_NON_UTF8_PATHS == vfsi_sync::VF_CAP_NON_UTF8_PATHS);
const _: () = assert!(VFSI_CAP_LSTAT == vfsi_sync::VF_CAP_LSTAT);

macro_rules! ffi_guard {
    ($fallback:expr, $body:block) => {{
        match std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| $body)) {
            Ok(value) => value,
            Err(_) => $fallback,
        }
    }};
}

macro_rules! fail_batch {
    ($results:expr, $failure:expr, $submitted:expr) => {{
        let failure = $failure;
        fail_results($results, failure, $submitted);
        return failure;
    }};
}

/// Opaque filesystem handle owned by C.
pub struct vfsi_fs {
    fs: Mutex<Box<dyn BindingBackend>>,
    files: Mutex<std::collections::HashMap<i32, VfFile>>,
    next_fd: AtomicI32,
    /// Kernel mountpoint used by application-visible paths.
    mountpoint: PathBuf,
    /// Backend path corresponding to `mountpoint`.
    backend_root: PathBuf,
}

/// Attributes returned by [`vfsi_stat`] and passed to listdir callbacks.
#[repr(C)]
#[derive(Clone, Copy)]
pub struct vfsi_attrs {
    /// Size of this structure, for forward-compatible extension.
    pub struct_size: u32,
    /// ABI version used to populate this structure.
    pub abi_version: u32,
    pub ftype: u32,
    pub mode: u32,
    pub size: u64,
    pub nlink: u32,
    pub fileid: u64,
    pub uid: u32,
    pub gid: u32,
    pub blocks: u64,
    pub atime_sec: i64,
    pub atime_nsec: u32,
    pub mtime_sec: i64,
    pub mtime_nsec: u32,
    pub ctime_sec: i64,
    pub ctime_nsec: u32,
}

/// Uniform ABI-v3 result for scalar and vector operations.
///
/// `index` is the completed count on success, the failing operation index on
/// an attributable error, or `VFSI_INDEX_UNKNOWN`. Vector calls also populate
/// a caller-owned result per element;
/// after a submitted concurrent batch fails, every non-failing element is
/// marked indeterminate because it may already have completed. `err_no`
/// retains the backend status while `category` is portable across protocols.
#[repr(C)]
#[derive(Clone, Copy)]
pub struct vfsi_result {
    pub struct_size: u32,
    pub abi_version: u32,
    pub index: usize,
    pub category: u32,
    pub err_no: u32,
    pub message: [c_char; VFSI_RESULT_MESSAGE_SIZE],
}

#[repr(C)]
#[derive(Clone, Copy)]
pub struct vfsi_open_op {
    pub path: *const c_char,
    pub flags: c_int,
    pub mode: u32,
    pub fd: c_int,
}

#[repr(C)]
#[derive(Clone, Copy)]
pub struct vfsi_stat_op {
    pub path: *const c_char,
    pub attrs: vfsi_attrs,
}

#[repr(C)]
#[derive(Clone, Copy)]
pub struct vfsi_setattr_op {
    pub path: *const c_char,
    pub mask: u32,
    pub mode: u32,
    pub size: u64,
    pub atime_sec: i64,
    pub atime_nsec: u32,
    pub mtime_sec: i64,
    pub mtime_nsec: u32,
}

#[repr(C)]
#[derive(Clone, Copy)]
pub struct vfsi_pread_op {
    pub fd: c_int,
    pub buf: *mut c_void,
    pub len: usize,
    pub offset: u64,
    pub got: usize,
}

#[repr(C)]
#[derive(Clone, Copy)]
pub struct vfsi_pwrite_op {
    pub fd: c_int,
    pub buf: *const c_void,
    pub len: usize,
    pub offset: u64,
    pub wrote: usize,
}

#[repr(C)]
#[derive(Clone, Copy)]
pub struct vfsi_mkdir_op {
    pub path: *const c_char,
    pub mode: u32,
}

#[repr(C)]
#[derive(Clone, Copy)]
pub struct vfsi_rename_op {
    pub oldpath: *const c_char,
    pub newpath: *const c_char,
}

#[repr(C)]
#[derive(Clone, Copy)]
pub struct vfsi_copy_op {
    pub src: *const c_char,
    pub src_offset: u64,
    pub dst: *const c_char,
    pub dst_offset: u64,
    pub length: u64,
    pub to_eof: bool,
}

impl vfsi_attrs {
    fn from_vf(a: &VfAttrs) -> vfsi_attrs {
        vfsi_attrs {
            struct_size: std::mem::size_of::<vfsi_attrs>() as u32,
            abi_version: VFSI_ABI_VERSION,
            ftype: vfsi_sync::file_type_to_nfs(&a.ftype),
            mode: a.mode,
            size: a.size,
            nlink: a.nlink,
            fileid: a.fileid,
            uid: a.uid,
            gid: a.gid,
            blocks: a.blocks,
            atime_sec: a.atime_sec,
            atime_nsec: a.atime_nsec,
            mtime_sec: a.mtime_sec,
            mtime_nsec: a.mtime_nsec,
            ctime_sec: a.ctime_sec,
            ctime_nsec: a.ctime_nsec,
        }
    }
}

impl vfsi_result {
    fn base(index: usize, category: u32, err_no: u32, message: &str) -> Self {
        let mut result = Self {
            struct_size: std::mem::size_of::<Self>() as u32,
            abi_version: VFSI_ABI_VERSION,
            index,
            category,
            err_no,
            message: [0; VFSI_RESULT_MESSAGE_SIZE],
        };
        let bytes = message.as_bytes();
        let len = bytes.len().min(VFSI_RESULT_MESSAGE_SIZE - 1);
        for (dst, src) in result.message[..len].iter_mut().zip(&bytes[..len]) {
            *dst = *src as c_char;
        }
        result
    }

    fn success(completed: usize) -> Self {
        Self::base(completed, VFSI_ERROR_NONE, 0, "")
    }

    fn item_success(index: usize) -> Self {
        Self::base(index, VFSI_ERROR_NONE, 0, "")
    }

    fn invalid(index: usize, message: &str) -> Self {
        Self::base(
            index,
            VFSI_ERROR_INVALID_ARGUMENT,
            libc::EINVAL as u32,
            message,
        )
    }

    fn panic() -> Self {
        Self::base(
            0,
            VFSI_ERROR_TRANSPORT,
            libc::EIO as u32,
            "panic across FFI",
        )
    }

    fn from_error(error: VfError) -> Self {
        match error {
            VfError::Op { index, err_no, .. } => Self::base(
                index,
                if err_no == VF_ERR_UNSUPPORTED {
                    VFSI_ERROR_UNSUPPORTED
                } else {
                    VFSI_ERROR_FILESYSTEM
                },
                err_no,
                "",
            ),
            VfError::OpUnattributed { err_no, .. } => Self::base(
                C_INDEX_UNKNOWN,
                if err_no == VF_ERR_UNSUPPORTED {
                    VFSI_ERROR_UNSUPPORTED
                } else {
                    VFSI_ERROR_FILESYSTEM
                },
                err_no,
                "",
            ),
            VfError::Transport { index, message, .. } => Self::base(
                index.unwrap_or(C_INDEX_UNKNOWN),
                VFSI_ERROR_TRANSPORT,
                vfsi_sync::VF_ERR_RPC,
                &message,
            ),
            _ => Self::base(0, VFSI_ERROR_TRANSPORT, libc::EIO as u32, "unknown error"),
        }
    }
}

// Keeping the error inline avoids allocating while crossing the C ABI; the
// fixed-size result is copied directly into the caller's return value.
#[allow(clippy::result_large_err)]
unsafe fn result_array<'a>(
    results: *mut vfsi_result,
    count: usize,
) -> Result<&'a mut [vfsi_result], vfsi_result> {
    if results.is_null() {
        return Err(vfsi_result::invalid(0, "null result array"));
    }
    let results = std::slice::from_raw_parts_mut(results, count);
    for (index, result) in results.iter_mut().enumerate() {
        *result = vfsi_result::base(index, VFSI_ERROR_NOT_ATTEMPTED, 0, "not attempted");
    }
    Ok(results)
}

fn complete_results(results: &mut [vfsi_result]) {
    for (index, result) in results.iter_mut().enumerate() {
        *result = vfsi_result::item_success(index);
    }
}

fn fail_results(results: &mut [vfsi_result], failure: vfsi_result, submitted: bool) {
    if submitted {
        for (index, result) in results.iter_mut().enumerate() {
            *result = vfsi_result::base(
                index,
                VFSI_ERROR_INDETERMINATE,
                0,
                "batch failed; completion is indeterminate",
            );
        }
    }
    if failure.index != C_INDEX_UNKNOWN {
        if let Some(result) = results.get_mut(failure.index) {
            *result = failure;
        }
    }
}

fn confirmed_close_prefix(error: &VfError, count: usize) -> usize {
    if error.is_transport() {
        0
    } else {
        error.index().unwrap_or(0).min(count)
    }
}

pub type vfsi_listdir_cb = Option<
    unsafe extern "C" fn(
        name: *const c_char,
        attrs: *const vfsi_attrs,
        userdata: *mut c_void,
    ) -> bool,
>;

pub type vfsi_listdirv_cb = Option<
    unsafe extern "C" fn(
        dir: *const c_char,
        name: *const c_char,
        attrs: *const vfsi_attrs,
        userdata: *mut c_void,
    ) -> bool,
>;

pub type vfsi_read_paths_cb = Option<
    unsafe extern "C" fn(
        path: *const c_char,
        data: *const u8,
        len: usize,
        userdata: *mut c_void,
    ) -> bool,
>;

/// Aggregate limits for complete shallow vector listings. Zero is a zero
/// budget; SIZE_MAX explicitly opts out. MODE is always requested.
#[repr(C)]
pub struct vfsi_listing_options {
    pub max_entries: usize,
    pub max_path_bytes: usize,
    pub attributes: u32,
}
/// Complete=1, stopped=2, not completed=0. Empty directories are explicitly
/// complete with zero delivered entries. Failure leaves every result incomplete.
#[repr(C)]
#[derive(Clone, Copy, Default)]
pub struct vfsi_listing_result {
    pub completion: u32,
    pub delivered: usize,
}
pub type vfsi_indexed_listdir_cb = Option<
    unsafe extern "C" fn(
        usize,
        *const c_char,
        *const c_char,
        *const vfsi_attrs,
        *mut c_void,
    ) -> bool,
>;

/// Complete bounded vector listings, with callbacks outside backend locks.
/// Collect the bounded cohort before delivery, so callers may safely fall back
/// on a listing error without mixing a partial snapshot into ordinary scanning.
/// Budgets include duplicate operands. Results are associated with input indices.
/// A false callback stops delivery successfully and is distinguishable from EOF.
/// A callback stop marks the entire cohort stopped, even if an earlier empty
/// directory had no entries to deliver. Requested but absent attributes fail
/// with ENOTSUP before delivery; applications must not fabricate stat values.
/// Operand planning is additionally capped by the default directory entry/path
/// limits, independently of the configured response quotas.
/// Backend first-page fetches use bounded directory cohorts; aggregate quotas
/// and deferred callback delivery span all cohorts, including duplicate inputs.
///
/// # Safety
/// `fs` must be a live handle. `dirs` and `results` must hold `count` elements,
/// and each directory must be NUL-terminated. `options` must be readable for the
/// call. Callback strings/attributes are borrowed only during the invocation.
/// The callback must not free `fs` or mutate the input/result arrays.
#[no_mangle]
pub unsafe extern "C" fn vfsi_listdirs(
    fs: *mut vfsi_fs,
    dirs: *const *const c_char,
    count: usize,
    options: *const vfsi_listing_options,
    cb: vfsi_indexed_listdir_cb,
    userdata: *mut c_void,
    results: *mut vfsi_listing_result,
) -> c_int {
    ffi_guard!(libc::EIO, {
        let (Some(fs), Some(options), Some(cb)) = (fs.as_ref(), options.as_ref(), cb) else {
            return libc::EINVAL;
        };
        if count == 0 {
            return 0;
        }
        if dirs.is_null() || results.is_null() {
            return libc::EINVAL;
        }
        // Caller owns count elements in both arrays.
        let results = std::slice::from_raw_parts_mut(results, count);
        results.fill(vfsi_listing_result::default());
        let Some(fields) = AttrMask::from_bits(options.attributes) else {
            return libc::EINVAL;
        };
        // Bound planning storage as well as returned entries; empty inputs can
        // otherwise bypass every payload quota.
        if count > vfsi_sync::DEFAULT_DIRECTORY_MAX_ENTRIES {
            return libc::EFBIG;
        }
        let mut planning_bytes = 0usize;
        // Check borrowed input spellings before allocating their owned copies.
        for i in 0..count {
            let pointer = *dirs.add(i);
            if pointer.is_null() {
                return libc::EINVAL;
            }
            let length = CStr::from_ptr(pointer).to_bytes().len();
            let Some(total) = planning_bytes.checked_add(length) else {
                return libc::EFBIG;
            };
            if total > vfsi_sync::DEFAULT_DIRECTORY_MAX_PATH_BYTES {
                return libc::EFBIG;
            }
            planning_bytes = total;
        }
        let mut paths = Vec::with_capacity(count);
        let mut index = std::collections::HashMap::<PathBuf, Vec<usize>>::new();
        for i in 0..count {
            let Some(path) = cstr_path(*dirs.add(i)) else {
                return libc::EINVAL;
            };
            let vpath = match vpath_for(fs, &path) {
                Ok(path) => path,
                Err(error) => return vf_code(&error),
            };
            let Some(total) = planning_bytes.checked_add(vpath.as_os_str().len()) else {
                return libc::EFBIG;
            };
            if total > vfsi_sync::DEFAULT_DIRECTORY_MAX_PATH_BYTES {
                return libc::EFBIG;
            }
            planning_bytes = total;
            index.entry(vpath).or_default().push(i);
            paths.push(path);
        }
        let refs: Vec<&Path> = index.keys().map(PathBuf::as_path).collect();
        let mut rows = Vec::new();
        let mut entries = 0usize;
        let mut bytes = 0usize;
        let mut overflow = false;
        let result = match lock_or_io(&fs.fs) {
            Ok(mut backend) => {
                // Native engines can retain every root's first page before
                // invoking cb. Bound that work even when output quotas are tiny.
                const DIRECTORY_COHORT: usize = 32;
                let mut result = Ok(());
                for cohort in refs.chunks(DIRECTORY_COHORT) {
                    // Never pass zero: native zero means unlimited enumeration.
                    let probe = options
                        .max_entries
                        .saturating_sub(entries)
                        .saturating_add(1);
                    result = backend.vlistdirs_impl(
                        cohort,
                        fields | AttrMask::MODE,
                        probe,
                        false,
                        &mut |attrs, dir| {
                            let Some(indices) = index.get(dir) else {
                                overflow = true;
                                return false;
                            };
                            let next_entries = entries.checked_add(indices.len());
                            let next_bytes = attrs
                                .file
                                .path()
                                .and_then(|path| path.as_os_str().len().checked_mul(indices.len()))
                                .and_then(|n| bytes.checked_add(n));
                            if next_entries.is_none_or(|n| n > options.max_entries)
                                || next_bytes.is_none_or(|n| n > options.max_path_bytes)
                            {
                                overflow = true;
                                return false;
                            }
                            entries = next_entries.unwrap_or_default();
                            bytes = next_bytes.unwrap_or_default();
                            rows.push((attrs.clone(), dir.to_path_buf()));
                            true
                        },
                    );
                    if result.is_err() || overflow {
                        break;
                    }
                }
                result
            }
            Err(error) => Err(error),
        };
        if let Err(error) = result {
            return vf_code(&error);
        }
        if overflow {
            return libc::EFBIG;
        }
        // Validate the entire snapshot before invoking user callbacks. A bad
        // row must not leave applications with a seemingly complete prefix.
        let mut prepared = Vec::with_capacity(rows.len());
        for (attrs, dir) in rows {
            if !attrs.returned.contains(fields | AttrMask::MODE) {
                return libc::ENOTSUP;
            }
            let Some(name) = attrs
                .file
                .path()
                .and_then(|p| p.file_name())
                .and_then(|name| cstr_from_os(name.as_bytes()))
            else {
                return libc::EIO;
            };
            prepared.push((vfsi_attrs::from_vf(&attrs), dir, name));
        }
        let paths: Vec<_> = paths
            .iter()
            .map(|path| cstr_from_os(path.as_os_str().as_bytes()))
            .collect();
        if paths.iter().any(Option::is_none) {
            return libc::EINVAL;
        }
        for result in results.iter_mut() {
            result.completion = 1;
        }
        for (attrs, dir, name) in prepared {
            for &i in &index[&dir] {
                let path = paths[i].as_ref().expect("validated C paths");
                results[i].delivered += 1;
                if !cb(i, path.as_ptr(), name.as_ptr(), &attrs, userdata) {
                    for result in results.iter_mut() {
                        result.completion = 2;
                    }
                    return 0;
                }
            }
        }
        0
    })
}

pub type vfsi_read_stream_cb = Option<
    unsafe extern "C" fn(
        path: *const c_char,
        index: usize,
        offset: u64,
        data: *const u8,
        len: usize,
        eof: bool,
        userdata: *mut c_void,
    ) -> bool,
>;

/// Return the ABI version implemented by the loaded library.
#[no_mangle]
pub extern "C" fn vfsi_abi_version() -> u32 {
    ffi_guard!(0, { VFSI_ABI_VERSION })
}

/// Return the negotiated NFS minor version, or zero for a non-NFS/invalid
/// handle.
#[allow(deprecated)]
#[no_mangle]
pub unsafe extern "C" fn vfsi_nfs_minorversion(fs: *const vfsi_fs) -> u32 {
    ffi_guard!(0, {
        let Some(fs) = fs.as_ref() else {
            return 0;
        };
        fs.fs
            .lock()
            .ok()
            .and_then(|backend| backend.nfs_minorversion())
            .unwrap_or(0)
    })
}

/// Return the negotiated SMB dialect revision (`0x0202` through `0x0311`),
/// or zero for a non-SMB/invalid handle.
#[allow(deprecated)]
#[no_mangle]
pub unsafe extern "C" fn vfsi_smb_dialect(fs: *const vfsi_fs) -> u16 {
    ffi_guard!(0, {
        let Some(fs) = fs.as_ref() else {
            return 0;
        };
        fs.fs
            .lock()
            .ok()
            .and_then(|backend| backend.smb_dialect())
            .unwrap_or(0)
    })
}

/// Return the current `VFSI_CAP_*` capability bitset.
#[no_mangle]
pub unsafe extern "C" fn vfsi_capabilities(fs: *const vfsi_fs) -> u64 {
    ffi_guard!(0, {
        let Some(fs) = fs.as_ref() else {
            return 0;
        };
        fs.fs
            .lock()
            .map(|backend| backend.capability_bits())
            .unwrap_or(0)
    })
}

fn mask() -> AttrMask {
    AttrMask::MODE
        | AttrMask::SIZE
        | AttrMask::NLINK
        | AttrMask::FILEID
        | AttrMask::BLOCKS
        | AttrMask::UID
        | AttrMask::GID
        | AttrMask::ATIME
        | AttrMask::MTIME
        | AttrMask::CTIME
}

fn bounded_listdir(
    fs: &vfsi_fs,
    path: &Path,
    fields: AttrMask,
    max_entries: usize,
    max_path_bytes: usize,
) -> Result<Vec<VfAttrs>, VfError> {
    let probe = if max_entries == usize::MAX {
        0
    } else {
        max_entries.saturating_add(1)
    };
    collect_bounded_entries(max_entries, max_path_bytes, |cb| {
        lock_or_io(&fs.fs)?.visit_dir_impl(path, fields, probe, cb)
    })
}

fn collect_bounded_entries(
    max_entries: usize,
    max_path_bytes: usize,
    visit: impl FnOnce(&mut dyn FnMut(&VfAttrs) -> bool) -> Result<(), VfError>,
) -> Result<Vec<VfAttrs>, VfError> {
    let mut entries = Vec::new();
    let mut bytes = 0usize;
    let mut overflow = false;
    visit(&mut |entry| {
        let next = bytes.checked_add(entry.file.path().map_or(0, |p| p.as_os_str().len()));
        if entries.len() >= max_entries || next.is_none_or(|n| n > max_path_bytes) {
            overflow = true;
            return false;
        }
        bytes = next.unwrap_or_default();
        entries.push(entry.clone());
        true
    })?;
    if overflow {
        return Err(VfError::client(0, libc::EFBIG as u32));
    }
    Ok(entries)
}

fn vf_code(e: &VfError) -> c_int {
    match e {
        VfError::Op { err_no, .. } | VfError::OpUnattributed { err_no, .. } => *err_no as c_int,
        VfError::Transport { .. } => libc::EIO,
        _ => e.err_no() as c_int,
    }
}

fn lock_or_io<T>(mutex: &Mutex<T>) -> Result<MutexGuard<'_, T>, VfError> {
    mutex
        .lock()
        .map_err(|_| VfError::failure(0, libc::EIO as u32))
}

fn cstr_path(path: *const c_char) -> Option<PathBuf> {
    if path.is_null() {
        return None;
    }
    // SAFETY: C callers must pass a NUL-terminated path string.
    let bytes = unsafe { CStr::from_ptr(path) }.to_bytes();
    Some(PathBuf::from(OsString::from_vec(bytes.to_vec())))
}

fn cstr_from_os(bytes: &[u8]) -> Option<CString> {
    CString::new(bytes).ok()
}

fn cstr_utf8(value: *const c_char) -> Option<String> {
    if value.is_null() {
        return None;
    }
    // SAFETY: C callers must pass a NUL-terminated string which remains valid
    // for the duration of the call.
    unsafe { CStr::from_ptr(value) }
        .to_str()
        .ok()
        .map(str::to_owned)
}

fn path_for(fs: &vfsi_fs, path: &Path) -> Option<PathBuf> {
    let rel = path.strip_prefix(&fs.mountpoint).ok()?;
    let mut mapped = fs.backend_root.clone();
    for component in rel.components() {
        match component {
            Component::Normal(part) => mapped.push(part),
            Component::CurDir => {}
            Component::ParentDir | Component::RootDir | Component::Prefix(_) => return None,
        }
    }
    Some(mapped)
}

fn make_fs(
    fs: Box<dyn BindingBackend>,
    mountpoint: PathBuf,
    backend_root: PathBuf,
) -> *mut vfsi_fs {
    Box::into_raw(Box::new(vfsi_fs {
        fs: Mutex::new(fs),
        files: Mutex::new(std::collections::HashMap::new()),
        next_fd: AtomicI32::new(1),
        mountpoint,
        backend_root,
    }))
}

fn insert_c_file(
    fs: &vfsi_fs,
    files: &mut std::collections::HashMap<i32, VfFile>,
    file: VfFile,
) -> Result<i32, VfError> {
    for _ in 0..i32::MAX {
        let fd = loop {
            let current = fs.next_fd.load(Ordering::Relaxed);
            let next = current.checked_add(1).unwrap_or(1);
            if fs
                .next_fd
                .compare_exchange_weak(current, next, Ordering::Relaxed, Ordering::Relaxed)
                .is_ok()
            {
                break current;
            }
        };
        if let std::collections::hash_map::Entry::Vacant(entry) = files.entry(fd) {
            entry.insert(file);
            return Ok(fd);
        }
    }
    Err(VfError::failure(0, libc::EMFILE as u32))
}

fn vpath_for(fs: &vfsi_fs, path: &std::path::Path) -> Result<PathBuf, VfError> {
    path_for(fs, path).ok_or_else(|| VfError::failure(0, ERR_NOENT))
}

/// Create a local-directory vfsi backend rooted at `root`.
#[no_mangle]
pub unsafe extern "C" fn vfsi_dummy_open(root: *const c_char, out: *mut *mut vfsi_fs) -> c_int {
    ffi_guard!(libc::EIO, {
        if root.is_null() || out.is_null() {
            return libc::EINVAL;
        }
        let Some(root) = cstr_path(root) else {
            return libc::EINVAL;
        };
        let fs = match DummyVecFs::try_new(root) {
            Ok(fs) => Box::new(fs) as Box<dyn BindingBackend>,
            Err(error) => return error.err_no() as c_int,
        };
        *out = make_fs(fs, PathBuf::from("/"), PathBuf::from("/"));
        0
    })
}

/// Create a local-directory vfsi backend rooted at `root`, treating
/// `mountpoint` as the kernel-visible root of the same directory. Callers can
/// pass ordinary kernel paths under `mountpoint`, which are mapped to `/`-rooted
/// vfsi paths before they reach the backend.
#[no_mangle]
pub unsafe extern "C" fn vfsi_dummy_open_mount(
    root: *const c_char,
    mountpoint: *const c_char,
    out: *mut *mut vfsi_fs,
) -> c_int {
    ffi_guard!(libc::EIO, {
        if root.is_null() || mountpoint.is_null() || out.is_null() {
            return libc::EINVAL;
        }
        let (Some(root), Some(mountpoint)) = (cstr_path(root), cstr_path(mountpoint)) else {
            return libc::EINVAL;
        };
        let fs = match DummyVecFs::try_new(root) {
            Ok(fs) => Box::new(fs) as Box<dyn BindingBackend>,
            Err(error) => return error.err_no() as c_int,
        };
        *out = make_fs(fs, mountpoint, PathBuf::from("/"));
        0
    })
}

/// Connect to an NFSv4 server at `host` and open the export root.
/// Negotiate NFSv4.2, falling back to NFSv4.1.
#[no_mangle]
pub unsafe extern "C" fn vfsi_nfs_open(host: *const c_char, out: *mut *mut vfsi_fs) -> c_int {
    ffi_guard!(libc::EIO, {
        if host.is_null() || out.is_null() {
            return libc::EINVAL;
        }
        // SAFETY: C callers must pass a NUL-terminated host string.
        let Ok(host) = unsafe { CStr::from_ptr(host) }.to_str() else {
            return libc::EINVAL;
        };
        match NfsVecFs::connect(host)
            .map(|f| Box::new(f) as Box<dyn BindingBackend>)
            .map_err(|e| vf_code(&e))
        {
            Ok(fs) => {
                *out = make_fs(fs, PathBuf::from("/"), PathBuf::from("/"));
                0
            }
            Err(code) => code,
        }
    })
}

/// Connect using an explicit supported NFS minor version (1 or 2).
#[no_mangle]
pub unsafe extern "C" fn vfsi_nfs_open_minor(
    host: *const c_char,
    minorversion: u32,
    out: *mut *mut vfsi_fs,
) -> c_int {
    ffi_guard!(libc::EIO, {
        if host.is_null() || out.is_null() || !matches!(minorversion, 1 | 2) {
            return libc::EINVAL;
        }
        let Ok(host) = unsafe { CStr::from_ptr(host) }.to_str() else {
            return libc::EINVAL;
        };
        match NfsVecFs::connect_minor(host, minorversion)
            .map(|f| Box::new(f) as Box<dyn BindingBackend>)
            .map_err(|e| vf_code(&e))
        {
            Ok(fs) => {
                *out = make_fs(fs, PathBuf::from("/"), PathBuf::from("/"));
                0
            }
            Err(code) => code,
        }
    })
}

/// Connect to an NFSv4.1/4.2 server and treat `mountpoint` (a local kernel mount
/// path) as the vfsi root. Callers can then pass ordinary kernel paths.
#[no_mangle]
pub unsafe extern "C" fn vfsi_nfs_open_mount(
    host: *const c_char,
    mountpoint: *const c_char,
    out: *mut *mut vfsi_fs,
) -> c_int {
    ffi_guard!(libc::EIO, {
        unsafe { vfsi_nfs_open_mount_export(host, c"/".as_ptr(), mountpoint, out) }
    })
}

/// Discover a Linux NFS mount and inherit its version, port and security.
/// `path` must be an absolute directory. Ordinary paths beneath it are mapped
/// to the corresponding remote directory. No AUTH_SYS downgrade or kernel
/// fallback is performed; direct access does not share the kernel cache.
#[no_mangle]
pub unsafe extern "C" fn vfsi_nfs_from_mount(path: *const c_char, out: *mut *mut vfsi_fs) -> c_int {
    ffi_guard!(libc::EIO, {
        if out.is_null() {
            return libc::EINVAL;
        }
        *out = std::ptr::null_mut();
        let Some(path) = cstr_path(path) else {
            return libc::EINVAL;
        };
        match vfsi_nfs::nfs::NfsClientBuilder::from_mount(&path)
            .and_then(|builder| builder.connect())
        {
            Ok(backend) => {
                *out = make_fs(Box::new(backend), path, PathBuf::from("/"));
                0
            }
            Err(error) => vf_code(&error),
        }
    })
}

/// Resource policy for an incremental tree traversal. Zero is a zero limit,
/// not unlimited. Set SIZE_MAX explicitly to opt out of a limit.
#[repr(C)]
#[derive(Clone, Copy)]
pub struct vfsi_walk_options {
    pub max_entries: usize,
    pub max_path_bytes: usize,
    pub max_depth: usize,
    pub attributes: u32,
    pub sort_by_name: bool,
}
/// Event kinds: 0=enter directory, 1=entry, 2=leave directory.
/// Return 0=continue, 1=prune directory, 2=stop. Arguments are borrowed.
pub type vfsi_walk_cb =
    Option<unsafe extern "C" fn(*const c_char, u32, usize, *const vfsi_attrs, *mut c_void) -> u32>;

/// Incremental no-follow traversal. Callbacks run outside the filesystem lock.
/// Pruned directories are never listed. Errors can follow delivered events;
/// callers must not replay side-effectful callbacks through another backend.
#[no_mangle]
pub unsafe extern "C" fn vfsi_walk(
    fs: *mut vfsi_fs,
    root: *const c_char,
    options: *const vfsi_walk_options,
    cb: vfsi_walk_cb,
    userdata: *mut c_void,
) -> c_int {
    ffi_guard!(libc::EIO, {
        let (Some(fs), Some(root), Some(options), Some(cb)) =
            (fs.as_ref(), cstr_path(root), options.as_ref(), cb)
        else {
            return libc::EINVAL;
        };
        let Some(fields) = AttrMask::from_bits(options.attributes) else {
            return libc::EINVAL;
        };
        let fields = fields | AttrMask::MODE;
        let result = (|| -> Result<(), VfError> {
            let path = vpath_for(fs, &root)?;
            let root_attrs = lock_or_io(&fs.fs)?.lstat_impl(&path)?;
            let metadata = vfsi_sync::metadata_from_attrs(root_attrs);
            let walk_options = vnfs::WalkOptions::new()
                .max_entries(options.max_entries)
                .max_path_bytes(options.max_path_bytes)
                .max_depth(options.max_depth);
            vfsi_sync::walk_events(
                vnfs::DirEntry::new(path, metadata),
                walk_options,
                options.sort_by_name,
                |path, limits| {
                    let entries = bounded_listdir(
                        fs,
                        path,
                        fields,
                        limits.entry_limit(),
                        limits.path_byte_limit(),
                    )?;
                    entries
                        .into_iter()
                        .map(|attrs| {
                            let path = attrs
                                .file
                                .path()
                                .ok_or_else(|| VfError::client(0, libc::EIO as u32))?
                                .to_path_buf();
                            Ok(vnfs::DirEntry::new(
                                path,
                                vfsi_sync::metadata_from_attrs(attrs),
                            ))
                        })
                        .collect()
                },
                |event| {
                    let relative = event
                        .entry
                        .path()
                        .strip_prefix(&fs.backend_root)
                        .map_err(|_| VfError::client(0, libc::EINVAL as u32))?;
                    let path = CString::new(fs.mountpoint.join(relative).as_os_str().as_bytes())
                        .map_err(|_| VfError::client(0, libc::EINVAL as u32))?;
                    let attrs = attrs_from_metadata(event.entry.attrs());
                    let kind = match event.kind {
                        vnfs::WalkEventKind::Enter => 0,
                        vnfs::WalkEventKind::Entry => 1,
                        vnfs::WalkEventKind::Leave => 2,
                    };
                    match cb(path.as_ptr(), kind, event.depth, &attrs, userdata) {
                        0 => Ok(vnfs::WalkControl::Continue),
                        1 => Ok(vnfs::WalkControl::SkipSubtree),
                        2 => Ok(vnfs::WalkControl::Stop),
                        _ => Err(VfError::client(0, libc::EINVAL as u32)),
                    }
                },
            )?;
            Ok(())
        })();
        result.map_or_else(|error| vf_code(&error), |_| 0)
    })
}

fn attrs_from_metadata(metadata: &vnfs::Attrs) -> vfsi_attrs {
    fn time(value: Option<std::time::SystemTime>) -> (i64, u32) {
        value
            .and_then(|v| match v.duration_since(std::time::UNIX_EPOCH) {
                Ok(d) => i64::try_from(d.as_secs())
                    .ok()
                    .map(|s| (s, d.subsec_nanos())),
                Err(e) => {
                    let d = e.duration();
                    i64::try_from(d.as_secs()).ok().and_then(|s| {
                        if d.subsec_nanos() == 0 {
                            s.checked_neg().map(|s| (s, 0))
                        } else {
                            s.checked_neg()
                                .and_then(|s| s.checked_sub(1))
                                .map(|s| (s, 1_000_000_000 - d.subsec_nanos()))
                        }
                    })
                }
            })
            .unwrap_or_default()
    }
    let (atime_sec, atime_nsec) = time(metadata.accessed());
    let (mtime_sec, mtime_nsec) = time(metadata.modified());
    let (ctime_sec, ctime_nsec) = time(metadata.changed());
    vfsi_attrs {
        struct_size: std::mem::size_of::<vfsi_attrs>() as u32,
        abi_version: VFSI_ABI_VERSION,
        ftype: vfsi_sync::file_type_to_nfs(&metadata.file_type()),
        mode: metadata.mode().unwrap_or_default() & 0o7777,
        size: metadata.len(),
        nlink: metadata.nlink().unwrap_or_default(),
        fileid: metadata.file_id().unwrap_or_default(),
        blocks: metadata.blocks().unwrap_or_default(),
        uid: metadata.uid().unwrap_or_default(),
        gid: metadata.gid().unwrap_or_default(),
        atime_sec,
        atime_nsec,
        mtime_sec,
        mtime_nsec,
        ctime_sec,
        ctime_nsec,
    }
}

/// Connect to an NFSv4.1/4.2 server, mapping a local kernel `mountpoint` to the
/// server-side `export_root` beneath the NFSv4 pseudo-root.
#[no_mangle]
pub unsafe extern "C" fn vfsi_nfs_open_mount_export(
    host: *const c_char,
    export_root: *const c_char,
    mountpoint: *const c_char,
    out: *mut *mut vfsi_fs,
) -> c_int {
    ffi_guard!(libc::EIO, {
        if host.is_null() || export_root.is_null() || mountpoint.is_null() || out.is_null() {
            return libc::EINVAL;
        }
        let Ok(host) = unsafe { CStr::from_ptr(host) }.to_str() else {
            return libc::EINVAL;
        };
        let (Some(export_root), Some(mountpoint)) = (cstr_path(export_root), cstr_path(mountpoint))
        else {
            return libc::EINVAL;
        };
        if !export_root.is_absolute() || !mountpoint.is_absolute() {
            return libc::EINVAL;
        }
        if export_root
            .components()
            .any(|c| matches!(c, Component::ParentDir))
        {
            return libc::EINVAL;
        }
        match NfsVecFs::connect(host)
            .map(|f| Box::new(f) as Box<dyn BindingBackend>)
            .map_err(|e| vf_code(&e))
        {
            Ok(fs) => {
                *out = make_fs(fs, mountpoint, export_root);
                0
            }
            Err(code) => code,
        }
    })
}

/// Connect to an SMB2/3 share. `server` may omit port 445; empty username and
/// password strings request guest access. Paths are rooted at the share root.
#[no_mangle]
pub unsafe extern "C" fn vfsi_smb_open(
    server: *const c_char,
    share: *const c_char,
    username: *const c_char,
    password: *const c_char,
    domain: *const c_char,
    out: *mut *mut vfsi_fs,
) -> c_int {
    ffi_guard!(libc::EIO, {
        if out.is_null() {
            return libc::EINVAL;
        }
        let (Some(server), Some(share), Some(username), Some(password), Some(domain)) = (
            cstr_utf8(server),
            cstr_utf8(share),
            cstr_utf8(username),
            cstr_utf8(password),
            cstr_utf8(domain),
        ) else {
            return libc::EINVAL;
        };
        match SmbVecFs::connect(&server, &share, &username, &password, &domain) {
            Ok(backend) => {
                *out = make_fs(
                    Box::new(backend) as Box<dyn BindingBackend>,
                    PathBuf::from("/"),
                    PathBuf::from("/"),
                );
                0
            }
            Err(error) => vf_code(&error),
        }
    })
}

/// Connect to an SMB2/3 share and map a kernel-visible `mountpoint` onto
/// `share_root` within that share. Both paths must be absolute and may not
/// contain parent-directory components.
#[no_mangle]
pub unsafe extern "C" fn vfsi_smb_open_mount(
    server: *const c_char,
    share: *const c_char,
    username: *const c_char,
    password: *const c_char,
    domain: *const c_char,
    share_root: *const c_char,
    mountpoint: *const c_char,
    out: *mut *mut vfsi_fs,
) -> c_int {
    ffi_guard!(libc::EIO, {
        if out.is_null() {
            return libc::EINVAL;
        }
        let (Some(server), Some(share), Some(username), Some(password), Some(domain)) = (
            cstr_utf8(server),
            cstr_utf8(share),
            cstr_utf8(username),
            cstr_utf8(password),
            cstr_utf8(domain),
        ) else {
            return libc::EINVAL;
        };
        let (Some(share_root), Some(mountpoint)) = (cstr_path(share_root), cstr_path(mountpoint))
        else {
            return libc::EINVAL;
        };
        if !share_root.is_absolute()
            || !mountpoint.is_absolute()
            || share_root
                .components()
                .chain(mountpoint.components())
                .any(|component| matches!(component, Component::ParentDir))
        {
            return libc::EINVAL;
        }
        match SmbVecFs::connect(&server, &share, &username, &password, &domain) {
            Ok(backend) => {
                *out = make_fs(
                    Box::new(backend) as Box<dyn BindingBackend>,
                    mountpoint,
                    share_root,
                );
                0
            }
            Err(error) => vf_code(&error),
        }
    })
}

/// Destroy a filesystem handle returned by one of the `vfsi_*_open*`
/// functions.
#[no_mangle]
pub unsafe extern "C" fn vfsi_free(fs: *mut vfsi_fs) {
    ffi_guard!((), {
        if !fs.is_null() {
            if std::env::var("VNFS_STATS").as_deref() == Ok("1") {
                let (n, ops, bytes, max) = vfsi_nfs::compound::compound_stats();
                if n > 0 {
                    eprintln!(
                    "[vfsi] compounds={} avg_ops={:.2} max_ops={} avg_bytes={:.0} total_bytes={}",
                    n,
                    ops as f64 / n as f64,
                    max,
                    bytes as f64 / n as f64,
                    bytes
                );
                }
                let (calls, us) = vfsi_nfs::compound::rpc_stats();
                if calls > 0 {
                    eprintln!(
                        "[vfsi] rpc_calls={} avg_rpc_ms={:.2} total_rpc_ms={:.1}",
                        calls,
                        us as f64 / calls as f64 / 1000.0,
                        us as f64 / 1000.0
                    );
                }
            }
            // SAFETY: frees an object previously created by this crate.
            unsafe { drop(Box::from_raw(fs)) };
        }
    })
}

fn stat_impl(fs: &vfsi_fs, path: &std::path::Path) -> Result<VfAttrs, VfError> {
    let vpath = vpath_for(fs, path)?;
    lock_or_io(&fs.fs)?.stat_impl(&vpath)
}

/// Stat `path`, following a final symlink.
#[no_mangle]
pub unsafe extern "C" fn vfsi_stat(
    fs: *mut vfsi_fs,
    path: *const c_char,
    out: *mut vfsi_attrs,
) -> c_int {
    ffi_guard!(libc::EIO, {
        let (Some(fs), Some(path), Some(out)) = (fs.as_ref(), cstr_path(path), out.as_mut()) else {
            return libc::EINVAL;
        };
        match stat_impl(fs, &path) {
            Ok(a) => {
                *out = vfsi_attrs::from_vf(&a);
                0
            }
            Err(e) => vf_code(&e),
        }
    })
}

fn open_impl(
    fs: &vfsi_fs,
    path: &std::path::Path,
    flags: c_int,
    mode: u32,
) -> Result<i32, VfError> {
    let vpath = vpath_for(fs, path)?;
    let file = lock_or_io(&fs.fs)?.open_raw_impl(&vpath, flags, mode)?;
    let mut files = lock_or_io(&fs.files)?;
    insert_c_file(fs, &mut files, file)
}

/// Open a file and return a vfsi descriptor (`>= 0`), or a negative errno.
#[no_mangle]
pub unsafe extern "C" fn vfsi_open(
    fs: *mut vfsi_fs,
    path: *const c_char,
    flags: c_int,
    mode: u32,
) -> c_int {
    ffi_guard!(-libc::EIO, {
        let (Some(fs), Some(path)) = (fs.as_ref(), cstr_path(path)) else {
            return -libc::EINVAL;
        };
        match open_impl(fs, &path, flags, mode) {
            Ok(fd) => fd,
            Err(e) => -vf_code(&e),
        }
    })
}

fn close_impl(fs: &vfsi_fs, fd: i32) -> Result<(), VfError> {
    let file = lock_or_io(&fs.files)?
        .remove(&fd)
        .ok_or_else(|| VfError::failure(0, ERR_EBADF))?;
    lock_or_io(&fs.fs)?.close_impl(&file)
}

/// Close a descriptor opened by [`vfsi_open`].
#[no_mangle]
pub unsafe extern "C" fn vfsi_close(fs: *mut vfsi_fs, fd: c_int) -> c_int {
    ffi_guard!(libc::EIO, {
        let Some(fs) = fs.as_ref() else {
            return libc::EINVAL;
        };
        match close_impl(fs, fd) {
            Ok(()) => 0,
            Err(e) => vf_code(&e),
        }
    })
}

fn pread_impl(
    fs: &vfsi_fs,
    fd: i32,
    buf: *mut c_void,
    len: usize,
    offset: u64,
) -> Result<usize, VfError> {
    let file = lock_or_io(&fs.files)?
        .get(&fd)
        .cloned()
        .ok_or_else(|| VfError::failure(0, ERR_EBADF))?;
    let data = lock_or_io(&fs.fs)?.read_raw_impl(&file, offset, len)?;
    // SAFETY: C caller must provide a buffer of at least `len` bytes.
    unsafe { std::ptr::copy_nonoverlapping(data.as_ptr(), buf as *mut u8, data.len()) };
    Ok(data.len())
}

/// Read up to `len` bytes at `offset` into `buf`; writes the actual count to
/// `*got` when non-NULL.
#[no_mangle]
pub unsafe extern "C" fn vfsi_pread(
    fs: *mut vfsi_fs,
    fd: c_int,
    buf: *mut c_void,
    len: usize,
    offset: u64,
    got: *mut usize,
) -> c_int {
    ffi_guard!(libc::EIO, {
        let (Some(fs), false, Some(buf)) = (fs.as_ref(), buf.is_null(), buf.as_mut()) else {
            return libc::EINVAL;
        };
        let _ = buf;
        match pread_impl(fs, fd, buf, len, offset) {
            Ok(n) => {
                if !got.is_null() {
                    // SAFETY: C caller may pass NULL, otherwise a writable usize.
                    unsafe { *got = n };
                }
                0
            }
            Err(e) => vf_code(&e),
        }
    })
}

fn pwrite_impl(
    fs: &vfsi_fs,
    fd: i32,
    buf: *const c_void,
    len: usize,
    offset: u64,
) -> Result<usize, VfError> {
    let file = lock_or_io(&fs.files)?
        .get(&fd)
        .cloned()
        .ok_or_else(|| VfError::failure(0, ERR_EBADF))?;
    // SAFETY: C caller must provide a valid buffer of `len` bytes.
    let data = unsafe { std::slice::from_raw_parts(buf as *const u8, len) };
    lock_or_io(&fs.fs)?.write_raw_impl(&file, offset, data)
}

/// Write `len` bytes at `offset`; writes the actual count to `*wrote`.
#[no_mangle]
pub unsafe extern "C" fn vfsi_pwrite(
    fs: *mut vfsi_fs,
    fd: c_int,
    buf: *const c_void,
    len: usize,
    offset: u64,
    wrote: *mut usize,
) -> c_int {
    ffi_guard!(libc::EIO, {
        let (Some(fs), false, Some(buf)) = (fs.as_ref(), buf.is_null(), buf.as_ref()) else {
            return libc::EINVAL;
        };
        let _ = buf;
        match pwrite_impl(fs, fd, buf, len, offset) {
            Ok(n) => {
                if !wrote.is_null() {
                    // SAFETY: C caller may pass NULL, otherwise a writable usize.
                    unsafe { *wrote = n };
                }
                0
            }
            Err(e) => vf_code(&e),
        }
    })
}

/// Create a directory (`create_parents != 0` behaves like `mkdir -p`).
#[no_mangle]
pub unsafe extern "C" fn vfsi_mkdir(
    fs: *mut vfsi_fs,
    path: *const c_char,
    mode: u32,
    create_parents: c_int,
) -> c_int {
    ffi_guard!(libc::EIO, {
        let (Some(fs), Some(path)) = (fs.as_ref(), cstr_path(path)) else {
            return libc::EINVAL;
        };
        let result: Result<(), VfError> = (|| {
            let path = vpath_for(fs, &path)?;
            let mut f = lock_or_io(&fs.fs)?;
            if create_parents != 0 {
                f.ensure_dir_impl(&path, mode)
            } else {
                f.mkdir_raw_impl(&path, mode)
            }
        })();
        match result {
            Ok(()) => 0,
            Err(e) => vf_code(&e),
        }
    })
}

/// Remove a path (directories must be empty).
#[no_mangle]
pub unsafe extern "C" fn vfsi_remove(fs: *mut vfsi_fs, path: *const c_char) -> c_int {
    ffi_guard!(libc::EIO, {
        let (Some(fs), Some(path)) = (fs.as_ref(), cstr_path(path)) else {
            return libc::EINVAL;
        };
        let result: Result<(), VfError> = (|| {
            let path = vpath_for(fs, &path)?;
            lock_or_io(&fs.fs)?.unlink_impl(&path)
        })();
        match result {
            Ok(()) => 0,
            Err(e) => vf_code(&e),
        }
    })
}

/// Rename `oldpath` to `newpath`.
#[no_mangle]
pub unsafe extern "C" fn vfsi_rename(
    fs: *mut vfsi_fs,
    oldpath: *const c_char,
    newpath: *const c_char,
) -> c_int {
    ffi_guard!(libc::EIO, {
        let (Some(fs), Some(old), Some(new)) =
            (fs.as_ref(), cstr_path(oldpath), cstr_path(newpath))
        else {
            return libc::EINVAL;
        };
        let result: Result<(), VfError> = (|| {
            let old = vpath_for(fs, &old)?;
            let new = vpath_for(fs, &new)?;
            lock_or_io(&fs.fs)?
                .vrename_impl(&[(VfFile::from_os_path(&old), VfFile::from_os_path(&new))])
        })();
        match result {
            Ok(()) => 0,
            Err(e) => vf_code(&e),
        }
    })
}

/// Copy one extent. When `to_eof` is true, `length` is ignored and copying
/// continues to the source EOF. The backend uses NFSv4.2 COPY or SMB
/// server-side copy when available and falls back to client-side I/O.
#[no_mangle]
pub unsafe extern "C" fn vfsi_copy(
    fs: *mut vfsi_fs,
    src: *const c_char,
    src_offset: u64,
    dst: *const c_char,
    dst_offset: u64,
    length: u64,
    to_eof: bool,
) -> c_int {
    ffi_guard!(libc::EIO, {
        let Some(fs) = fs.as_ref() else {
            return libc::EINVAL;
        };
        let (Some(src), Some(dst)) = (cstr_path(src), cstr_path(dst)) else {
            return libc::EINVAL;
        };
        let (Some(src), Some(dst)) = (path_for(fs, &src), path_for(fs, &dst)) else {
            return libc::ENOENT;
        };
        let pair = ExtentPair::from_os_paths(
            &src,
            src_offset,
            &dst,
            dst_offset,
            (!to_eof).then_some(length),
        );
        match lock_or_io(&fs.fs)
            .and_then(|mut backend| backend.vcopy_impl(&[pair], vfsi_sync::CopyOption::new()))
        {
            Ok(()) => 0,
            Err(error) => vf_code(&error),
        }
    })
}

/// Open `count` files in one backend vector call. ABI-v2 functions remain
/// available; this and the other `*v` entry points use the uniform ABI-v3
/// overall and per-element result contract.
#[no_mangle]
pub unsafe extern "C" fn vfsi_openv(
    fs: *mut vfsi_fs,
    ops: *mut vfsi_open_op,
    count: usize,
    item_results: *mut vfsi_result,
) -> vfsi_result {
    ffi_guard!(vfsi_result::panic(), {
        let Some(fs) = fs.as_ref() else {
            return vfsi_result::invalid(0, "null filesystem");
        };
        if count == 0 {
            return vfsi_result::success(0);
        }
        let results = match result_array(item_results, count) {
            Ok(results) => results,
            Err(error) => return error,
        };
        let Some(ops) = ops.as_mut() else {
            fail_batch!(
                results,
                vfsi_result::invalid(0, "null operation array"),
                false
            );
        };
        let ops = std::slice::from_raw_parts_mut(ops, count);
        let mut paths = Vec::with_capacity(count);
        let mut flags = Vec::with_capacity(count);
        let mut modes = Vec::with_capacity(count);
        for (index, op) in ops.iter().enumerate() {
            let Some(path) = cstr_path(op.path) else {
                fail_batch!(results, vfsi_result::invalid(index, "null path"), false);
            };
            match vpath_for(fs, &path) {
                Ok(path) => paths.push(path),
                Err(error) => fail_batch!(
                    results,
                    vfsi_result::from_error(error.with_index(index)),
                    false
                ),
            }
            flags.push(op.flags);
            modes.push(op.mode);
        }
        let refs: Vec<&Path> = paths.iter().map(PathBuf::as_path).collect();
        let opened = {
            let mut backend = match lock_or_io(&fs.fs) {
                Ok(backend) => backend,
                Err(error) => fail_batch!(results, vfsi_result::from_error(error), true),
            };
            match backend.vopen_raw_impl(&refs, &flags, &modes) {
                Ok(opened) => opened,
                Err(error) => return vfsi_result::from_error(error),
            }
        };
        let mut registered = Vec::with_capacity(count);
        let registration = (|| -> Result<(), VfError> {
            let mut files = lock_or_io(&fs.files)?;
            for (index, (op, file)) in ops.iter_mut().zip(&opened).enumerate() {
                let fd = insert_c_file(fs, &mut files, file.clone())
                    .map_err(|error| error.with_index(index))?;
                op.fd = fd;
                registered.push(fd);
            }
            Ok(())
        })();
        if let Err(error) = registration {
            if let Ok(mut files) = fs.files.lock() {
                for fd in registered {
                    files.remove(&fd);
                }
            }
            if let Ok(mut backend) = fs.fs.lock() {
                let _ = backend.vclose_impl(&opened);
            }
            fail_batch!(results, vfsi_result::from_error(error), true);
        }
        complete_results(results);
        vfsi_result::success(count)
    })
}

/// Close a descriptor array in one backend vector call.
#[no_mangle]
pub unsafe extern "C" fn vfsi_closev(
    fs: *mut vfsi_fs,
    fds: *const c_int,
    count: usize,
    item_results: *mut vfsi_result,
) -> vfsi_result {
    ffi_guard!(vfsi_result::panic(), {
        let Some(fs) = fs.as_ref() else {
            return vfsi_result::invalid(0, "null filesystem");
        };
        if count == 0 {
            return vfsi_result::success(0);
        }
        let results = match result_array(item_results, count) {
            Ok(results) => results,
            Err(error) => return error,
        };
        if fds.is_null() {
            fail_batch!(
                results,
                vfsi_result::invalid(0, "null descriptor array"),
                false
            );
        }
        let fds = std::slice::from_raw_parts(fds, count);
        let files = {
            let table = match lock_or_io(&fs.files) {
                Ok(table) => table,
                Err(error) => fail_batch!(results, vfsi_result::from_error(error), false),
            };
            let mut files = Vec::with_capacity(count);
            for (index, fd) in fds.iter().enumerate() {
                let Some(file) = table.get(fd).cloned() else {
                    fail_batch!(
                        results,
                        vfsi_result::from_error(VfError::failure(index, ERR_EBADF)),
                        false
                    );
                };
                files.push(file);
            }
            files
        };
        let mut backend = match lock_or_io(&fs.fs) {
            Ok(backend) => backend,
            Err(error) => fail_batch!(results, vfsi_result::from_error(error), false),
        };
        match backend.vclose_impl(&files) {
            Ok(()) => {
                if let Ok(mut table) = fs.files.lock() {
                    for fd in fds {
                        table.remove(fd);
                    }
                }
                complete_results(results);
                vfsi_result::success(count)
            }
            Err(error) => {
                let closed_prefix = confirmed_close_prefix(&error, fds.len());
                if closed_prefix > 0 {
                    if let Ok(mut table) = fs.files.lock() {
                        for fd in fds.iter().take(closed_prefix) {
                            table.remove(fd);
                        }
                    }
                }
                let failure = vfsi_result::from_error(error);
                fail_results(results, failure, true);
                failure
            }
        }
    })
}

/// Stat a path array in one backend vector call.
#[no_mangle]
pub unsafe extern "C" fn vfsi_statv(
    fs: *mut vfsi_fs,
    ops: *mut vfsi_stat_op,
    count: usize,
    item_results: *mut vfsi_result,
) -> vfsi_result {
    ffi_guard!(vfsi_result::panic(), {
        let Some(fs) = fs.as_ref() else {
            return vfsi_result::invalid(0, "null filesystem");
        };
        if count == 0 {
            return vfsi_result::success(0);
        }
        let results = match result_array(item_results, count) {
            Ok(results) => results,
            Err(error) => return error,
        };
        let Some(ops) = ops.as_mut() else {
            fail_batch!(
                results,
                vfsi_result::invalid(0, "null operation array"),
                false
            );
        };
        let ops = std::slice::from_raw_parts_mut(ops, count);
        let mut attrs = Vec::with_capacity(count);
        for (index, op) in ops.iter().enumerate() {
            let Some(path) = cstr_path(op.path) else {
                fail_batch!(results, vfsi_result::invalid(index, "null path"), false);
            };
            let path = match vpath_for(fs, &path) {
                Ok(path) => path,
                Err(error) => fail_batch!(
                    results,
                    vfsi_result::from_error(error.with_index(index)),
                    false
                ),
            };
            attrs.push(VfAttrs {
                file: VfFile::from_os_path(&path),
                masks: mask(),
                ..VfAttrs::default()
            });
        }
        let mut backend = match lock_or_io(&fs.fs) {
            Ok(backend) => backend,
            Err(error) => fail_batch!(results, vfsi_result::from_error(error), false),
        };
        if let Err(error) = backend.vgetattrs_impl(&mut attrs) {
            fail_batch!(results, vfsi_result::from_error(error), true);
        }
        for (op, attrs) in ops.iter_mut().zip(&attrs) {
            op.attrs = vfsi_attrs::from_vf(attrs);
        }
        complete_results(results);
        vfsi_result::success(count)
    })
}

/// Set selected attributes for a path array in one backend vector call.
#[no_mangle]
pub unsafe extern "C" fn vfsi_setattrv(
    fs: *mut vfsi_fs,
    ops: *const vfsi_setattr_op,
    count: usize,
    item_results: *mut vfsi_result,
) -> vfsi_result {
    ffi_guard!(vfsi_result::panic(), {
        let Some(fs) = fs.as_ref() else {
            return vfsi_result::invalid(0, "null filesystem");
        };
        if count == 0 {
            return vfsi_result::success(0);
        }
        let results = match result_array(item_results, count) {
            Ok(results) => results,
            Err(error) => return error,
        };
        if ops.is_null() {
            fail_batch!(
                results,
                vfsi_result::invalid(0, "null operation array"),
                false
            );
        }
        let ops = std::slice::from_raw_parts(ops, count);
        let mut attrs = Vec::with_capacity(count);
        for (index, op) in ops.iter().enumerate() {
            let Some(path) = cstr_path(op.path) else {
                fail_batch!(results, vfsi_result::invalid(index, "null path"), false);
            };
            let path = match vpath_for(fs, &path) {
                Ok(path) => path,
                Err(error) => fail_batch!(
                    results,
                    vfsi_result::from_error(error.with_index(index)),
                    false
                ),
            };
            let Some(masks) = AttrMask::from_bits(op.mask) else {
                fail_batch!(
                    results,
                    vfsi_result::invalid(index, "unknown attribute mask bit"),
                    false
                );
            };
            attrs.push(VfAttrs {
                file: VfFile::from_os_path(&path),
                masks,
                mode: op.mode,
                size: op.size,
                atime_sec: op.atime_sec,
                atime_nsec: op.atime_nsec,
                mtime_sec: op.mtime_sec,
                mtime_nsec: op.mtime_nsec,
                ..VfAttrs::default()
            });
        }
        let mut backend = match lock_or_io(&fs.fs) {
            Ok(backend) => backend,
            Err(error) => fail_batch!(results, vfsi_result::from_error(error), false),
        };
        match backend.vsetattrs_raw_impl(&attrs) {
            Ok(()) => {
                complete_results(results);
                vfsi_result::success(count)
            }
            Err(error) => {
                let failure = vfsi_result::from_error(error);
                fail_results(results, failure, true);
                failure
            }
        }
    })
}

/// Positioned vector read using caller-owned buffers.
#[no_mangle]
pub unsafe extern "C" fn vfsi_preadv(
    fs: *mut vfsi_fs,
    ops: *mut vfsi_pread_op,
    count: usize,
    item_results: *mut vfsi_result,
) -> vfsi_result {
    ffi_guard!(vfsi_result::panic(), {
        let Some(fs) = fs.as_ref() else {
            return vfsi_result::invalid(0, "null filesystem");
        };
        if count == 0 {
            return vfsi_result::success(0);
        }
        let item_results = match result_array(item_results, count) {
            Ok(results) => results,
            Err(error) => return error,
        };
        let Some(ops) = ops.as_mut() else {
            fail_batch!(
                item_results,
                vfsi_result::invalid(0, "null operation array"),
                false
            );
        };
        let ops = std::slice::from_raw_parts_mut(ops, count);
        let table = match lock_or_io(&fs.files) {
            Ok(table) => table,
            Err(error) => {
                fail_batch!(item_results, vfsi_result::from_error(error), false)
            }
        };
        let mut reads = Vec::with_capacity(count);
        for (index, op) in ops.iter().enumerate() {
            if op.len > 0 && op.buf.is_null() {
                fail_batch!(
                    item_results,
                    vfsi_result::invalid(index, "null read buffer"),
                    false
                );
            }
            let Some(file) = table.get(&op.fd).cloned() else {
                fail_batch!(
                    item_results,
                    vfsi_result::from_error(VfError::failure(index, ERR_EBADF)),
                    false
                );
            };
            reads.push(ReadOp::at(file, op.offset, op.len));
        }
        drop(table);
        let mut backend = match lock_or_io(&fs.fs) {
            Ok(backend) => backend,
            Err(error) => {
                fail_batch!(item_results, vfsi_result::from_error(error), false)
            }
        };
        let results = match backend.vread_impl(&reads) {
            Ok(results) => results,
            Err(error) => {
                fail_batch!(item_results, vfsi_result::from_error(error), true)
            }
        };
        for (op, result) in ops.iter_mut().zip(results) {
            if !result.data.is_empty() {
                std::ptr::copy_nonoverlapping(
                    result.data.as_ptr(),
                    op.buf.cast::<u8>(),
                    result.data.len(),
                );
            }
            op.got = result.data.len();
        }
        complete_results(item_results);
        vfsi_result::success(count)
    })
}

/// Positioned vector write using caller-owned buffers.
#[no_mangle]
pub unsafe extern "C" fn vfsi_pwritev(
    fs: *mut vfsi_fs,
    ops: *mut vfsi_pwrite_op,
    count: usize,
    item_results: *mut vfsi_result,
) -> vfsi_result {
    ffi_guard!(vfsi_result::panic(), {
        let Some(fs) = fs.as_ref() else {
            return vfsi_result::invalid(0, "null filesystem");
        };
        if count == 0 {
            return vfsi_result::success(0);
        }
        let item_results = match result_array(item_results, count) {
            Ok(results) => results,
            Err(error) => return error,
        };
        let Some(ops) = ops.as_mut() else {
            fail_batch!(
                item_results,
                vfsi_result::invalid(0, "null operation array"),
                false
            );
        };
        let ops = std::slice::from_raw_parts_mut(ops, count);
        let table = match lock_or_io(&fs.files) {
            Ok(table) => table,
            Err(error) => {
                fail_batch!(item_results, vfsi_result::from_error(error), false)
            }
        };
        let mut writes = Vec::with_capacity(count);
        for (index, op) in ops.iter().enumerate() {
            if op.len > 0 && op.buf.is_null() {
                fail_batch!(
                    item_results,
                    vfsi_result::invalid(index, "null write buffer"),
                    false
                );
            }
            let Some(file) = table.get(&op.fd).cloned() else {
                fail_batch!(
                    item_results,
                    vfsi_result::from_error(VfError::failure(index, ERR_EBADF)),
                    false
                );
            };
            let data = if op.len == 0 {
                Vec::new()
            } else {
                std::slice::from_raw_parts(op.buf.cast::<u8>(), op.len).to_vec()
            };
            writes.push(WriteOp::at(file, op.offset, data));
        }
        drop(table);
        let mut backend = match lock_or_io(&fs.fs) {
            Ok(backend) => backend,
            Err(error) => {
                fail_batch!(item_results, vfsi_result::from_error(error), false)
            }
        };
        let results = match backend.vwrite_owned_impl(&writes) {
            Ok(results) => results,
            Err(error) => {
                fail_batch!(item_results, vfsi_result::from_error(error), true)
            }
        };
        for (op, result) in ops.iter_mut().zip(results) {
            op.wrote = result.written;
        }
        complete_results(item_results);
        vfsi_result::success(count)
    })
}

/// Create a directory array in one backend vector call.
#[no_mangle]
pub unsafe extern "C" fn vfsi_mkdirv(
    fs: *mut vfsi_fs,
    ops: *const vfsi_mkdir_op,
    count: usize,
    item_results: *mut vfsi_result,
) -> vfsi_result {
    ffi_guard!(vfsi_result::panic(), {
        let Some(fs) = fs.as_ref() else {
            return vfsi_result::invalid(0, "null filesystem");
        };
        if count == 0 {
            return vfsi_result::success(0);
        }
        let results = match result_array(item_results, count) {
            Ok(results) => results,
            Err(error) => return error,
        };
        if ops.is_null() {
            fail_batch!(
                results,
                vfsi_result::invalid(0, "null operation array"),
                false
            );
        }
        let ops = std::slice::from_raw_parts(ops, count);
        let mut dirs = Vec::with_capacity(count);
        for (index, op) in ops.iter().enumerate() {
            let Some(path) = cstr_path(op.path) else {
                fail_batch!(results, vfsi_result::invalid(index, "null path"), false);
            };
            let path = match vpath_for(fs, &path) {
                Ok(path) => path,
                Err(error) => fail_batch!(
                    results,
                    vfsi_result::from_error(error.with_index(index)),
                    false
                ),
            };
            dirs.push(VfAttrs {
                file: VfFile::from_os_path(&path),
                masks: AttrMask::MODE,
                mode: op.mode,
                ..VfAttrs::default()
            });
        }
        let mut backend = match lock_or_io(&fs.fs) {
            Ok(backend) => backend,
            Err(error) => fail_batch!(results, vfsi_result::from_error(error), false),
        };
        match backend.vmkdir_impl(&dirs) {
            Ok(()) => {
                complete_results(results);
                vfsi_result::success(count)
            }
            Err(error) => {
                let failure = vfsi_result::from_error(error);
                fail_results(results, failure, true);
                failure
            }
        }
    })
}

/// Remove a path array in one backend vector call.
#[no_mangle]
pub unsafe extern "C" fn vfsi_removev(
    fs: *mut vfsi_fs,
    paths: *const *const c_char,
    count: usize,
    item_results: *mut vfsi_result,
) -> vfsi_result {
    ffi_guard!(vfsi_result::panic(), {
        let Some(fs) = fs.as_ref() else {
            return vfsi_result::invalid(0, "null filesystem");
        };
        if count == 0 {
            return vfsi_result::success(0);
        }
        let results = match result_array(item_results, count) {
            Ok(results) => results,
            Err(error) => return error,
        };
        if paths.is_null() {
            fail_batch!(results, vfsi_result::invalid(0, "null path array"), false);
        }
        let paths = std::slice::from_raw_parts(paths, count);
        let mut files = Vec::with_capacity(count);
        for (index, path) in paths.iter().enumerate() {
            let Some(path) = cstr_path(*path) else {
                fail_batch!(results, vfsi_result::invalid(index, "null path"), false);
            };
            let path = match vpath_for(fs, &path) {
                Ok(path) => path,
                Err(error) => fail_batch!(
                    results,
                    vfsi_result::from_error(error.with_index(index)),
                    false
                ),
            };
            files.push(VfFile::from_os_path(&path));
        }
        let mut backend = match lock_or_io(&fs.fs) {
            Ok(backend) => backend,
            Err(error) => fail_batch!(results, vfsi_result::from_error(error), false),
        };
        match backend.vremove_impl(&files) {
            Ok(()) => {
                complete_results(results);
                vfsi_result::success(count)
            }
            Err(error) => {
                let failure = vfsi_result::from_error(error);
                fail_results(results, failure, true);
                failure
            }
        }
    })
}

/// Rename a path-pair array in one backend vector call.
#[no_mangle]
pub unsafe extern "C" fn vfsi_renamev(
    fs: *mut vfsi_fs,
    ops: *const vfsi_rename_op,
    count: usize,
    item_results: *mut vfsi_result,
) -> vfsi_result {
    ffi_guard!(vfsi_result::panic(), {
        let Some(fs) = fs.as_ref() else {
            return vfsi_result::invalid(0, "null filesystem");
        };
        if count == 0 {
            return vfsi_result::success(0);
        }
        let results = match result_array(item_results, count) {
            Ok(results) => results,
            Err(error) => return error,
        };
        if ops.is_null() {
            fail_batch!(
                results,
                vfsi_result::invalid(0, "null operation array"),
                false
            );
        }
        let ops = std::slice::from_raw_parts(ops, count);
        let mut pairs = Vec::with_capacity(count);
        for (index, op) in ops.iter().enumerate() {
            let (Some(oldpath), Some(newpath)) = (cstr_path(op.oldpath), cstr_path(op.newpath))
            else {
                fail_batch!(results, vfsi_result::invalid(index, "null path"), false);
            };
            let (oldpath, newpath) = match (vpath_for(fs, &oldpath), vpath_for(fs, &newpath)) {
                (Ok(oldpath), Ok(newpath)) => (oldpath, newpath),
                (Err(error), _) | (_, Err(error)) => {
                    fail_batch!(
                        results,
                        vfsi_result::from_error(error.with_index(index)),
                        false
                    );
                }
            };
            pairs.push((
                VfFile::from_os_path(&oldpath),
                VfFile::from_os_path(&newpath),
            ));
        }
        let mut backend = match lock_or_io(&fs.fs) {
            Ok(backend) => backend,
            Err(error) => fail_batch!(results, vfsi_result::from_error(error), false),
        };
        match backend.vrename_impl(&pairs) {
            Ok(()) => {
                complete_results(results);
                vfsi_result::success(count)
            }
            Err(error) => {
                let failure = vfsi_result::from_error(error);
                fail_results(results, failure, true);
                failure
            }
        }
    })
}

/// Copy an extent-pair array in one backend vector call.
#[no_mangle]
pub unsafe extern "C" fn vfsi_copyv(
    fs: *mut vfsi_fs,
    ops: *const vfsi_copy_op,
    count: usize,
    item_results: *mut vfsi_result,
) -> vfsi_result {
    ffi_guard!(vfsi_result::panic(), {
        let Some(fs) = fs.as_ref() else {
            return vfsi_result::invalid(0, "null filesystem");
        };
        if count == 0 {
            return vfsi_result::success(0);
        }
        let results = match result_array(item_results, count) {
            Ok(results) => results,
            Err(error) => return error,
        };
        if ops.is_null() {
            fail_batch!(
                results,
                vfsi_result::invalid(0, "null operation array"),
                false
            );
        }
        let ops = std::slice::from_raw_parts(ops, count);
        let mut pairs = Vec::with_capacity(count);
        for (index, op) in ops.iter().enumerate() {
            let (Some(src), Some(dst)) = (cstr_path(op.src), cstr_path(op.dst)) else {
                fail_batch!(results, vfsi_result::invalid(index, "null path"), false);
            };
            let (Some(src), Some(dst)) = (path_for(fs, &src), path_for(fs, &dst)) else {
                fail_batch!(
                    results,
                    vfsi_result::from_error(VfError::failure(index, ERR_NOENT)),
                    false
                );
            };
            pairs.push(ExtentPair::from_os_paths(
                &src,
                op.src_offset,
                &dst,
                op.dst_offset,
                (!op.to_eof).then_some(op.length),
            ));
        }
        let mut backend = match lock_or_io(&fs.fs) {
            Ok(backend) => backend,
            Err(error) => fail_batch!(results, vfsi_result::from_error(error), false),
        };
        match backend.vcopy_impl(&pairs, vfsi_sync::CopyOption::new()) {
            Ok(()) => {
                complete_results(results);
                vfsi_result::success(count)
            }
            Err(error) => {
                let failure = vfsi_result::from_error(error);
                fail_results(results, failure, true);
                failure
            }
        }
    })
}

/// Stream several paths in bounded vectorized chunks. Returning `false` from
/// `cb` cancels successfully. The callback provides backpressure and must not
/// reenter the same filesystem handle.
#[no_mangle]
pub unsafe extern "C" fn vfsi_read_streamv(
    fs: *mut vfsi_fs,
    paths: *const *const c_char,
    count: usize,
    chunk_size: usize,
    memory_limit: usize,
    cb: vfsi_read_stream_cb,
    userdata: *mut c_void,
) -> vfsi_result {
    ffi_guard!(vfsi_result::panic(), {
        let Some(fs) = fs.as_ref() else {
            return vfsi_result::invalid(0, "null filesystem");
        };
        let Some(cb) = cb else {
            return vfsi_result::invalid(0, "null callback");
        };
        if chunk_size == 0 || memory_limit == 0 {
            return vfsi_result::invalid(0, "chunk and memory limits must be non-zero");
        }
        if count == 0 {
            return vfsi_result::success(0);
        }
        if paths.is_null() {
            return vfsi_result::invalid(0, "null path array");
        }
        let paths = std::slice::from_raw_parts(paths, count);
        let mut cpaths = Vec::with_capacity(count);
        let mut files = Vec::with_capacity(count);
        for (index, path) in paths.iter().enumerate() {
            let Some(kernel_path) = cstr_path(*path) else {
                return vfsi_result::invalid(index, "null path");
            };
            let Some(cpath) = cstr_from_os(kernel_path.as_os_str().as_bytes()) else {
                return vfsi_result::invalid(index, "path contains NUL");
            };
            let vpath = match vpath_for(fs, &kernel_path) {
                Ok(path) => path,
                Err(error) => return vfsi_result::from_error(error.with_index(index)),
            };
            cpaths.push(cpath);
            files.push(VfFile::from_os_path(&vpath));
        }
        let mut backend = match lock_or_io(&fs.fs) {
            Ok(backend) => backend,
            Err(error) => return vfsi_result::from_error(error),
        };
        let result = backend.vstream_impl(
            &files,
            chunk_size,
            memory_limit,
            &mut |index, offset, data, eof| {
                cb(
                    cpaths[index].as_ptr(),
                    index,
                    offset,
                    data.as_ptr(),
                    data.len(),
                    eof,
                    userdata,
                )
            },
        );
        match result {
            Ok(()) => vfsi_result::success(count),
            Err(error) => vfsi_result::from_error(error),
        }
    })
}

/// List `dir` and call `cb` for each entry. Returning `false` from `cb`
/// stops the listing.
#[no_mangle]
pub unsafe extern "C" fn vfsi_listdir(
    fs: *mut vfsi_fs,
    dir: *const c_char,
    cb: vfsi_listdir_cb,
    userdata: *mut c_void,
) -> c_int {
    vfsi_listdir_with_limits(
        fs,
        dir,
        vfsi_sync::DEFAULT_DIRECTORY_MAX_ENTRIES,
        vfsi_sync::DEFAULT_DIRECTORY_MAX_PATH_BYTES,
        cb,
        userdata,
    )
}

/// One bounded directory listing. Zero permits only an empty directory.
/// Callbacks run outside the filesystem lock.
#[no_mangle]
pub unsafe extern "C" fn vfsi_listdir_with_limits(
    fs: *mut vfsi_fs,
    dir: *const c_char,
    max_entries: usize,
    max_path_bytes: usize,
    cb: vfsi_listdir_cb,
    userdata: *mut c_void,
) -> c_int {
    ffi_guard!(libc::EIO, {
        let (Some(fs), Some(dir)) = (fs.as_ref(), cstr_path(dir)) else {
            return libc::EINVAL;
        };
        let Some(cb) = cb else {
            return libc::EINVAL;
        };
        let res = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
            let dir = vpath_for(fs, &dir)?;
            let entries = bounded_listdir(fs, &dir, mask(), max_entries, max_path_bytes)?;
            for a in entries {
                let name = a
                    .file
                    .path()
                    .and_then(|p| p.file_name())
                    .map(|n| n.as_bytes())
                    .and_then(cstr_from_os)
                    .unwrap_or_default();
                let attrs = vfsi_attrs::from_vf(&a);
                // SAFETY: callback was provided by C and is called from the same
                // thread while `attrs`/`name` are alive.
                if !unsafe { cb(name.as_ptr(), &attrs, userdata) } {
                    break;
                }
            }
            Ok::<_, VfError>(())
        }));
        match res {
            Ok(Ok(())) => 0,
            Ok(Err(e)) => vf_code(&e),
            Err(_) => libc::EIO,
        }
    })
}

/// List several directories in one vectorized batch, calling `cb` for each
/// entry with the directory the entry came from.
#[no_mangle]
pub unsafe extern "C" fn vfsi_listdirv(
    fs: *mut vfsi_fs,
    dirs: *const *const c_char,
    count: usize,
    max_entries: usize,
    recursive: bool,
    cb: vfsi_listdirv_cb,
    userdata: *mut c_void,
) -> c_int {
    ffi_guard!(libc::EIO, {
        let (Some(fs), false, false) = (fs.as_ref(), dirs.is_null(), cb.is_none()) else {
            return libc::EINVAL;
        };
        let Some(cb) = cb else {
            return libc::EINVAL;
        };
        let mut paths = Vec::with_capacity(count);
        for i in 0..count {
            // SAFETY: `dirs` points to `count` NUL-terminated strings.
            let p = unsafe { *dirs.add(i) };
            let Some(path) = cstr_path(p) else {
                return libc::EINVAL;
            };
            paths.push(path);
        }
        let res = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
            let original_paths = paths.clone();
            let vpaths: Result<Vec<PathBuf>, VfError> =
                paths.iter().map(|p| vpath_for(fs, p)).collect();
            let vpaths = vpaths?;
            let refs: Vec<&Path> = vpaths.iter().map(PathBuf::as_path).collect();
            let vpath_index: std::collections::HashMap<PathBuf, usize> = vpaths
                .iter()
                .enumerate()
                .map(|(i, p)| (p.clone(), i))
                .collect();
            let mountpoint = fs.mountpoint.clone();
            let c_cb = cb;
            let mut rows = Vec::new();
            {
                let mut backend = lock_or_io(&fs.fs)?;
                backend.vlistdirs_impl(
                    &refs,
                    mask(),
                    max_entries,
                    recursive,
                    &mut |attrs, dir| {
                        rows.push((attrs.clone(), dir.to_path_buf()));
                        true
                    },
                )?;
            }
            for (attrs, dir) in rows {
                let kernel_dir = match vpath_index.get(&dir) {
                    Some(&i) => original_paths[i].clone(),
                    None => {
                        let rel = dir.strip_prefix("/").unwrap_or(&dir);
                        mountpoint.join(rel)
                    }
                };
                let dir = kernel_dir.as_os_str().as_bytes();
                let Some(dir) = cstr_from_os(dir) else {
                    break;
                };
                let name = attrs
                    .file
                    .path()
                    .and_then(|p| p.file_name())
                    .map(|n| n.as_bytes())
                    .and_then(cstr_from_os)
                    .unwrap_or_default();
                let a = vfsi_attrs::from_vf(&attrs);
                // SAFETY: `c_cb` was provided by C and is invoked from the same
                // thread while its arguments are alive. No filesystem mutex is held.
                if !unsafe { c_cb(dir.as_ptr(), name.as_ptr(), &a, userdata) } {
                    break;
                }
            }
            Ok::<_, VfError>(())
        }));
        match res {
            Ok(Ok(())) => 0,
            Ok(Err(e)) => vf_code(&e),
            Err(_) => libc::EIO,
        }
    })
}

/// Read the full contents of several files in one vectorized batch, calling
/// `cb` for each file after its data has been fetched.
#[no_mangle]
pub unsafe extern "C" fn vfsi_read_paths(
    fs: *mut vfsi_fs,
    paths: *const *const c_char,
    count: usize,
    cb: vfsi_read_paths_cb,
    userdata: *mut c_void,
) -> c_int {
    vfsi_read_paths_with_limit(
        fs,
        paths,
        count,
        vfsi_sync::DEFAULT_READ_ALLV_MAX_TOTAL_BYTES,
        cb,
        userdata,
    )
}

/// Whole-file vector with an explicit aggregate payload budget. Oversized
/// results are an error, never successful truncation. Zero is a zero budget.
#[no_mangle]
pub unsafe extern "C" fn vfsi_read_paths_with_limit(
    fs: *mut vfsi_fs,
    paths: *const *const c_char,
    count: usize,
    max_bytes: usize,
    cb: vfsi_read_paths_cb,
    userdata: *mut c_void,
) -> c_int {
    ffi_guard!(libc::EIO, {
        let (Some(fs), false, false) = (fs.as_ref(), paths.is_null(), cb.is_none()) else {
            return libc::EINVAL;
        };
        let Some(cb) = cb else {
            return libc::EINVAL;
        };
        let mut kernel_paths = Vec::with_capacity(count);
        for i in 0..count {
            // SAFETY: `paths` points to `count` NUL-terminated strings.
            let p = unsafe { *paths.add(i) };
            let Some(path) = cstr_path(p) else {
                return libc::EINVAL;
            };
            kernel_paths.push(path);
        }
        let res = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
            let vpaths: Result<Vec<PathBuf>, VfError> =
                kernel_paths.iter().map(|p| vpath_for(fs, p)).collect();
            let vpaths = vpaths?;
            let files: Vec<VfFile> = vpaths.iter().map(|p| VfFile::from_os_path(p)).collect();
            let datas = lock_or_io(&fs.fs)?.vread_all_with_options_impl(
                &files,
                vfsi_sync::ReadAllOptions::new().max_total_bytes(max_bytes),
            )?;
            let c_cb = cb;
            for (i, data) in datas.iter().enumerate() {
                let Some(path) = cstr_from_os(kernel_paths[i].as_os_str().as_bytes()) else {
                    continue;
                };
                // SAFETY: `c_cb` was provided by C and is invoked from the same
                // thread while `path`/`data` are alive.
                if !unsafe { c_cb(path.as_ptr(), data.as_ptr(), data.len(), userdata) } {
                    break;
                }
            }
            Ok::<_, VfError>(())
        }));
        match res {
            Ok(Ok(())) => 0,
            Ok(Err(e)) => vf_code(&e),
            Err(_) => libc::EIO,
        }
    })
}

// Protocol inspection belongs to the bindings, outside the native operation contracts.
trait BindingBackend: vfsi_sync::Backend {
    fn nfs_minorversion(&self) -> Option<u32> {
        None
    }
    fn smb_dialect(&self) -> Option<u16> {
        None
    }
}
impl BindingBackend for DummyVecFs {}
impl BindingBackend for NfsVecFs {
    fn nfs_minorversion(&self) -> Option<u32> {
        Some(vfsi_nfs::NfsExtensions::nfs_minor_version(self))
    }
}
impl BindingBackend for SmbVecFs {
    fn smb_dialect(&self) -> Option<u16> {
        Some(vfsi_smb::SmbExtensions::smb_dialect_revision(self))
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::ffi::CString;

    #[derive(Default)]
    struct ListingCall {
        directories: Vec<PathBuf>,
        max_entries: usize,
    }

    // Exercise the actual C entry point. Like NFS, this backend fetches all
    // roots' first pages before its first quota callback, and records that work.
    struct ListingBackend {
        calls: std::sync::Arc<Mutex<Vec<ListingCall>>>,
        entries_per_dir: usize,
        emitted: usize,
        missing: AttrMask,
        missing_after: usize,
        fail_call: Option<usize>,
    }

    impl vfsi_sync::FileSystem for ListingBackend {
        fn sync_data(&mut self, _: &VfFile) -> vfsi_sync::VfResult<()> {
            Err(VfError::unsupported(0))
        }
        fn open_impl(&mut self, _: &vfsi_sync::OpenOp) -> vfsi_sync::VfResult<VfFile> {
            Err(VfError::unsupported(0))
        }
        fn close_impl(&mut self, _: &VfFile) -> vfsi_sync::VfResult<()> {
            Err(VfError::unsupported(0))
        }
        fn read_impl(&mut self, _: &ReadOp) -> vfsi_sync::VfResult<vfsi_sync::ReadResult> {
            Err(VfError::unsupported(0))
        }
        fn write_impl(
            &mut self,
            _: vfsi_sync::WriteOpRef<'_>,
        ) -> vfsi_sync::VfResult<vfsi_sync::WriteResult> {
            Err(VfError::unsupported(0))
        }
        fn seek_impl(&mut self, _: &VfFile, _: std::io::SeekFrom) -> vfsi_sync::VfResult<u64> {
            Err(VfError::unsupported(0))
        }
        fn metadata_impl(&mut self, _: vfsi_sync::MetadataQuery) -> vfsi_sync::VfResult<VfAttrs> {
            Err(VfError::unsupported(0))
        }
        fn set_attributes_impl(&mut self, _: vfsi_sync::SetAttributes) -> vfsi_sync::VfResult<()> {
            Err(VfError::unsupported(0))
        }
    }

    impl vfsi_sync::Backend for ListingBackend {
        fn vread_impl(&mut self, _: &[ReadOp]) -> vfsi_sync::VfResult<Vec<vfsi_sync::ReadResult>> {
            Err(VfError::unsupported(0))
        }

        fn vlistdirs_impl(
            &mut self,
            dirs: &[&Path],
            masks: AttrMask,
            max_entries: usize,
            recursive: bool,
            cb: &mut dyn FnMut(&VfAttrs, &Path) -> bool,
        ) -> vfsi_sync::VfRes {
            assert!(!recursive);
            let call = {
                let mut calls = self.calls.lock().unwrap();
                calls.push(ListingCall {
                    directories: dirs.iter().map(|path| path.to_path_buf()).collect(),
                    max_entries,
                });
                calls.len()
            };
            if self.fail_call == Some(call) {
                return Err(VfError::client(0, libc::EIO as u32));
            }
            let mut delivered = 0;
            for dir in dirs {
                for entry in 0..self.entries_per_dir {
                    if max_entries != 0 && delivered >= max_entries {
                        return Ok(());
                    }
                    let returned = if self.emitted >= self.missing_after {
                        masks & !self.missing
                    } else {
                        masks
                    };
                    let attrs = VfAttrs {
                        file: VfFile::from_os_path(&dir.join(format!("entry-{entry}"))),
                        masks,
                        returned,
                        mode: libc::S_IFREG | 0o644,
                        // Zero ownership is valid when explicitly returned.
                        uid: 0,
                        gid: 0,
                        ..Default::default()
                    };
                    self.emitted += 1;
                    if !cb(&attrs, dir) {
                        return Ok(());
                    }
                    delivered += 1;
                }
            }
            Ok(())
        }
    }
    impl BindingBackend for ListingBackend {}

    struct ListingFixture {
        fs: *mut vfsi_fs,
        calls: std::sync::Arc<Mutex<Vec<ListingCall>>>,
    }
    impl ListingFixture {
        fn new(entries_per_dir: usize, missing: AttrMask, missing_after: usize) -> Self {
            Self::with_failure(entries_per_dir, missing, missing_after, None)
        }

        fn with_failure(
            entries_per_dir: usize,
            missing: AttrMask,
            missing_after: usize,
            fail_call: Option<usize>,
        ) -> Self {
            let calls = std::sync::Arc::new(Mutex::new(Vec::new()));
            Self {
                fs: make_fs(
                    Box::new(ListingBackend {
                        calls: calls.clone(),
                        entries_per_dir,
                        emitted: 0,
                        missing,
                        missing_after,
                        fail_call,
                    }),
                    PathBuf::from("/"),
                    PathBuf::from("/"),
                ),
                calls,
            }
        }

        fn run(
            &self,
            dirs: &[CString],
            options: &vfsi_listing_options,
        ) -> (c_int, Vec<usize>, Vec<vfsi_listing_result>) {
            unsafe extern "C" fn cb(
                index: usize,
                _: *const c_char,
                _: *const c_char,
                _: *const vfsi_attrs,
                user: *mut c_void,
            ) -> bool {
                let indices = &mut *(user as *mut Vec<usize>);
                indices.push(index);
                true
            }
            let pointers: Vec<_> = dirs.iter().map(|dir| dir.as_ptr()).collect();
            // Failure must clear even caller-supplied, previously successful results.
            let mut results = vec![
                vfsi_listing_result {
                    completion: 1,
                    delivered: 7
                };
                dirs.len()
            ];
            let mut indices = Vec::<usize>::new();
            let status = unsafe {
                vfsi_listdirs(
                    self.fs,
                    pointers.as_ptr(),
                    pointers.len(),
                    options,
                    Some(cb),
                    &mut indices as *mut _ as *mut c_void,
                    results.as_mut_ptr(),
                )
            };
            (status, indices, results)
        }
    }
    impl Drop for ListingFixture {
        fn drop(&mut self) {
            unsafe { vfsi_free(self.fs) };
        }
    }

    #[test]
    fn indexed_listings_reject_missing_returned_fields_before_any_callback() {
        let options = vfsi_listing_options {
            max_entries: 10,
            max_path_bytes: 1024,
            attributes: VFSI_ATTR_SIZE
                | VFSI_ATTR_NLINK
                | VFSI_ATTR_FILEID
                | VFSI_ATTR_BLOCKS
                | VFSI_ATTR_RDEV
                | VFSI_ATTR_UID
                | VFSI_ATTR_GID
                | VFSI_ATTR_ATIME
                | VFSI_ATTR_MTIME
                | VFSI_ATTR_CTIME,
        };
        let fields = AttrMask::from_bits(options.attributes).unwrap() | AttrMask::MODE;
        let dirs = [CString::new("/dir").unwrap()];
        for bit in fields.iter() {
            // A valid prefix followed by an omitted server field must not leak.
            let fixture = ListingFixture::new(2, bit, 1);
            let (status, indices, results) = fixture.run(&dirs, &options);
            assert_eq!(status, libc::ENOTSUP, "missing returned field: {bit:?}");
            assert!(indices.is_empty());
            assert!(results
                .iter()
                .all(|r| r.completion == 0 && r.delivered == 0));
        }
        let fixture = ListingFixture::new(2, AttrMask::empty(), 0);
        let (status, indices, results) = fixture.run(&dirs, &options);
        assert_eq!(status, 0, "explicitly returned zero ownership is valid");
        assert_eq!(indices, [0, 0]);
        assert_eq!(results[0].completion, 1);
        assert_eq!(results[0].delivered, 2);
    }

    #[test]
    fn indexed_listings_bound_first_page_fetches_even_with_tiny_quotas() {
        let dirs: Vec<_> = (0..97)
            .map(|n| CString::new(format!("/dir-{n}")).unwrap())
            .collect();
        for (max_entries, max_path_bytes, expected_calls) in [
            (1, usize::MAX, 1),
            (usize::MAX, 1, 1),
            (32, usize::MAX, 2),
            (33, usize::MAX, 2),
        ] {
            let fixture = ListingFixture::new(1, AttrMask::empty(), 0);
            let (status, indices, results) = fixture.run(
                &dirs,
                &vfsi_listing_options {
                    max_entries,
                    max_path_bytes,
                    attributes: VFSI_ATTR_MODE,
                },
            );
            assert_eq!(status, libc::EFBIG);
            assert!(indices.is_empty());
            assert!(results
                .iter()
                .all(|r| r.completion == 0 && r.delivered == 0));
            let calls = fixture.calls.lock().unwrap();
            assert_eq!(calls.len(), expected_calls);
            assert!(
                calls.iter().all(|call| call.directories.len() <= 32),
                "first pages must be bounded before backend callbacks"
            );
            if expected_calls == 2 {
                assert_eq!(
                    calls[1].max_entries,
                    max_entries - 32 + 1,
                    "the next cohort must receive the remaining budget plus one probe"
                );
            }
        }
    }

    #[test]
    fn indexed_listings_share_exact_budgets_across_cohorts_and_duplicate_operands() {
        let mut dirs: Vec<_> = (0..65)
            .map(|n| CString::new(format!("/dir-{n}")).unwrap())
            .collect();
        dirs.push(dirs[0].clone());
        let bytes = dirs
            .iter()
            .map(|dir| dir.as_bytes().len() + b"/entry-0".len())
            .sum();
        for (max_entries, max_path_bytes, status) in [
            (dirs.len(), bytes, 0),
            (dirs.len() - 1, bytes, libc::EFBIG),
            (dirs.len(), bytes - 1, libc::EFBIG),
        ] {
            let fixture = ListingFixture::new(1, AttrMask::empty(), 0);
            let (actual, mut indices, results) = fixture.run(
                &dirs,
                &vfsi_listing_options {
                    max_entries,
                    max_path_bytes,
                    attributes: VFSI_ATTR_MODE,
                },
            );
            assert_eq!(actual, status);
            assert_eq!(fixture.calls.lock().unwrap().len(), 3);
            if status == 0 {
                indices.sort_unstable();
                assert_eq!(indices, (0..dirs.len()).collect::<Vec<_>>());
                assert!(results
                    .iter()
                    .all(|r| r.completion == 1 && r.delivered == 1));
            } else {
                assert!(
                    indices.is_empty(),
                    "a later-cohort overflow must not leak a prefix"
                );
                assert!(results
                    .iter()
                    .all(|r| r.completion == 0 && r.delivered == 0));
            }
        }
        // Zero response budgets still allow empty roots in multiple cohorts.
        let fixture = ListingFixture::new(0, AttrMask::empty(), 0);
        let (status, indices, results) = fixture.run(
            &dirs,
            &vfsi_listing_options {
                max_entries: 0,
                max_path_bytes: 0,
                attributes: VFSI_ATTR_MODE,
            },
        );
        assert_eq!(status, 0);
        assert!(indices.is_empty());
        assert!(results
            .iter()
            .all(|r| r.completion == 1 && r.delivered == 0));
        let calls = fixture.calls.lock().unwrap();
        assert_eq!(calls.len(), 3);
        assert!(calls.iter().all(|call| call.max_entries == 1));
    }

    #[test]
    fn indexed_listings_discard_earlier_cohorts_on_late_backend_or_metadata_failure() {
        let dirs: Vec<_> = (0..65)
            .map(|n| CString::new(format!("/dir-{n}")).unwrap())
            .collect();
        let options = vfsi_listing_options {
            max_entries: dirs.len(),
            max_path_bytes: 4096,
            attributes: VFSI_ATTR_MODE | VFSI_ATTR_UID | VFSI_ATTR_GID,
        };
        for (missing, fail_call, expected) in [
            (AttrMask::empty(), Some(3), libc::EIO),
            (AttrMask::UID | AttrMask::GID, None, libc::ENOTSUP),
        ] {
            let fixture = ListingFixture::with_failure(1, missing, 32, fail_call);
            let (status, indices, results) = fixture.run(&dirs, &options);
            assert_eq!(status, expected);
            assert_eq!(fixture.calls.lock().unwrap().len(), 3);
            assert!(indices.is_empty());
            assert!(results
                .iter()
                .all(|r| r.completion == 0 && r.delivered == 0));
        }
    }

    #[test]
    fn directory_byte_overflow_stops_before_retaining_or_visiting_more_entries() {
        for max_entries in [100, usize::MAX] {
            let mut visited = 0;
            let error = collect_bounded_entries(max_entries, 1, |cb| {
                for _ in 0..100 {
                    visited += 1;
                    if !cb(&VfAttrs {
                        file: VfFile::from_path("/long-name"),
                        ..Default::default()
                    }) {
                        break;
                    }
                }
                Ok(())
            })
            .unwrap_err();
            assert_eq!(error.err_no(), libc::EFBIG as u32);
            assert_eq!(
                visited, 1,
                "overflow must stop enumeration at the first oversized entry"
            );
        }
    }

    #[test]
    fn bounded_directory_accepts_exact_limits_and_rejects_only_the_probe() {
        let entry = VfAttrs {
            file: VfFile::from_path("/a"),
            ..Default::default()
        };
        let exact = collect_bounded_entries(1, 2, |cb| {
            assert!(cb(&entry));
            Ok(())
        })
        .unwrap();
        assert_eq!(exact.len(), 1);
        for (count, bytes) in [(0, 2), (1, 1), (1, 4)] {
            let mut visited = 0;
            let error = collect_bounded_entries(count, bytes, |cb| {
                for _ in 0..3 {
                    visited += 1;
                    if !cb(&entry) {
                        break;
                    }
                }
                Ok(())
            })
            .unwrap_err();
            assert_eq!(error.err_no(), libc::EFBIG as u32);
            assert_eq!(visited, if count == 1 && bytes == 4 { 2 } else { 1 });
        }
        let error = collect_bounded_entries(10, 100, |cb| {
            assert!(cb(&entry));
            Err(VfError::client(0, libc::EIO as u32))
        })
        .unwrap_err();
        assert_eq!(
            error.err_no(),
            libc::EIO as u32,
            "backend errors must not become successful prefixes"
        );
    }

    #[test]
    fn bounded_c_adapters_prune_before_io_and_preserve_error_limits() {
        unsafe extern "C" fn walk(
            path: *const c_char,
            kind: u32,
            _depth: usize,
            _attrs: *const vfsi_attrs,
            data: *mut c_void,
        ) -> u32 {
            let (fs, visited) = &mut *(data as *mut (*mut vfsi_fs, Vec<String>));
            let path = CStr::from_ptr(path).to_string_lossy().into_owned();
            assert!(!path.ends_with("hidden"));
            assert_ne!(
                vfsi_capabilities(*fs),
                0,
                "callback must run without the backend lock"
            );
            visited.push(path.clone());
            if kind == 0 && path.ends_with("blocked") {
                1
            } else {
                0
            }
        }
        unsafe extern "C" fn listing(
            _name: *const c_char,
            _attrs: *const vfsi_attrs,
            data: *mut c_void,
        ) -> bool {
            *(data as *mut usize) += 1;
            true
        }
        unsafe extern "C" fn read(
            _path: *const c_char,
            _data: *const u8,
            _len: usize,
            data: *mut c_void,
        ) -> bool {
            *(data as *mut usize) += 1;
            true
        }
        let (root, path) = temp_root();
        std::fs::create_dir(root.path().join("blocked")).unwrap();
        std::fs::write(root.path().join("blocked/hidden"), b"hidden").unwrap();
        std::fs::write(root.path().join("a"), b"abc").unwrap();
        unsafe {
            let mut fs = std::ptr::null_mut();
            assert_eq!(
                vfsi_dummy_open_mount(path.as_ptr(), path.as_ptr(), &mut fs),
                0
            );
            let mut context = (fs, Vec::<String>::new());
            let options = vfsi_walk_options {
                max_entries: 3,
                max_path_bytes: 1024,
                max_depth: 10,
                attributes: VFSI_ATTR_MODE,
                sort_by_name: true,
            };
            assert_eq!(
                vfsi_walk(
                    fs,
                    path.as_ptr(),
                    &options,
                    Some(walk),
                    (&mut context as *mut (*mut vfsi_fs, Vec<String>)).cast()
                ),
                0
            );
            assert_eq!(context.1.len(), 5);
            let mut calls = 0usize;
            assert_eq!(
                vfsi_listdir_with_limits(
                    fs,
                    path.as_ptr(),
                    1,
                    1024,
                    Some(listing),
                    (&mut calls as *mut usize).cast()
                ),
                libc::EFBIG
            );
            let file = CString::new(root.path().join("a").as_os_str().as_bytes()).unwrap();
            assert_eq!(
                vfsi_read_paths_with_limit(
                    fs,
                    &file.as_ptr(),
                    1,
                    1,
                    Some(read),
                    (&mut calls as *mut usize).cast()
                ),
                libc::EFBIG
            );
            assert_eq!(calls, 0);
            vfsi_free(fs);
            assert_eq!(
                vfsi_nfs_from_mount(c"relative".as_ptr(), &mut fs),
                libc::EINVAL
            );
            assert!(fs.is_null());
        }
    }

    fn temp_root() -> (tempfile::TempDir, CString) {
        let root = tempfile::TempDir::new().unwrap();
        let path = CString::new(root.path().as_os_str().as_encoded_bytes()).unwrap();
        (root, path)
    }

    #[test]
    fn unknown_transport_index_remains_unknown_for_c_callers() {
        let failure = vfsi_result::from_error(VfError::transport(None, "lost reply"));
        assert_eq!(failure.index, C_INDEX_UNKNOWN);
        let mut items = [vfsi_result::panic(), vfsi_result::panic()];
        fail_results(&mut items, failure, true);
        assert!(items
            .iter()
            .all(|item| item.category == VFSI_ERROR_INDETERMINATE));
    }

    #[test]
    fn unattributed_status_keeps_its_errno_and_category_for_c_callers() {
        // A compound-level NFS status with no per-op index must still surface
        // its real errno through the scalar helpers and stay a filesystem
        // error, not be downgraded to EIO/transport.
        let error = vfsi_sync::error_from_rpc(vfsi_sync::RpcError::op(0, 10005), None);
        assert_eq!(error.index(), None);
        assert_eq!(vf_code(&error), 10005);
        let failure = vfsi_result::from_error(error);
        assert_eq!(failure.index, C_INDEX_UNKNOWN);
        assert_eq!(failure.category, VFSI_ERROR_FILESYSTEM);
        assert_eq!(failure.err_no, 10005);
    }

    #[test]
    fn close_failure_only_releases_a_confirmed_semantic_prefix() {
        assert_eq!(
            confirmed_close_prefix(&VfError::failure(2, libc::EIO as u32), 4),
            2
        );
        assert_eq!(
            confirmed_close_prefix(&VfError::transport(None, "lost reply"), 4),
            0
        );
    }

    #[test]
    fn smb_constructor_rejects_invalid_arguments_before_connecting() {
        let mut fs: *mut vfsi_fs = std::ptr::null_mut();
        assert_eq!(
            unsafe {
                vfsi_smb_open(
                    std::ptr::null(),
                    c"share".as_ptr(),
                    c"".as_ptr(),
                    c"".as_ptr(),
                    c"".as_ptr(),
                    &mut fs,
                )
            },
            libc::EINVAL
        );
        let invalid_utf8 = [0xff_u8, 0];
        assert_eq!(
            unsafe {
                vfsi_smb_open(
                    invalid_utf8.as_ptr().cast(),
                    c"share".as_ptr(),
                    c"".as_ptr(),
                    c"".as_ptr(),
                    c"".as_ptr(),
                    &mut fs,
                )
            },
            libc::EINVAL
        );
        assert!(fs.is_null());
    }

    #[test]
    fn dummy_constructor_reports_root_setup_errors() {
        let directory =
            std::env::temp_dir().join(format!("vfsi-c-invalid-root-{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&directory);
        std::fs::create_dir(&directory).unwrap();
        let file = directory.join("not-a-directory");
        std::fs::write(&file, b"x").unwrap();
        let file = CString::new(file.as_os_str().as_bytes()).unwrap();
        let mut filesystem: *mut vfsi_fs = std::ptr::null_mut();
        let result = unsafe { vfsi_dummy_open(file.as_ptr(), &mut filesystem) };
        assert!(matches!(
            result,
            value if value == libc::EEXIST || value == libc::ENOTDIR
        ));
        assert!(filesystem.is_null());
        std::fs::remove_dir_all(directory).unwrap();
    }

    #[test]
    fn dummy_backend_read_write_list() {
        let (_root, root) = temp_root();
        let mut fs: *mut vfsi_fs = std::ptr::null_mut();
        assert_eq!(unsafe { vfsi_dummy_open(root.as_ptr(), &mut fs) }, 0);
        assert!(!fs.is_null());

        let dir = CString::new("/d").unwrap();
        assert_eq!(unsafe { vfsi_mkdir(fs, dir.as_ptr(), 0o755, 1) }, 0);
        let path = CString::new("/d/f.bin").unwrap();
        let fd = unsafe {
            vfsi_open(
                fs,
                path.as_ptr(),
                libc::O_CREAT | libc::O_RDWR | libc::O_TRUNC,
                0o644,
            )
        };
        assert!(fd > 0);
        let data = b"hello".as_ptr() as *const c_void;
        assert_eq!(
            unsafe { vfsi_pwrite(fs, fd, data, 5, 0, std::ptr::null_mut()) },
            0
        );
        assert_eq!(unsafe { vfsi_close(fs, fd) }, 0);

        let mut buf = [0u8; 8];
        let fd = unsafe { vfsi_open(fs, path.as_ptr(), libc::O_RDONLY, 0) };
        assert!(fd > 0);
        let mut got = 0usize;
        assert_eq!(
            unsafe { vfsi_pread(fs, fd, buf.as_mut_ptr() as *mut c_void, 8, 0, &mut got) },
            0
        );
        assert_eq!(got, 5);
        assert_eq!(&buf[..5], b"hello");
        assert_eq!(unsafe { vfsi_close(fs, fd) }, 0);

        let mut seen: Vec<String> = Vec::new();
        unsafe extern "C" fn callback(
            name: *const c_char,
            _: *const vfsi_attrs,
            user: *mut c_void,
        ) -> bool {
            let v = &mut *(user as *mut Vec<String>);
            v.push(CStr::from_ptr(name).to_string_lossy().into_owned());
            true
        }
        assert_eq!(
            unsafe {
                vfsi_listdir(
                    fs,
                    dir.as_ptr(),
                    Some(callback),
                    &mut seen as *mut _ as *mut c_void,
                )
            },
            0
        );
        assert_eq!(seen, vec!["f.bin"]);

        unsafe { vfsi_free(fs) };
    }

    #[test]
    fn indexed_listings_report_empty_duplicates_stop_and_reject_overflow_before_callbacks() {
        let (_root, root) = temp_root();
        let mut fs = std::ptr::null_mut();
        assert_eq!(unsafe { vfsi_dummy_open(root.as_ptr(), &mut fs) }, 0);
        let dir = CString::new("/dir").unwrap();
        let empty = CString::new("/empty").unwrap();
        for path in [&dir, &empty] {
            assert_eq!(unsafe { vfsi_mkdir(fs, path.as_ptr(), 0o755, 0) }, 0);
        }
        let file = CString::new("/dir/file").unwrap();
        let fd = unsafe { vfsi_open(fs, file.as_ptr(), libc::O_CREAT | libc::O_WRONLY, 0o644) };
        assert!(fd > 0);
        assert_eq!(unsafe { vfsi_close(fs, fd) }, 0);
        struct Seen {
            fs: *mut vfsi_fs,
            indices: Vec<usize>,
            stop: bool,
        }
        unsafe extern "C" fn cb(
            index: usize,
            dir: *const c_char,
            _: *const c_char,
            _: *const vfsi_attrs,
            user: *mut c_void,
        ) -> bool {
            let seen = &mut *(user as *mut Seen);
            let mut attrs = std::mem::zeroed();
            // Re-entering must not deadlock: delivery is outside the backend lock.
            assert_eq!(vfsi_stat(seen.fs, dir, &mut attrs), 0);
            seen.indices.push(index);
            !seen.stop
        }
        let dirs = [dir.as_ptr(), empty.as_ptr(), dir.as_ptr()];
        let mut options = vfsi_listing_options {
            max_entries: 2,
            max_path_bytes: 18,
            attributes: VFSI_ATTR_MODE,
        };
        let mut results = [vfsi_listing_result::default(); 3];
        let mut seen = Seen {
            fs,
            indices: vec![],
            stop: false,
        };
        let run = |options: &vfsi_listing_options,
                   seen: &mut Seen,
                   results: &mut [vfsi_listing_result; 3]| unsafe {
            vfsi_listdirs(
                fs,
                dirs.as_ptr(),
                3,
                options,
                Some(cb),
                seen as *mut _ as *mut c_void,
                results.as_mut_ptr(),
            )
        };
        assert_eq!(run(&options, &mut seen, &mut results), 0);
        seen.indices.sort_unstable();
        assert_eq!(seen.indices, [0, 2]);
        assert!(results.iter().all(|result| result.completion == 1));
        assert_eq!(results.map(|result| result.delivered), [1, 0, 1]);
        for (entries, bytes) in [(1, 18), (2, 17)] {
            options.max_entries = entries;
            options.max_path_bytes = bytes;
            seen.indices.clear();
            assert_eq!(run(&options, &mut seen, &mut results), libc::EFBIG);
            assert!(seen.indices.is_empty());
            assert!(results
                .iter()
                .all(|result| result.completion == 0 && result.delivered == 0));
        }
        options.max_entries = 2;
        options.max_path_bytes = 18;
        seen.stop = true;
        assert_eq!(run(&options, &mut seen, &mut results), 0);
        assert_eq!(seen.indices.len(), 1);
        assert!(results.iter().all(|result| result.completion == 2));
        let missing = CString::new("/missing").unwrap();
        let bad_dirs = [dir.as_ptr(), missing.as_ptr()];
        seen.indices.clear();
        seen.stop = false;
        assert_eq!(
            unsafe {
                vfsi_listdirs(
                    fs,
                    bad_dirs.as_ptr(),
                    2,
                    &options,
                    Some(cb),
                    &mut seen as *mut _ as *mut c_void,
                    results.as_mut_ptr(),
                )
            },
            libc::ENOENT
        );
        assert!(seen.indices.is_empty());
        unsafe {
            vfsi_free(fs);
        }
    }

    #[test]
    fn dummy_backend_listdirv_maps_dirs_to_entries() {
        let (_root, root) = temp_root();
        let mut fs: *mut vfsi_fs = std::ptr::null_mut();
        assert_eq!(unsafe { vfsi_dummy_open(root.as_ptr(), &mut fs) }, 0);
        assert!(!fs.is_null());

        let d1 = CString::new("/v/d1").unwrap();
        let d2 = CString::new("/v/d2").unwrap();
        assert_eq!(unsafe { vfsi_mkdir(fs, d1.as_ptr(), 0o755, 1) }, 0);
        assert_eq!(unsafe { vfsi_mkdir(fs, d2.as_ptr(), 0o755, 1) }, 0);
        let p1 = CString::new("/v/d1/one.bin").unwrap();
        let p2 = CString::new("/v/d2/two.bin").unwrap();
        for p in [&p1, &p2] {
            let fd = unsafe {
                vfsi_open(
                    fs,
                    p.as_ptr(),
                    libc::O_CREAT | libc::O_RDWR | libc::O_TRUNC,
                    0o644,
                )
            };
            assert!(fd > 0);
            assert_eq!(unsafe { vfsi_close(fs, fd) }, 0);
        }

        #[derive(Default)]
        struct Seen {
            rows: Vec<(String, String)>,
        }
        unsafe extern "C" fn cb(
            dir: *const c_char,
            name: *const c_char,
            _: *const vfsi_attrs,
            user: *mut c_void,
        ) -> bool {
            let seen = &mut *(user as *mut Seen);
            seen.rows.push((
                CStr::from_ptr(dir).to_string_lossy().into_owned(),
                CStr::from_ptr(name).to_string_lossy().into_owned(),
            ));
            true
        }

        let dirs = [d1.as_ptr(), d2.as_ptr()];
        let mut seen = Seen::default();
        assert_eq!(
            unsafe {
                vfsi_listdirv(
                    fs,
                    dirs.as_ptr(),
                    dirs.len(),
                    0,
                    false,
                    Some(cb),
                    &mut seen as *mut _ as *mut c_void,
                )
            },
            0
        );
        assert_eq!(
            seen.rows,
            vec![
                ("/v/d1".to_string(), "one.bin".to_string()),
                ("/v/d2".to_string(), "two.bin".to_string()),
            ]
        );

        let sub = CString::new("/v/d1/sub").unwrap();
        let nested = CString::new("/v/d1/sub/nested.bin").unwrap();
        assert_eq!(unsafe { vfsi_mkdir(fs, sub.as_ptr(), 0o755, 1) }, 0);
        let fd = unsafe {
            vfsi_open(
                fs,
                nested.as_ptr(),
                libc::O_CREAT | libc::O_RDWR | libc::O_TRUNC,
                0o644,
            )
        };
        assert!(fd > 0);
        assert_eq!(unsafe { vfsi_close(fs, fd) }, 0);
        let one_dir = [d1.as_ptr()];
        seen.rows.clear();
        assert_eq!(
            unsafe {
                vfsi_listdirv(
                    fs,
                    one_dir.as_ptr(),
                    one_dir.len(),
                    0,
                    true,
                    Some(cb),
                    &mut seen as *mut _ as *mut c_void,
                )
            },
            0
        );
        assert!(seen
            .rows
            .contains(&("/v/d1/sub".to_string(), "nested.bin".to_string())));

        unsafe { vfsi_free(fs) };
    }

    #[test]
    fn listdirv_callback_can_reenter_filesystem() {
        if vfsi_sync::test_support::supervise_with_deadline(
            "tests::listdirv_callback_can_reenter_filesystem",
        ) {
            return;
        }
        let (_root, root) = temp_root();
        let mut fs: *mut vfsi_fs = std::ptr::null_mut();
        assert_eq!(unsafe { vfsi_dummy_open(root.as_ptr(), &mut fs) }, 0);
        let dir = CString::new("/reentrant").unwrap();
        let path = CString::new("/reentrant/file").unwrap();
        assert_eq!(unsafe { vfsi_mkdir(fs, dir.as_ptr(), 0o755, 1) }, 0);
        let fd = unsafe { vfsi_open(fs, path.as_ptr(), libc::O_CREAT | libc::O_RDWR, 0o644) };
        assert!(fd > 0);
        assert_eq!(unsafe { vfsi_close(fs, fd) }, 0);

        struct Reentrant {
            fs: *mut vfsi_fs,
            path: CString,
            stat_result: c_int,
        }
        unsafe extern "C" fn cb(
            _: *const c_char,
            _: *const c_char,
            _: *const vfsi_attrs,
            user: *mut c_void,
        ) -> bool {
            let state = &mut *(user as *mut Reentrant);
            let mut attrs = std::mem::zeroed();
            state.stat_result = vfsi_stat(state.fs, state.path.as_ptr(), &mut attrs);
            false
        }

        let dirs = [dir.as_ptr()];
        let mut state = Reentrant {
            fs,
            path,
            stat_result: -1,
        };
        assert_eq!(
            unsafe {
                vfsi_listdirv(
                    fs,
                    dirs.as_ptr(),
                    dirs.len(),
                    0,
                    false,
                    Some(cb),
                    &mut state as *mut _ as *mut c_void,
                )
            },
            0
        );
        assert_eq!(state.stat_result, 0);
        unsafe { vfsi_free(fs) };
    }

    #[test]
    fn poisoned_backend_mutex_returns_eio() {
        let (_root, root) = temp_root();
        let mut fs: *mut vfsi_fs = std::ptr::null_mut();
        assert_eq!(unsafe { vfsi_dummy_open(root.as_ptr(), &mut fs) }, 0);
        let handle = unsafe { &*fs };
        let _ = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
            let _guard = handle.fs.lock().unwrap();
            panic!("poison backend mutex");
        }));

        let path = CString::new("/").unwrap();
        let mut attrs = unsafe { std::mem::zeroed() };
        assert_eq!(
            unsafe { vfsi_stat(fs, path.as_ptr(), &mut attrs) },
            libc::EIO
        );
        unsafe { vfsi_free(fs) };
    }

    #[test]
    fn dummy_open_mount_accepts_kernel_paths() {
        let (_root, root) = temp_root();
        let mut fs: *mut vfsi_fs = std::ptr::null_mut();
        assert_eq!(
            unsafe { vfsi_dummy_open_mount(root.as_ptr(), root.as_ptr(), &mut fs) },
            0
        );
        assert!(!fs.is_null());

        let mut path = root.as_bytes().to_vec();
        path.extend_from_slice(b"/mount-dir/file.bin");
        let path = CString::new(path).unwrap();
        let mut dir = root.as_bytes().to_vec();
        dir.extend_from_slice(b"/mount-dir");
        let dir = CString::new(dir).unwrap();

        assert_eq!(unsafe { vfsi_mkdir(fs, dir.as_ptr(), 0o755, 1) }, 0);
        let fd = unsafe {
            vfsi_open(
                fs,
                path.as_ptr(),
                libc::O_CREAT | libc::O_RDWR | libc::O_TRUNC,
                0o644,
            )
        };
        assert!(fd > 0);
        assert_eq!(unsafe { vfsi_close(fs, fd) }, 0);
        assert_eq!(unsafe { vfsi_remove(fs, path.as_ptr()) }, 0);
        assert_eq!(unsafe { vfsi_remove(fs, dir.as_ptr()) }, 0);

        unsafe { vfsi_free(fs) };
    }

    #[test]
    fn mount_mapping_includes_backend_root_and_rejects_escape() {
        let (_root, root) = temp_root();
        let backend = Box::new(DummyVecFs::new(PathBuf::from(
            root.to_string_lossy().into_owned(),
        ))) as Box<dyn BindingBackend>;
        let raw = make_fs(
            backend,
            PathBuf::from("/mnt/repos"),
            PathBuf::from("/exports/git"),
        );
        let fs = unsafe { &*raw };

        assert_eq!(
            path_for(fs, Path::new("/mnt/repos/project/objects")),
            Some(PathBuf::from("/exports/git/project/objects"))
        );
        assert_eq!(path_for(fs, Path::new("/mnt/repos/../escape")), None);

        unsafe { vfsi_free(raw) };
    }

    #[test]
    fn read_paths_batches_full_file_contents() {
        let (_root, root) = temp_root();
        let mut fs: *mut vfsi_fs = std::ptr::null_mut();
        assert_eq!(
            unsafe { vfsi_dummy_open_mount(root.as_ptr(), root.as_ptr(), &mut fs) },
            0
        );
        assert!(!fs.is_null());

        let mut dir = root.as_bytes().to_vec();
        dir.extend_from_slice(b"/read-dir");
        let dir = CString::new(dir).unwrap();
        assert_eq!(unsafe { vfsi_mkdir(fs, dir.as_ptr(), 0o755, 1) }, 0);

        let path_a = {
            let mut p = dir.as_bytes().to_vec();
            p.extend_from_slice(b"/a.bin");
            CString::new(p).unwrap()
        };
        let path_b = {
            let mut p = dir.as_bytes().to_vec();
            p.extend_from_slice(b"/b.bin");
            CString::new(p).unwrap()
        };
        for (path, contents) in [(&path_a, &b"first"[..]), (&path_b, &b"second-longer"[..])] {
            let fd = unsafe {
                vfsi_open(
                    fs,
                    path.as_ptr(),
                    libc::O_CREAT | libc::O_RDWR | libc::O_TRUNC,
                    0o644,
                )
            };
            assert!(fd > 0);
            assert_eq!(
                unsafe {
                    vfsi_pwrite(
                        fs,
                        fd,
                        contents.as_ptr() as *const c_void,
                        contents.len(),
                        0,
                        std::ptr::null_mut(),
                    )
                },
                0
            );
            assert_eq!(unsafe { vfsi_close(fs, fd) }, 0);
        }

        #[derive(Default)]
        struct Seen {
            rows: Vec<(String, Vec<u8>)>,
        }
        unsafe extern "C" fn cb(
            path: *const c_char,
            data: *const u8,
            len: usize,
            user: *mut c_void,
        ) -> bool {
            let seen = &mut *(user as *mut Seen);
            let bytes = unsafe { std::slice::from_raw_parts(data, len) };
            seen.rows.push((
                CStr::from_ptr(path).to_string_lossy().into_owned(),
                bytes.to_vec(),
            ));
            true
        }

        let paths = [path_a.as_ptr(), path_b.as_ptr()];
        let mut seen = Seen::default();
        assert_eq!(
            unsafe {
                vfsi_read_paths(
                    fs,
                    paths.as_ptr(),
                    paths.len(),
                    Some(cb),
                    &mut seen as *mut _ as *mut c_void,
                )
            },
            0
        );
        assert_eq!(seen.rows[0].1, b"first");
        assert_eq!(seen.rows[1].1, b"second-longer");

        unsafe { vfsi_free(fs) };
    }

    #[test]
    fn abi_v3_vector_io_and_bounded_streaming() {
        let (_root, root) = temp_root();
        let mut fs: *mut vfsi_fs = std::ptr::null_mut();
        assert_eq!(unsafe { vfsi_dummy_open(root.as_ptr(), &mut fs) }, 0);
        let mut item_results = [vfsi_result::panic(); 2];
        let mut one_result = [vfsi_result::panic(); 1];

        let dir_a = CString::new("/v3-a").unwrap();
        let dir_b = CString::new("/v3-b").unwrap();
        let mkdir_ops = [
            vfsi_mkdir_op {
                path: dir_a.as_ptr(),
                mode: 0o755,
            },
            vfsi_mkdir_op {
                path: dir_b.as_ptr(),
                mode: 0o755,
            },
        ];
        let result = unsafe {
            vfsi_mkdirv(
                fs,
                mkdir_ops.as_ptr(),
                mkdir_ops.len(),
                item_results.as_mut_ptr(),
            )
        };
        assert_eq!(result.category, VFSI_ERROR_NONE);
        assert_eq!(result.index, 2);
        assert!(item_results
            .iter()
            .all(|result| result.category == VFSI_ERROR_NONE));

        let path_a = CString::new("/v3-a/a.bin").unwrap();
        let path_b = CString::new("/v3-b/b.bin").unwrap();
        let mut open_ops = [
            vfsi_open_op {
                path: path_a.as_ptr(),
                flags: libc::O_CREAT | libc::O_RDWR | libc::O_TRUNC,
                mode: 0o644,
                fd: -1,
            },
            vfsi_open_op {
                path: path_b.as_ptr(),
                flags: libc::O_CREAT | libc::O_RDWR | libc::O_TRUNC,
                mode: 0o644,
                fd: -1,
            },
        ];
        let result = unsafe {
            vfsi_openv(
                fs,
                open_ops.as_mut_ptr(),
                open_ops.len(),
                item_results.as_mut_ptr(),
            )
        };
        assert_eq!(result.category, VFSI_ERROR_NONE);
        assert!(open_ops.iter().all(|op| op.fd > 0));

        let data_a = b"abcdef";
        let data_b = b"1234567";
        let mut writes = [
            vfsi_pwrite_op {
                fd: open_ops[0].fd,
                buf: data_a.as_ptr().cast(),
                len: data_a.len(),
                offset: 0,
                wrote: 0,
            },
            vfsi_pwrite_op {
                fd: open_ops[1].fd,
                buf: data_b.as_ptr().cast(),
                len: data_b.len(),
                offset: 0,
                wrote: 0,
            },
        ];
        assert_eq!(
            unsafe {
                vfsi_pwritev(
                    fs,
                    writes.as_mut_ptr(),
                    writes.len(),
                    item_results.as_mut_ptr(),
                )
            }
            .category,
            VFSI_ERROR_NONE
        );
        assert_eq!([writes[0].wrote, writes[1].wrote], [6, 7]);

        let mut buf_a = [0u8; 8];
        let mut buf_b = [0u8; 8];
        let mut reads = [
            vfsi_pread_op {
                fd: open_ops[0].fd,
                buf: buf_a.as_mut_ptr().cast(),
                len: buf_a.len(),
                offset: 0,
                got: 0,
            },
            vfsi_pread_op {
                fd: open_ops[1].fd,
                buf: buf_b.as_mut_ptr().cast(),
                len: buf_b.len(),
                offset: 0,
                got: 0,
            },
        ];
        assert_eq!(
            unsafe {
                vfsi_preadv(
                    fs,
                    reads.as_mut_ptr(),
                    reads.len(),
                    item_results.as_mut_ptr(),
                )
            }
            .category,
            VFSI_ERROR_NONE
        );
        assert_eq!(&buf_a[..reads[0].got], data_a);
        assert_eq!(&buf_b[..reads[1].got], data_b);

        let fds = [open_ops[0].fd, open_ops[1].fd];
        assert_eq!(
            unsafe { vfsi_closev(fs, fds.as_ptr(), fds.len(), item_results.as_mut_ptr(),) }
                .category,
            VFSI_ERROR_NONE
        );

        #[derive(Default)]
        struct Streamed {
            files: [Vec<u8>; 2],
            max_chunk: usize,
        }
        unsafe extern "C" fn stream_cb(
            _: *const c_char,
            index: usize,
            _: u64,
            data: *const u8,
            len: usize,
            _: bool,
            userdata: *mut c_void,
        ) -> bool {
            let state = &mut *userdata.cast::<Streamed>();
            state.max_chunk = state.max_chunk.max(len);
            state.files[index].extend_from_slice(std::slice::from_raw_parts(data, len));
            true
        }
        let paths = [path_a.as_ptr(), path_b.as_ptr()];
        let mut streamed = Streamed::default();
        let result = unsafe {
            vfsi_read_streamv(
                fs,
                paths.as_ptr(),
                paths.len(),
                3,
                4,
                Some(stream_cb),
                &mut streamed as *mut _ as *mut c_void,
            )
        };
        assert_eq!(result.category, VFSI_ERROR_NONE);
        assert!(streamed.max_chunk <= 3);
        assert_eq!(streamed.files[0], data_a);
        assert_eq!(streamed.files[1], data_b);

        let mut stats = [
            vfsi_stat_op {
                path: path_a.as_ptr(),
                attrs: unsafe { std::mem::zeroed() },
            },
            vfsi_stat_op {
                path: path_b.as_ptr(),
                attrs: unsafe { std::mem::zeroed() },
            },
        ];
        assert_eq!(
            unsafe {
                vfsi_statv(
                    fs,
                    stats.as_mut_ptr(),
                    stats.len(),
                    item_results.as_mut_ptr(),
                )
            }
            .category,
            VFSI_ERROR_NONE
        );
        assert_eq!([stats[0].attrs.size, stats[1].attrs.size], [6, 7]);

        let setattr = [vfsi_setattr_op {
            path: path_a.as_ptr(),
            mask: VFSI_ATTR_SIZE,
            mode: 0,
            size: 2,
            atime_sec: 0,
            atime_nsec: 0,
            mtime_sec: 0,
            mtime_nsec: 0,
        }];
        assert_eq!(
            unsafe { vfsi_setattrv(fs, setattr.as_ptr(), setattr.len(), one_result.as_mut_ptr(),) }
                .category,
            VFSI_ERROR_NONE
        );

        let renamed_a = CString::new("/v3-a/renamed.bin").unwrap();
        let renamed_b = CString::new("/v3-b/renamed.bin").unwrap();
        let renames = [
            vfsi_rename_op {
                oldpath: path_a.as_ptr(),
                newpath: renamed_a.as_ptr(),
            },
            vfsi_rename_op {
                oldpath: path_b.as_ptr(),
                newpath: renamed_b.as_ptr(),
            },
        ];
        assert_eq!(
            unsafe {
                vfsi_renamev(
                    fs,
                    renames.as_ptr(),
                    renames.len(),
                    item_results.as_mut_ptr(),
                )
            }
            .category,
            VFSI_ERROR_NONE
        );
        let remove_paths = [renamed_a.as_ptr(), renamed_b.as_ptr()];
        assert_eq!(
            unsafe {
                vfsi_removev(
                    fs,
                    remove_paths.as_ptr(),
                    remove_paths.len(),
                    item_results.as_mut_ptr(),
                )
            }
            .category,
            VFSI_ERROR_NONE
        );
        assert_eq!(
            unsafe {
                vfsi_removev(
                    fs,
                    [dir_a.as_ptr(), dir_b.as_ptr()].as_ptr(),
                    2,
                    item_results.as_mut_ptr(),
                )
            }
            .category,
            VFSI_ERROR_NONE
        );

        let missing = CString::new("/missing").unwrap();
        let root_path = CString::new("/").unwrap();
        let mut failed_stats = [
            vfsi_stat_op {
                path: missing.as_ptr(),
                attrs: unsafe { std::mem::zeroed() },
            },
            vfsi_stat_op {
                path: root_path.as_ptr(),
                attrs: unsafe { std::mem::zeroed() },
            },
        ];
        let failed = unsafe {
            vfsi_statv(
                fs,
                failed_stats.as_mut_ptr(),
                failed_stats.len(),
                item_results.as_mut_ptr(),
            )
        };
        assert_eq!(failed.index, 0);
        assert_eq!(failed.category, VFSI_ERROR_FILESYSTEM);
        assert_eq!(item_results[0].category, VFSI_ERROR_FILESYSTEM);
        assert_eq!(item_results[1].category, VFSI_ERROR_INDETERMINATE);
        unsafe { vfsi_free(fs) };
    }
}