drmkit-scene-sources 0.1.2

Tier-1 buffer sources for drmkit scenes: dumb buffers and imported DMA-BUFs.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
// SPDX-FileCopyrightText: (c) 2026 Joel Winarske
// SPDX-License-Identifier: MIT

//! Tests for the tier-1 sources.
//!
//! Allocating a dumb buffer needs a card, so those cases are `#[ignore]`d and
//! run under the vkms lane with `--include-ignored` — the same convention as
//! `drmkit-core` and `drmkit-dumb`. The damage bookkeeping needs no card and
//! runs everywhere.

use super::*;
use std::sync::Mutex;

use drmkit_core::Device;
use drmkit_dumb::MapAccess;
use drmkit_scene::{AcquiredBuffer, BindingModel, DamageRect, LayerBufferSource, SourceError};
use drmkit_sync::SyncFence;

/// `Device::open` acquires DRM master, which is per open file description, so
/// card-dependent cases serialize rather than racing for it.
static CARD_LOCK: Mutex<()> = Mutex::new(());

fn card_guard() -> std::sync::MutexGuard<'static, ()> {
    CARD_LOCK
        .lock()
        .unwrap_or_else(std::sync::PoisonError::into_inner)
}

/// Open the card, or `None` if this machine has no vkms.
///
/// Absence of the device is a different condition from the device being there
/// and misbehaving. Locally it means vkms is not loaded, which is a skip; in
/// the lane it means the lane is not testing what it claims, which is a
/// failure — the same line `DRMKIT_REQUIRE_MASTER` already draws for DRM
/// master. Everything past this point still asserts.
fn open_card() -> Option<Device> {
    let path = std::env::var("DRMKIT_TEST_CARD").unwrap_or_else(|_| "/dev/dri/card0".to_owned());
    match Device::open(&path) {
        Ok(device) => Some(device),
        Err(error) => {
            assert!(
                std::env::var_os("DRMKIT_REQUIRE_MASTER").is_none(),
                "{path}: {error}, but DRMKIT_REQUIRE_MASTER is set"
            );
            println!("note: skipped -- no DRM device at {path} ({error})");
            None
        }
    }
}

/// The format every KMS driver accepts for a dumb buffer.
///
/// Taken from `drmkit-fmt` rather than written as a literal: the first version
/// of this file hardcoded `0x3234_5258`, which transposes two digits of the
/// real `XR24` code and made every allocation fail with "not a recognized DRM
/// `FourCC`". There is a constant for exactly this reason.
use drmkit_fmt::fourcc::XRGB8888;

#[test]
#[ignore = "needs a DRM device; run under the vkms lane with --include-ignored"]
fn a_dumb_source_hands_out_a_stable_framebuffer_vkms() {
    let _guard = card_guard();
    let Some(device) = open_card() else { return };
    let mut source = DumbBufferSource::create(&device, 64, 64, XRGB8888).expect("create");

    assert_eq!(source.format().width, 64);
    assert_eq!(source.format().height, 64);
    assert_eq!(source.format().fourcc, XRGB8888);
    assert_eq!(source.format().modifier, 0, "a dumb buffer is linear");
    assert_eq!(source.binding_model(), BindingModel::SceneSubmitsFbId);

    let first = source.acquire().expect("acquire");
    assert_ne!(first.fb_id, 0);
    let fb = first.fb_id;
    source.release(first);

    let second = source.acquire().expect("acquire again");
    assert_eq!(
        second.fb_id, fb,
        "a single-buffer source hands out the same framebuffer every frame"
    );
    source.release(second);
}

/// The mapping is a real, writable view, and reading it back proves it is
/// coherent — which is what lets a software producer paint straight into the
/// scanout buffer.
#[test]
#[ignore = "needs a DRM device; run under the vkms lane with --include-ignored"]
fn a_dumb_source_maps_a_writable_coherent_view_vkms() {
    let _guard = card_guard();
    let Some(device) = open_card() else { return };
    let mut source = DumbBufferSource::create(&device, 32, 32, XRGB8888).expect("create");

    {
        let mut view = source.map(MapAccess::Write).expect("map");
        assert_eq!(view.width(), 32);
        assert_eq!(view.height(), 32);
        view.row_mut(0).expect("row 0").fill(0xab);
    }

    let view = source.map(MapAccess::Read).expect("map");
    assert!(view.row(0).expect("row 0").iter().all(|b| *b == 0xab));
}

/// The kernel zero-fills a dumb buffer, so the first frame is transparent
/// rather than whatever was in memory.
#[test]
#[ignore = "needs a DRM device; run under the vkms lane with --include-ignored"]
fn a_fresh_dumb_source_starts_zeroed_vkms() {
    let _guard = card_guard();
    let Some(device) = open_card() else { return };
    let mut source = DumbBufferSource::create(&device, 32, 32, XRGB8888).expect("create");

    let view = source.map(MapAccess::Read).expect("map");
    assert!(
        view.pixels().iter().all(|b| *b == 0),
        "the first acquire must not present uninitialized memory"
    );
}

/// A session resume re-allocates against the new device and preserves the
/// shape: consumers rely on `format()` returning the same value across it.
#[test]
#[ignore = "needs a DRM device; run under the vkms lane with --include-ignored"]
fn a_session_resume_preserves_the_source_format_vkms() {
    let _guard = card_guard();
    let Some(device) = open_card() else { return };
    let mut source = DumbBufferSource::create(&device, 48, 24, XRGB8888).expect("create");

    let before = source.format();
    let old_fb = source.acquire().expect("acquire").fb_id;

    source.on_session_paused();
    source
        .on_session_resumed(&device)
        .expect("re-allocate on resume");

    assert_eq!(source.format(), before, "the shape must survive a resume");
    let after_fb = source.acquire().expect("acquire").fb_id;
    assert_ne!(
        after_fb, 0,
        "the source must be usable again after a resume"
    );
    let _ = old_fb;
}

/// A packed format is allocated at its own depth, as the reference sizes it:
/// a 16-bit format gets a 16-bit stride, and keeps it across a resume.
#[test]
#[ignore = "needs a DRM device; run under the vkms lane with --include-ignored"]
fn a_dumb_source_allocates_at_the_formats_depth_vkms() {
    let _guard = card_guard();
    let Some(device) = open_card() else { return };
    let width = 64;
    let mut source =
        DumbBufferSource::create(&device, width, 16, drmkit_fmt::fourcc::RGB565).expect("create");
    assert_eq!(source.buffer().stride(), width * 2, "two bytes a pixel");

    source.on_session_paused();
    source.on_session_resumed(&device).expect("resume");
    assert_eq!(
        source.buffer().stride(),
        width * 2,
        "the resumed allocation follows the format too"
    );
}

/// A semi-planar format is one allocation holding both planes, registered as
/// two: the reference's `create_planar` path. At 32 bpp and one plane the
/// kernel refuses the framebuffer.
#[test]
#[ignore = "needs a DRM device; run under the vkms lane with --include-ignored"]
fn a_dumb_source_allocates_a_semiplanar_format_vkms() {
    let _guard = card_guard();
    let Some(device) = open_card() else { return };
    let mut source =
        DumbBufferSource::create(&device, 64, 32, drmkit_fmt::fourcc::NV12).expect("create NV12");
    assert_ne!(source.acquire().expect("acquire").fb_id, 0);
}

/// A format with no known depth is refused before anything is allocated,
/// as the reference refuses it with `EINVAL`.
#[test]
#[ignore = "needs a DRM device; run under the vkms lane with --include-ignored"]
fn a_dumb_source_refuses_a_format_it_cannot_size_vkms() {
    let _guard = card_guard();
    let Some(device) = open_card() else { return };
    let created = DumbBufferSource::create(&device, 64, 32, drmkit_fmt::fourcc::YUV420);
    assert!(
        matches!(created, Err(drmkit_dumb::DumbError::InvalidConfig { .. })),
        "{created:?}"
    );
}

/// Repeated resumes must not leak: each one forgets the old handles and
/// allocates fresh. Measured as descriptor-table growth, for the same reason as
/// the other leak tests — an absolute count races the parallel harness.
#[test]
#[ignore = "needs a DRM device; run under the vkms lane with --include-ignored"]
fn repeated_session_resumes_do_not_leak_vkms() {
    let _guard = card_guard();
    let Some(device) = open_card() else { return };
    let mut source = DumbBufferSource::create(&device, 32, 32, XRGB8888).expect("create");

    let count = || {
        std::fs::read_dir("/proc/self/fd")
            .expect("/proc/self/fd")
            .count()
    };

    for _ in 0..8 {
        source.on_session_resumed(&device).expect("resume");
    }
    let after_few = count();

    for _ in 0..120 {
        source.on_session_resumed(&device).expect("resume");
    }
    let after_many = count();

    let growth = after_many.saturating_sub(after_few);
    assert!(
        growth < 16,
        "120 further resumes grew the fd table by {growth}"
    );
}

// --- damage bookkeeping, no card needed --------------------------------------

/// A source with no buffer cannot acquire — and says so as a failure, not as
/// flow control, because there is nothing to wait for.
#[test]
fn acquiring_without_a_framebuffer_is_a_failure_not_a_skip() {
    // A source can only reach this state through a failed allocation, which
    // `create` reports instead of returning. The distinction still matters:
    // `WouldBlock` means "try next frame", and there is no next frame here.
    let error = SourceError::Failed(rustix::io::Errno::INVAL);
    assert!(
        !matches!(error, SourceError::WouldBlock),
        "a missing framebuffer is not something a later frame will fix"
    );
}

/// Damage is handed over on acquire and cleared, so the next frame starts from
/// full-frame unless the producer says otherwise.
#[test]
#[ignore = "needs a DRM device; run under the vkms lane with --include-ignored"]
fn damage_is_reported_once_then_cleared_vkms() {
    let _guard = card_guard();
    let Some(device) = open_card() else { return };
    let mut source = DumbBufferSource::create(&device, 64, 64, XRGB8888).expect("create");

    let dirty = [DamageRect {
        x: 4,
        y: 8,
        w: 16,
        h: 16,
    }];
    source.set_damage(&dirty);

    let first = source.acquire().expect("acquire");
    assert_eq!(first.damage.len(), 1);
    assert_eq!(first.damage[0].x, 4);
    assert_eq!(first.damage[0].w, 16);
    source.release(first);

    let second = source.acquire().expect("acquire");
    assert!(
        second.damage.is_empty(),
        "damage describes one frame; an unset next frame means full-frame"
    );
    source.release(second);
}

/// Setting damage twice replaces rather than accumulates: the producer knows
/// what it just painted, and merging a stale region would over-report.
#[test]
#[ignore = "needs a DRM device; run under the vkms lane with --include-ignored"]
fn setting_damage_replaces_the_previous_set_vkms() {
    let _guard = card_guard();
    let Some(device) = open_card() else { return };
    let mut source = DumbBufferSource::create(&device, 64, 64, XRGB8888).expect("create");

    source.set_damage(&[DamageRect {
        x: 0,
        y: 0,
        w: 8,
        h: 8,
    }]);
    source.set_damage(&[DamageRect {
        x: 32,
        y: 32,
        w: 4,
        h: 4,
    }]);

    let acquired = source.acquire().expect("acquire");
    assert_eq!(acquired.damage.len(), 1, "the earlier set is replaced");
    assert_eq!(acquired.damage[0].x, 32);
    source.release(acquired);
}

/// An empty damage set means full-frame, which is correct but not
/// power-optimal — the scene emits no clips at all.
#[test]
#[ignore = "needs a DRM device; run under the vkms lane with --include-ignored"]
fn empty_damage_means_full_frame_vkms() {
    let _guard = card_guard();
    let Some(device) = open_card() else { return };
    let mut source = DumbBufferSource::create(&device, 64, 64, XRGB8888).expect("create");

    source.set_damage(&[DamageRect {
        x: 0,
        y: 0,
        w: 8,
        h: 8,
    }]);
    source.set_damage(&[]);

    let acquired = source.acquire().expect("acquire");
    assert!(acquired.damage.is_empty());
    source.release(acquired);
}

// --- ExternalDmaBufSource: the acquire-fence dup (plan §4.9, upstream #230) --

use std::os::fd::{AsFd as _, AsRawFd as _, OwnedFd};
use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};

use drmkit_scene::SourceFormat;

/// An eventfd standing in for a producer's render-done fence.
fn fake_fence() -> OwnedFd {
    rustix::event::eventfd(0, rustix::event::EventfdFlags::CLOEXEC).expect("eventfd")
}

/// A descriptor for the validation cases, which are rejected before any ioctl.
fn placeholder_fd() -> OwnedFd {
    rustix::event::eventfd(0, rustix::event::EventfdFlags::CLOEXEC).expect("eventfd")
}

/// A **real** dma-buf, made by allocating a dumb buffer and exporting its GEM
/// handle through PRIME.
///
/// The first version of these tests fed an eventfd to `create` and fell back to
/// a skip when the driver refused it. Every one of the fence cases took that
/// path -- four silent skips, including the §4.9 pin this chunk exists for. A
/// test that skips on the only interesting configuration is not a test.
///
/// Returns the descriptor and the pitch the kernel chose, which the caller
/// needs for the plane description. The dumb buffer is dropped: the exported
/// descriptor keeps the underlying object alive.
fn real_dma_buf(device: &Device, width: u32, height: u32) -> Option<(OwnedFd, u32)> {
    use drm::control::Device as _;

    let buffer = drmkit_dumb::Buffer::create(
        device,
        &drmkit_dumb::Config {
            width,
            height,
            fourcc: XRGB8888,
            add_fb: false,
            ..drmkit_dumb::Config::default()
        },
    )
    .ok()?;

    let handle = drm::control::from_u32(buffer.gem_handle()?)?;
    let pitch = buffer.stride();
    let fd = device.buffer_to_prime_fd(handle, 0).ok()?;
    Some((fd, pitch))
}

fn plane(fd: &OwnedFd) -> ExternalPlane<'_> {
    ExternalPlane {
        fd: fd.as_fd(),
        offset: 0,
        pitch: 256,
    }
}

fn external_format() -> SourceFormat {
    SourceFormat {
        fourcc: XRGB8888,
        modifier: 0,
        width: 64,
        height: 64,
    }
}

/// An import's GEM handles go when it does.
///
/// Each handle holds a reference to its dma-buf, so one left open pins the
/// buffer until the device descriptor closes -- a producer cycling through
/// buffers would grow kernel memory without bound, eviction or not. The
/// reference closes them after removing the framebuffer.
///
/// The buffer is allocated on one open of the card and imported on another,
/// so the importing file has no handle of its own for it: re-importing while
/// the source lives finds the source's handle, and once the source is gone a
/// close of that handle must be refused as already closed.
#[test]
#[ignore = "needs a DRM device; run under the vkms lane with --include-ignored"]
fn an_import_closes_its_gem_handles_vkms() {
    use drm::control::Device as _;

    let _guard = card_guard();
    let Some(exporter) = open_card() else { return };
    let Some(importer) = open_card() else { return };
    let Some((fd, pitch)) = real_dma_buf(&exporter, 64, 64) else {
        panic!("vkms allocates and exports a dumb buffer");
    };
    let planes = [ExternalPlane {
        fd: fd.as_fd(),
        offset: 0,
        pitch,
    }];

    let source =
        ExternalDmaBufSource::create(&importer, external_format(), &planes, None).expect("import");
    let handle = importer
        .prime_fd_to_buffer(fd.as_fd())
        .expect("the source's handle, found again");
    drop(source);

    assert!(
        importer.close_buffer(handle).is_err(),
        "the source left its GEM handle open"
    );
}

/// A failed import closes what it imported before the kernel refused it.
///
/// A pitch too narrow for the width passes every check here and is refused at
/// `AddFB2`, after the handle exists: the reference unwinds that import, and
/// so must this.
#[test]
#[ignore = "needs a DRM device; run under the vkms lane with --include-ignored"]
fn a_refused_import_closes_its_gem_handles_vkms() {
    use drm::control::Device as _;

    let _guard = card_guard();
    let Some(exporter) = open_card() else { return };
    let Some(importer) = open_card() else { return };
    let Some((fd, _)) = real_dma_buf(&exporter, 64, 64) else {
        panic!("vkms allocates and exports a dumb buffer");
    };
    // Imported first, so the handle is known; the source's import finds the
    // same one.
    let handle = importer.prime_fd_to_buffer(fd.as_fd()).expect("import");
    let narrow = [ExternalPlane {
        fd: fd.as_fd(),
        offset: 0,
        pitch: 4,
    }];

    assert!(
        ExternalDmaBufSource::create(&importer, external_format(), &narrow, None).is_err(),
        "a 4-byte pitch cannot hold a 64-pixel row"
    );
    assert!(
        importer.close_buffer(handle).is_err(),
        "the failed import left its GEM handle open"
    );
}

// --- validation, no card needed ---------------------------------------------

#[test]
#[ignore = "needs a DRM device; run under the vkms lane with --include-ignored"]
fn external_create_rejects_unusable_shapes_vkms() {
    let _guard = card_guard();
    let Some(device) = open_card() else { return };
    let fd = placeholder_fd();

    let cases: [(SourceFormat, &str); 3] = [
        (
            SourceFormat {
                width: 0,
                ..external_format()
            },
            "zero width",
        ),
        (
            SourceFormat {
                height: 0,
                ..external_format()
            },
            "zero height",
        ),
        (
            SourceFormat {
                fourcc: 0,
                ..external_format()
            },
            "zero format",
        ),
    ];

    for (format, what) in cases {
        assert!(
            matches!(
                ExternalDmaBufSource::create(&device, format, &[plane(&fd)], None),
                Err(ExternalError::Invalid { .. })
            ),
            "{what} must be rejected"
        );
    }

    // No planes, and a plane with no pitch.
    assert!(matches!(
        ExternalDmaBufSource::create(&device, external_format(), &[], None),
        Err(ExternalError::Invalid { .. })
    ));
    let bad_pitch = ExternalPlane {
        fd: fd.as_fd(),
        offset: 0,
        pitch: 0,
    };
    assert!(matches!(
        ExternalDmaBufSource::create(&device, external_format(), &[bad_pitch], None),
        Err(ExternalError::Invalid { .. })
    ));
}

/// More planes than any format has.
///
/// The array the handles go into is fixed at four, so a fifth would write past
/// it if the count were not checked -- and four is the kernel's own limit, so
/// nothing legitimate is being turned away.
#[test]
#[ignore = "needs a DRM device; run under the vkms lane with --include-ignored"]
fn external_create_rejects_more_planes_than_a_format_can_have_vkms() {
    let _guard = card_guard();
    let Some(device) = open_card() else { return };
    let fd = placeholder_fd();
    let five: Vec<ExternalPlane<'_>> = (0..5).map(|_| plane(&fd)).collect();

    assert!(matches!(
        ExternalDmaBufSource::create(&device, external_format(), &five, None),
        Err(ExternalError::Invalid { .. })
    ));

    // Four is accepted by the shape check -- it may still fail later on the
    // import, which is a different answer and the point of the distinction.
    let four: Vec<ExternalPlane<'_>> = (0..4).map(|_| plane(&fd)).collect();
    assert!(
        !matches!(
            ExternalDmaBufSource::create(&device, external_format(), &four, None),
            Err(ExternalError::Invalid { .. })
        ),
        "four planes is a shape the kernel allows"
    );
}

/// Multi-plane layouts pass validation.
///
/// The reference makes this point by handing `create` a device built from fd
/// -1 and asserting the error is `bad_file_descriptor` rather than
/// `invalid_argument` -- the layout was accepted, and the failure came from
/// the device. Here a `&Device` is a live DRM device by construction, so the
/// same distinction is drawn from the other side: whatever these do, they must
/// not come back `Invalid`, because that would mean the shape was rejected.
#[test]
#[ignore = "needs a DRM device; run under the vkms lane with --include-ignored"]
fn external_create_accepts_multi_plane_layouts_vkms() {
    const W: u32 = 64;
    const H: u32 = 64;

    let _guard = card_guard();
    let Some(device) = open_card() else { return };
    let fd = placeholder_fd();

    let at = |offset: u32, pitch: u32| ExternalPlane {
        fd: fd.as_fd(),
        offset,
        pitch,
    };

    // NV12: an 8bpp Y plane and an interleaved 8bpp chroma plane after it.
    let nv12 = [at(0, W), at(W * H, W)];
    // YUV420: Y, then two half-width chroma planes.
    let yuv420 = [
        at(0, W),
        at(W * H, W / 2),
        at(W * H + (W / 2) * (H / 2), W / 2),
    ];
    // A tiled single-plane layout -- the modifier must not make the shape
    // check reject it.
    let tiled = [at(0, W * 4)];

    let cases: [(&str, u32, u64, &[ExternalPlane<'_>]); 3] = [
        ("NV12", drmkit_fmt::fourcc::NV12, 0, &nv12),
        ("YUV420", drmkit_fmt::fourcc::YUV420, 0, &yuv420),
        (
            "tiled XRGB8888",
            XRGB8888,
            // An arbitrary vendor modifier: what matters is that it is not
            // LINEAR and does not change the shape check's answer.
            0x0100_0000_0000_0002,
            &tiled,
        ),
    ];

    for (what, fourcc, modifier, planes) in cases {
        let format = SourceFormat {
            fourcc,
            modifier,
            width: W,
            height: H,
        };
        assert!(
            !matches!(
                ExternalDmaBufSource::create(&device, format, planes, None),
                Err(ExternalError::Invalid { .. })
            ),
            "{what} is a valid layout and must not be rejected as malformed"
        );
    }
}

/// A failed create must **not** fire the release callback: the caller still
/// owns the upstream buffer and will re-queue or drop it themselves. Firing
/// would re-queue a buffer the caller has not finished with.
#[test]
#[ignore = "needs a DRM device; run under the vkms lane with --include-ignored"]
fn a_failed_create_does_not_fire_the_release_callback_vkms() {
    let _guard = card_guard();
    let Some(device) = open_card() else { return };
    let fd = placeholder_fd();
    let fired = Arc::new(AtomicUsize::new(0));

    let counter = Arc::clone(&fired);
    let result = ExternalDmaBufSource::create(
        &device,
        SourceFormat {
            width: 0,
            ..external_format()
        },
        &[plane(&fd)],
        Some(Box::new(move || {
            counter.fetch_add(1, Ordering::Relaxed);
        })),
    );

    assert!(result.is_err());
    assert_eq!(
        fired.load(Ordering::Relaxed),
        0,
        "the caller still owns the upstream buffer after a failed create"
    );
}

// --- the fence dup ----------------------------------------------------------

/// **Plan §4.9 / upstream PR #230.** Two consecutive acquires must yield
/// **independently closeable** descriptors.
///
/// An owned fence handed over on one acquire would be gone by the next, so a
/// later commit would go out unsynced and the display engine could sample the
/// buffer before the producer's writes land. Nothing reports it: the commit
/// succeeds, the counters balance, and the frame tears under load.
///
/// This used to say the scene acquires each source twice per frame, once for
/// the `TEST_ONLY` commit and once for the real one. Measured through the T7
/// runner, it does not: six frames over two layers produce twelve acquires,
/// exactly one per source per frame, including the frame that searches. The
/// test commit is built by `DeviceCommitter` from the allocator's `Layer`
/// property bags, which never carry a fence, so `IN_FENCE_FD` reaches the
/// apply only — and drm-cxx agrees byte for byte, so it is settled behavior
/// rather than a divergence.
///
/// The requirement is unchanged; only the reason is. One fence has to arm
/// frame after frame, which is what `fence-dup-independence.scenario` pins at
/// the trace level.
#[test]
#[ignore = "needs a DRM device; run under the vkms lane with --include-ignored"]
fn two_acquires_yield_independently_closeable_fences_vkms() {
    let _guard = card_guard();
    let Some(device) = open_card() else { return };
    let (dmabuf, pitch) = real_dma_buf(&device, 64, 64).expect("export a real dma-buf");
    let planes = [ExternalPlane {
        fd: dmabuf.as_fd(),
        offset: 0,
        pitch,
    }];
    let mut source = ExternalDmaBufSource::create(&device, external_format(), &planes, None)
        .expect("wrap a real dma-buf");

    source.set_acquire_fence(
        drmkit_sync::SyncFence::import(fake_fence().as_fd()).expect("import fence"),
    );

    let first = source.acquire().expect("first acquire");
    let second = source.acquire().expect("second acquire");

    let first_fd = first
        .acquire_fence
        .as_ref()
        .and_then(drmkit_sync::SyncFence::as_fd);
    let second_fd = second
        .acquire_fence
        .as_ref()
        .and_then(drmkit_sync::SyncFence::as_fd);

    assert!(
        first_fd.is_some(),
        "the TEST commit's acquire must be fenced"
    );
    assert!(
        second_fd.is_some(),
        "and so must the real commit's -- an owned fence would have been \
         consumed by the first, leaving the real commit unsynced"
    );
    assert_ne!(
        first_fd.map(|fd| fd.as_raw_fd()),
        second_fd.map(|fd| fd.as_raw_fd()),
        "each acquire must get its own descriptor, not an alias"
    );

    // Dropping one must not disturb the other: each rides its own buffer's
    // lifecycle and closes on release.
    drop(first);
    assert!(
        rustix::fs::fstat(second_fd.expect("second fence")).is_ok(),
        "releasing one buffer must not close another's fence"
    );

    assert!(
        source.has_acquire_fence(),
        "the producer's fence stays live for the next frame; only \
         set_acquire_fence replaces it"
    );
}

/// With no producer fence set, acquires are simply unfenced — the common case
/// for a source whose buffer is ready synchronously.
#[test]
#[ignore = "needs a DRM device; run under the vkms lane with --include-ignored"]
fn acquires_are_unfenced_when_no_producer_fence_is_set_vkms() {
    let _guard = card_guard();
    let Some(device) = open_card() else { return };
    let (dmabuf, pitch) = real_dma_buf(&device, 64, 64).expect("export a real dma-buf");
    let planes = [ExternalPlane {
        fd: dmabuf.as_fd(),
        offset: 0,
        pitch,
    }];
    let mut source = ExternalDmaBufSource::create(&device, external_format(), &planes, None)
        .expect("wrap a real dma-buf");

    assert!(!source.has_acquire_fence());
    let acquired = source.acquire().expect("acquire");
    assert!(acquired.acquire_fence.is_none());
}

/// The release callback fires **exactly once**, whether the source is released
/// or torn down without ever reaching release. Firing twice would re-queue a
/// buffer still in use; never firing would stall the producer's pipeline.
#[test]
#[ignore = "needs a DRM device; run under the vkms lane with --include-ignored"]
fn the_release_callback_fires_exactly_once_vkms() {
    let _guard = card_guard();
    let Some(device) = open_card() else { return };
    let (dmabuf, pitch) = real_dma_buf(&device, 64, 64).expect("export a real dma-buf");
    let planes = [ExternalPlane {
        fd: dmabuf.as_fd(),
        offset: 0,
        pitch,
    }];
    let fired = Arc::new(AtomicUsize::new(0));

    {
        let counter = Arc::clone(&fired);
        let mut source = ExternalDmaBufSource::create(
            &device,
            external_format(),
            &planes,
            Some(Box::new(move || {
                counter.fetch_add(1, Ordering::Relaxed);
            })),
        )
        .expect("wrap a real dma-buf");

        let acquired = source.acquire().expect("acquire");
        source.release(acquired);
        assert_eq!(
            fired.load(Ordering::Relaxed),
            1,
            "the first retire re-queues"
        );

        let again = source.acquire().expect("acquire");
        source.release(again);
        assert_eq!(
            fired.load(Ordering::Relaxed),
            1,
            "a second release must not re-queue a buffer still in use"
        );
    }

    assert_eq!(
        fired.load(Ordering::Relaxed),
        1,
        "and the drop must not fire it again"
    );
}

/// A source torn down before ever being released must still re-queue upstream,
/// or the producer waits for a slot that never comes back.
#[test]
#[ignore = "needs a DRM device; run under the vkms lane with --include-ignored"]
fn dropping_without_releasing_still_fires_the_callback_vkms() {
    let _guard = card_guard();
    let Some(device) = open_card() else { return };
    let (dmabuf, pitch) = real_dma_buf(&device, 64, 64).expect("export a real dma-buf");
    let planes = [ExternalPlane {
        fd: dmabuf.as_fd(),
        offset: 0,
        pitch,
    }];
    let fired = Arc::new(AtomicUsize::new(0));

    {
        let counter = Arc::clone(&fired);
        let source = ExternalDmaBufSource::create(
            &device,
            external_format(),
            &planes,
            Some(Box::new(move || {
                counter.fetch_add(1, Ordering::Relaxed);
            })),
        )
        .expect("wrap a real dma-buf");
        drop(source);
    }

    assert_eq!(
        fired.load(Ordering::Relaxed),
        1,
        "teardown must re-queue the upstream buffer"
    );
}

// --- DmaBufSourceCache -------------------------------------------------------

/// A repeated key returns the same source, framebuffer and all.
///
/// This is the whole point of the cache: a swapchain hands the same descriptors
/// back every frame, and importing them again would be two ioctls per plane per
/// frame to arrive at the framebuffer id the kernel already had.
#[test]
fn a_repeated_key_reuses_the_import() {
    let _guard = card_guard();
    let Some(device) = open_card() else { return };
    let Some((fd, pitch)) = real_dma_buf(&device, 64, 64) else {
        panic!("a dumb buffer must export a dma-buf on any KMS driver");
    };

    let format = SourceFormat {
        fourcc: XRGB8888,
        modifier: 0,
        width: 64,
        height: 64,
    };
    let planes = [ExternalPlane {
        fd: fd.as_fd(),
        offset: 0,
        pitch,
    }];

    let mut cache = DmaBufSourceCache::new();
    let first = cache
        .get_or_create(7, &device, format, &planes)
        .expect("first import")
        .acquire()
        .expect("acquire")
        .fb_id;
    let second = cache
        .get_or_create(7, &device, format, &planes)
        .expect("second lookup")
        .acquire()
        .expect("acquire")
        .fb_id;

    assert_eq!(
        first, second,
        "the same key must hand back the same framebuffer, not a fresh import"
    );
    assert_eq!(cache.len(), 1, "one buffer, one entry");
}

/// A key reused for a different buffer is re-imported, not handed back stale.
///
/// A producer reusing an index after a resize is normal. Returning the old
/// source would scan out the wrong memory at the wrong stride — which the
/// kernel accepts, because the framebuffer is perfectly valid; it is simply
/// the previous buffer.
#[test]
fn a_key_reused_for_new_geometry_is_reimported() {
    let _guard = card_guard();
    let Some(device) = open_card() else { return };
    let Some((small_fd, small_pitch)) = real_dma_buf(&device, 64, 64) else {
        panic!("dma-buf export");
    };
    let Some((large_fd, large_pitch)) = real_dma_buf(&device, 128, 128) else {
        panic!("dma-buf export");
    };

    let mut cache = DmaBufSourceCache::new();
    cache
        .get_or_create(
            1,
            &device,
            SourceFormat {
                fourcc: XRGB8888,
                modifier: 0,
                width: 64,
                height: 64,
            },
            &[ExternalPlane {
                fd: small_fd.as_fd(),
                offset: 0,
                pitch: small_pitch,
            }],
        )
        .expect("first import");

    let bigger = SourceFormat {
        fourcc: XRGB8888,
        modifier: 0,
        width: 128,
        height: 128,
    };
    cache
        .get_or_create(
            1,
            &device,
            bigger,
            &[ExternalPlane {
                fd: large_fd.as_fd(),
                offset: 0,
                pitch: large_pitch,
            }],
        )
        .expect("re-import");

    // The cached source's own geometry, not its framebuffer id. The id proves
    // nothing here: dropping the old source frees its framebuffer and the
    // kernel hands the very same id straight back to the replacement -- which
    // is what the first version of this case saw and mistook for a cache hit.
    let cached = cache.find(1).expect("an entry under the reused key");
    assert_eq!(
        LayerBufferSource::format(cached),
        bigger,
        "the geometry changed under the same key, so the source must have been \
         rebuilt rather than handed back stale"
    );
    assert_eq!(
        cache.len(),
        1,
        "the replacement takes the old entry's place"
    );
}

/// Evicting drops the import, so the next lookup builds a new one.
#[test]
fn eviction_forces_a_fresh_import() {
    let _guard = card_guard();
    let Some(device) = open_card() else { return };
    let Some((fd, pitch)) = real_dma_buf(&device, 64, 64) else {
        panic!("dma-buf export");
    };
    let format = SourceFormat {
        fourcc: XRGB8888,
        modifier: 0,
        width: 64,
        height: 64,
    };
    let planes = [ExternalPlane {
        fd: fd.as_fd(),
        offset: 0,
        pitch,
    }];

    let mut cache = DmaBufSourceCache::new();
    cache
        .get_or_create(3, &device, format, &planes)
        .expect("import");
    assert!(cache.find(3).is_some());

    assert!(
        cache.evict(3),
        "evicting a present key reports it was there"
    );
    assert!(!cache.evict(3), "evicting it twice does not");
    assert!(cache.find(3).is_none());
    assert!(cache.is_empty());

    cache
        .get_or_create(3, &device, format, &planes)
        .expect("re-import after eviction");
    assert_eq!(cache.len(), 1);

    cache.clear();
    assert!(cache.is_empty(), "clear drops everything");
}

/// A failed import caches nothing.
///
/// Otherwise a transient failure would poison the key: every later frame would
/// find the broken entry and hand it back, and the layer would never recover.
#[test]
fn a_failed_import_leaves_the_cache_untouched() {
    let _guard = card_guard();
    let Some(device) = open_card() else { return };
    let Some((fd, pitch)) = real_dma_buf(&device, 64, 64) else {
        panic!("dma-buf export");
    };

    let mut cache = DmaBufSourceCache::new();
    let refused = cache.get_or_create(
        9,
        &device,
        SourceFormat {
            fourcc: XRGB8888,
            modifier: 0,
            width: 0, // rejected before any ioctl
            height: 64,
        },
        &[ExternalPlane {
            fd: fd.as_fd(),
            offset: 0,
            pitch,
        }],
    );

    assert!(refused.is_err(), "a zero dimension must be refused");
    assert!(
        cache.find(9).is_none(),
        "a failed import must leave no entry behind to be handed out later"
    );
    assert!(cache.is_empty());
}

// --- ExternalDmaBufRing ------------------------------------------------------

/// Build a ring of `n` slots over real exported dma-bufs.
///
/// Returns the ring and the descriptors, which the caller must keep alive only
/// because the test wants them — the ring duplicates its own.
fn ring_of(device: &Device, n: usize) -> Option<(ExternalDmaBufRing, Vec<OwnedFd>)> {
    let mut fds = Vec::new();
    let mut pitches = Vec::new();
    for _ in 0..n {
        let (fd, pitch) = real_dma_buf(device, 64, 64)?;
        fds.push(fd);
        pitches.push(pitch);
    }
    let planes: Vec<Vec<ExternalPlane<'_>>> = fds
        .iter()
        .zip(&pitches)
        .map(|(fd, pitch)| {
            vec![ExternalPlane {
                fd: fd.as_fd(),
                offset: 0,
                pitch: *pitch,
            }]
        })
        .collect();
    let slots: Vec<&[ExternalPlane<'_>]> = planes.iter().map(Vec::as_slice).collect();

    let ring = ExternalDmaBufRing::create(
        device,
        SourceFormat {
            fourcc: XRGB8888,
            modifier: 0,
            width: 64,
            height: 64,
        },
        &slots,
        None,
    )
    .expect("import the ring");
    Some((ring, fds))
}

/// Whether `fb_id` names a framebuffer `device` can see.
fn framebuffer_exists(device: &Device, fb_id: u32) -> bool {
    use drm::control::Device as _;
    drm::control::from_u32::<drm::control::framebuffer::Handle>(fb_id)
        .is_some_and(|fb| device.get_framebuffer(fb).is_ok())
}

/// An external source presents again after a session resume.
///
/// The pause is modeled the way libseat does it: the old descriptor is
/// closed, which takes its framebuffers with it, and the resume hands over a
/// fresh one. The producer's buffer survives, so the reference re-imports it;
/// without that every acquire after the resume hands out an id the new
/// descriptor has never registered.
#[test]
#[ignore = "needs a DRM device; run under the vkms lane with --include-ignored"]
fn an_external_source_reimports_on_resume_vkms() {
    let _guard = card_guard();
    let Some(before) = open_card() else { return };
    let Some((fd, pitch)) = real_dma_buf(&before, 64, 64) else {
        panic!("vkms allocates and exports a dumb buffer");
    };
    let planes = [ExternalPlane {
        fd: fd.as_fd(),
        offset: 0,
        pitch,
    }];
    let mut source =
        ExternalDmaBufSource::create(&before, external_format(), &planes, None).expect("import");

    source.on_session_paused();
    drop(before);
    let Some(after) = open_card() else { return };
    source.on_session_resumed(&after).expect("re-import");

    let fb_id = source.acquire().expect("acquire after resume").fb_id;
    assert!(
        framebuffer_exists(&after, fb_id),
        "framebuffer {fb_id} is not registered on the new descriptor"
    );
}

/// Clearing a cache after its device has gone touches nothing on the device
/// that replaced it.
///
/// After a session loss the old descriptor is closed and its number is free;
/// the next open takes it, and the kernel hands out the freed framebuffer id
/// again. A clear that tore its imports down by ioctl would remove the new
/// file's framebuffer under that id. It must forget them instead, as the
/// kernel already reclaimed them with the old descriptor.
#[test]
#[ignore = "needs a DRM device; run under the vkms lane with --include-ignored"]
fn clearing_a_cache_after_session_loss_spares_the_new_device_vkms() {
    use std::os::fd::AsRawFd as _;

    let _guard = card_guard();
    let Some(exporter) = open_card() else { return };
    let Some(before) = open_card() else { return };
    let Some((fd, pitch)) = real_dma_buf(&exporter, 64, 64) else {
        panic!("vkms allocates and exports a dumb buffer");
    };
    let planes = [ExternalPlane {
        fd: fd.as_fd(),
        offset: 0,
        pitch,
    }];

    let mut cache = DmaBufSourceCache::new();
    let old_fb = cache
        .get_or_create(1, &before, external_format(), &planes)
        .expect("import")
        .acquire()
        .expect("acquire")
        .fb_id;
    let number = before.as_fd().as_raw_fd();
    drop(before);

    let Some(after) = open_card() else { return };
    if after.as_fd().as_raw_fd() != number {
        println!("note: skipped -- the descriptor number was not reused");
        return;
    }
    let mut fresh =
        ExternalDmaBufSource::create(&after, external_format(), &planes, None).expect("import");
    let new_fb = fresh.acquire().expect("acquire").fb_id;
    if new_fb != old_fb {
        println!("note: the framebuffer id was not reused ({old_fb} -> {new_fb})");
    }

    cache.clear();
    assert!(
        framebuffer_exists(&after, new_fb),
        "clearing the cache removed framebuffer {new_fb} from the device that replaced its own"
    );
}

/// A ring presents again after a session resume, every slot of it.
#[test]
#[ignore = "needs a DRM device; run under the vkms lane with --include-ignored"]
fn a_ring_reimports_every_slot_on_resume_vkms() {
    let _guard = card_guard();
    let Some(before) = open_card() else { return };
    let Some((mut ring, _fds)) = ring_of(&before, 2) else {
        panic!("dma-buf export");
    };

    ring.on_session_paused();
    drop(before);
    let Some(after) = open_card() else { return };
    ring.on_session_resumed(&after).expect("re-import");

    for slot in 0..2 {
        ring.submit(slot, None, &[]);
        let fb_id = ring
            .acquire()
            .unwrap_or_else(|error| panic!("slot {slot} after resume: {error}"))
            .fb_id;
        assert!(
            framebuffer_exists(&after, fb_id),
            "slot {slot}'s framebuffer {fb_id} is not registered on the new descriptor"
        );
    }
}

/// Every slot gets its own framebuffer.
///
/// One id shared across slots would mean the producer's rotation changed
/// nothing on screen — every frame would present whichever buffer that id
/// happened to name.
#[test]
fn each_slot_gets_its_own_framebuffer() {
    let _guard = card_guard();
    let Some(device) = open_card() else { return };
    let Some((mut ring, _fds)) = ring_of(&device, 3) else {
        panic!("dma-buf export");
    };
    assert_eq!(ring.slot_count(), 3);

    let mut seen = std::collections::HashSet::new();
    for slot in 0..3 {
        ring.submit(slot, None, &[]);
        let fb = ring.acquire().expect("acquire").fb_id;
        assert!(fb != 0, "slot {slot} has no framebuffer");
        assert!(
            seen.insert(fb),
            "slot {slot} reused another slot's framebuffer"
        );
    }
}

/// With nothing new submitted, the ring re-presents what is on screen.
///
/// Returning `WouldBlock` instead would have the scene drop the layer, which
/// blanks the plane — a producer that pauses for one vblank should freeze, not
/// disappear.
#[test]
fn an_idle_ring_holds_the_last_frame() {
    let _guard = card_guard();
    let Some(device) = open_card() else { return };
    let Some((mut ring, _fds)) = ring_of(&device, 2) else {
        panic!("dma-buf export");
    };

    ring.submit(1, None, &[]);
    let first = ring.acquire().expect("first frame");
    assert!(!ring.has_fresh_frame(), "the submission was taken");

    let held = ring.acquire().expect("an idle vblank still presents");
    assert_eq!(held.fb_id, first.fb_id, "the same buffer stays up");
    assert_eq!(
        held.token, first.token,
        "and under the same token, so it is not mistaken for a superseded frame"
    );
}

/// A slot is handed back only once something newer is on screen.
#[test]
fn a_slot_is_released_when_superseded() {
    let _guard = card_guard();
    let Some(device) = open_card() else { return };
    let Some((mut ring, _fds)) = ring_of(&device, 2) else {
        panic!("dma-buf export");
    };

    let freed = Arc::new(Mutex::new(Vec::new()));
    let sink = Arc::clone(&freed);
    ring.set_on_release(Box::new(move |slot, fence| {
        sink.lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
            .push((slot, fence.is_some()));
    }));

    ring.submit(0, None, &[]);
    let first_token = ring.acquire().expect("first").token;
    // Release keys on the token alone, so a buffer carrying it says the same
    // thing as the one the scene held. `AcquiredBuffer` owns its fence and so
    // is deliberately not `Clone`.
    ring.release(AcquiredBuffer {
        token: first_token,
        ..AcquiredBuffer::default()
    });
    assert!(
        freed
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
            .is_empty(),
        "slot 0 is still on screen; telling the producer it is free would race \
         it into overwriting live scanout"
    );

    ring.submit(1, None, &[]);
    let second_token = ring.acquire().expect("second").token;
    ring.release(AcquiredBuffer {
        token: first_token,
        ..AcquiredBuffer::default()
    });
    assert_eq!(
        &*freed
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner),
        &[(0, false)],
        "slot 0 left the screen and must come back to the producer"
    );

    // And the newly live one still does not.
    ring.release(AcquiredBuffer {
        token: second_token,
        ..AcquiredBuffer::default()
    });
    assert_eq!(
        freed
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
            .len(),
        1
    );
}

/// The release fence reaches the producer.
///
/// A GPU producer waits on it and re-renders the slot with no CPU stall. Losing
/// it would not break correctness — the callback edge still says "free" — but
/// it forces the stall the fence exists to avoid.
#[test]
fn a_release_fence_is_forwarded_to_the_producer() {
    let _guard = card_guard();
    let Some(device) = open_card() else { return };
    let Some((mut ring, _fds)) = ring_of(&device, 2) else {
        panic!("dma-buf export");
    };

    let fenced = Arc::new(AtomicUsize::new(0));
    let counter = Arc::clone(&fenced);
    ring.set_on_release(Box::new(move |_, fence| {
        if fence.is_some() {
            counter.fetch_add(1, Ordering::SeqCst);
        }
    }));
    assert!(
        ring.wants_release_fence(),
        "with a listener attached the scene should ask the kernel for an \
         out-fence"
    );

    ring.submit(0, None, &[]);
    let first_token = ring.acquire().expect("first").token;
    ring.submit(1, None, &[]);
    ring.acquire().expect("second");

    let stand_in =
        rustix::event::eventfd(0, rustix::event::EventfdFlags::CLOEXEC).expect("eventfd");
    ring.release_with_fence(
        AcquiredBuffer {
            token: first_token,
            ..AcquiredBuffer::default()
        },
        Some(SyncFence::from_owned(stand_in)),
    );

    assert_eq!(
        fenced.load(Ordering::SeqCst),
        1,
        "the displacing commit's fence must reach the producer"
    );
}

/// Nothing listening means no reason to ask the kernel for an out-fence.
#[test]
fn a_ring_with_no_listener_wants_no_release_fence() {
    let _guard = card_guard();
    let Some(device) = open_card() else { return };
    let Some((ring, _fds)) = ring_of(&device, 1) else {
        panic!("dma-buf export");
    };
    assert!(!ring.wants_release_fence());
}

/// A paused session leaves nothing presentable.
///
/// The descriptor is revoked, so the framebuffer ids are meaningless. Handing
/// one to a commit would take the whole frame down, so the ring reports no
/// frame until the producer submits against a re-imported ring.
#[test]
fn a_paused_ring_presents_nothing() {
    let _guard = card_guard();
    let Some(device) = open_card() else { return };
    let Some((mut ring, _fds)) = ring_of(&device, 2) else {
        panic!("dma-buf export");
    };

    ring.submit(0, None, &[]);
    ring.acquire().expect("a frame before the pause");

    ring.on_session_paused();

    assert_eq!(ring.scanning_slot(), None, "nothing is on screen any more");
    assert!(
        matches!(ring.acquire(), Err(SourceError::WouldBlock)),
        "with nothing on screen there is nothing to hold"
    );

    // The part that needs the framebuffers actually forgotten. Clearing the
    // presenter alone is not enough: a producer that keeps submitting across
    // the pause would otherwise be handed a framebuffer id registered on a
    // descriptor that no longer exists, and committing it takes the whole
    // frame down.
    ring.submit(0, None, &[]);
    assert!(
        matches!(ring.acquire(), Err(SourceError::Failed(_))),
        "a slot whose framebuffer was forgotten must not be presented"
    );
}

/// A ring needs at least one slot.
#[test]
fn an_empty_ring_is_refused() {
    let _guard = card_guard();
    let Some(device) = open_card() else { return };
    let result = ExternalDmaBufRing::create(
        &device,
        SourceFormat {
            fourcc: XRGB8888,
            modifier: 0,
            width: 64,
            height: 64,
        },
        &[],
        None,
    );
    assert!(result.is_err(), "a ring with no slots can never present");
}

/// A slot index the ring does not have is ignored.
///
/// The producer owns the indices it was built with. Failing loudly on its own
/// thread, where there is no commit to fail, would give it nothing to do about
/// it.
#[test]
fn an_out_of_range_submit_is_ignored() {
    let _guard = card_guard();
    let Some(device) = open_card() else { return };
    let Some((mut ring, _fds)) = ring_of(&device, 2) else {
        panic!("dma-buf export");
    };

    ring.submit(99, None, &[]);
    assert!(!ring.has_fresh_frame(), "nothing was queued");
    assert!(matches!(ring.acquire(), Err(SourceError::WouldBlock)));
}

// --- ExternalDmaBufPool ------------------------------------------------------

fn pool_format() -> SourceFormat {
    SourceFormat {
        fourcc: XRGB8888,
        modifier: 0,
        width: 64,
        height: 64,
    }
}

/// A key is imported once and reused thereafter.
#[test]
fn a_pool_imports_each_key_once() {
    let _guard = card_guard();
    let Some(device) = open_card() else { return };
    let Some((fd, pitch)) = real_dma_buf(&device, 64, 64) else {
        panic!("dma-buf export");
    };
    let planes = [ExternalPlane {
        fd: fd.as_fd(),
        offset: 0,
        pitch,
    }];

    let mut pool = ExternalDmaBufPool::new(pool_format(), None);
    assert_eq!(pool.cached_count(), 0, "a pool starts empty");

    pool.submit(&device, 42, &planes, None, &[])
        .expect("submit");
    let first = pool.acquire().expect("first frame").fb_id;
    assert_eq!(pool.cached_count(), 1);

    pool.submit(&device, 42, &planes, None, &[])
        .expect("submit");
    let second = pool.acquire().expect("second frame").fb_id;

    assert_eq!(first, second, "the same key must reuse its import");
    assert_eq!(pool.cached_count(), 1, "and not import a second time");
}

/// Distinct keys are distinct buffers.
#[test]
fn a_pool_keeps_keys_apart() {
    let _guard = card_guard();
    let Some(device) = open_card() else { return };
    let Some((a_fd, a_pitch)) = real_dma_buf(&device, 64, 64) else {
        panic!("dma-buf export");
    };
    let Some((b_fd, b_pitch)) = real_dma_buf(&device, 64, 64) else {
        panic!("dma-buf export");
    };

    let mut pool = ExternalDmaBufPool::new(pool_format(), None);
    pool.submit(
        &device,
        1,
        &[ExternalPlane {
            fd: a_fd.as_fd(),
            offset: 0,
            pitch: a_pitch,
        }],
        None,
        &[],
    )
    .expect("submit");
    let first = pool.acquire().expect("first").fb_id;

    pool.submit(
        &device,
        2,
        &[ExternalPlane {
            fd: b_fd.as_fd(),
            offset: 0,
            pitch: b_pitch,
        }],
        None,
        &[],
    )
    .expect("submit");
    let second = pool.acquire().expect("second").fb_id;

    assert_ne!(first, second, "two keys must not share a framebuffer");
    assert_eq!(pool.cached_count(), 2);
}

/// A failed import skips the frame and holds the last good buffer, and says
/// why. A frozen layer beats a blank one.
#[test]
fn a_failed_import_holds_the_last_frame() {
    let _guard = card_guard();
    let Some(device) = open_card() else { return };
    let Some((fd, pitch)) = real_dma_buf(&device, 64, 64) else {
        panic!("dma-buf export");
    };
    let planes = [ExternalPlane {
        fd: fd.as_fd(),
        offset: 0,
        pitch,
    }];

    let mut pool = ExternalDmaBufPool::new(pool_format(), None);
    pool.submit(&device, 1, &planes, None, &[]).expect("submit");
    let good = pool.acquire().expect("a good frame").fb_id;

    // A key the pool has never seen, with a plane list it must refuse.
    assert!(
        matches!(
            pool.submit(&device, 2, &[], None, &[]),
            Err(ExternalError::Invalid { .. })
        ),
        "an empty plane list cannot be imported, and the caller hears why"
    );
    assert_eq!(pool.cached_count(), 1, "the bad key cached nothing");

    let held = pool.acquire().expect("the layer must not go blank");
    assert_eq!(held.fb_id, good, "the last good buffer stays up");
}

/// A new generation retires the old buffers, but not while they are on screen.
///
/// Tearing down a framebuffer the kernel is still scanning out is exactly the
/// hazard the deferred-release protocol exists to avoid; a resolution change
/// must not become a way around it.
#[test]
fn a_generation_reset_retires_buffers_only_once_unreferenced() {
    let _guard = card_guard();
    let Some(device) = open_card() else { return };
    let Some((old_fd, old_pitch)) = real_dma_buf(&device, 64, 64) else {
        panic!("dma-buf export");
    };
    let Some((new_fd, new_pitch)) = real_dma_buf(&device, 32, 32) else {
        panic!("dma-buf export");
    };

    let mut pool = ExternalDmaBufPool::new(pool_format(), None);
    pool.submit(
        &device,
        1,
        &[ExternalPlane {
            fd: old_fd.as_fd(),
            offset: 0,
            pitch: old_pitch,
        }],
        None,
        &[],
    )
    .expect("submit");
    let old_token = pool.acquire().expect("the old generation").token;
    assert_eq!(pool.cached_count(), 1);

    pool.reset_generation(SourceFormat {
        fourcc: XRGB8888,
        modifier: 0,
        width: 32,
        height: 32,
    });

    // Still on screen, so still imported.
    pool.acquire().expect("holding the old buffer");
    assert_eq!(
        pool.cached_count(),
        1,
        "the retiring buffer is on screen and must not be torn down under it"
    );

    // The new generation arrives under a fresh key, as the contract requires.
    pool.submit(
        &device,
        2,
        &[ExternalPlane {
            fd: new_fd.as_fd(),
            offset: 0,
            pitch: new_pitch,
        }],
        None,
        &[],
    )
    .expect("submit");
    pool.acquire().expect("the new generation");
    pool.release(AcquiredBuffer {
        token: old_token,
        ..AcquiredBuffer::default()
    });
    pool.acquire().expect("a later frame sweeps");

    assert_eq!(
        pool.cached_count(),
        1,
        "once nothing references it, the old buffer is torn down"
    );
    assert_eq!(
        LayerBufferSource::format(&pool).width,
        32,
        "and future imports use the new geometry"
    );
}

/// A paused pool drops its imports so the producer re-imports on resume.
#[test]
fn a_paused_pool_forgets_its_imports() {
    let _guard = card_guard();
    let Some(device) = open_card() else { return };
    let Some((fd, pitch)) = real_dma_buf(&device, 64, 64) else {
        panic!("dma-buf export");
    };
    let planes = [ExternalPlane {
        fd: fd.as_fd(),
        offset: 0,
        pitch,
    }];

    let mut pool = ExternalDmaBufPool::new(pool_format(), None);
    pool.submit(&device, 1, &planes, None, &[]).expect("submit");
    pool.acquire().expect("a frame");
    assert_eq!(pool.cached_count(), 1);

    pool.on_session_paused();

    assert_eq!(
        pool.cached_count(),
        0,
        "every framebuffer id belonged to a descriptor that is now revoked"
    );
    assert!(matches!(pool.acquire(), Err(SourceError::WouldBlock)));
}

// --- GbmBufferSource ---------------------------------------------------------

/// A GBM allocation becomes a framebuffer the scene can submit.
///
/// The path this covers is the one that carries the modifier: the buffer goes
/// to KMS as a DMA-BUF import, so a tiled or compressed allocation arrives at
/// `add_planar_framebuffer` described as what it is. On vkms everything is
/// linear, so what is pinned here is that the export-import round trip works
/// at all and reports the shape it was asked for.
#[cfg(feature = "gbm")]
#[test]
#[ignore = "needs a DRM device; run under the vkms lane with --include-ignored"]
fn a_gbm_allocation_becomes_a_submittable_framebuffer_vkms() {
    let _guard = card_guard();
    let Some(device) = open_card() else { return };

    let mut source = match crate::GbmBufferSource::create(&device, 64, 64, XRGB8888, &[0]) {
        Ok(source) => source,
        Err(error) => {
            println!("note: skipped -- no GBM allocation on this card ({error})");
            return;
        }
    };

    let format = LayerBufferSource::format(&source);
    assert_eq!(format.width, 64);
    assert_eq!(format.height, 64);
    assert_eq!(format.fourcc, XRGB8888);

    let fb_id = source.fb_id().expect("the import registered a framebuffer");
    assert_ne!(fb_id, 0, "a zero fb_id is what the scene skips writing");

    let acquired = source.acquire().expect("acquire");
    assert_eq!(
        acquired.fb_id, fb_id,
        "a single-buffer source hands out the framebuffer it registered"
    );
    source.release(acquired);
}

/// The source reports the modifier the allocation actually has.
///
/// Not the one that was requested: a driver with no constrained entry point
/// falls back to an unconstrained allocation, and a framebuffer registered
/// with a modifier the buffer does not have is one the kernel either refuses
/// or -- worse -- accepts and scans out as garbage.
#[cfg(feature = "gbm")]
#[test]
#[ignore = "needs a DRM device; run under the vkms lane with --include-ignored"]
fn the_reported_modifier_is_the_one_the_buffer_has_vkms() {
    let _guard = card_guard();
    let Some(device) = open_card() else { return };

    let source = match crate::GbmBufferSource::create(&device, 64, 64, XRGB8888, &[0]) {
        Ok(source) => source,
        Err(error) => {
            println!("note: skipped -- no GBM allocation on this card ({error})");
            return;
        }
    };

    assert_eq!(
        LayerBufferSource::format(&source).modifier,
        source.buffer().modifier(),
        "the framebuffer describes the layout the allocation reports"
    );
}

/// Composition reaches this source through its DMA-BUF, not a CPU map.
///
/// A GBM buffer may be tiled or device-local, so `map` is correctly
/// unsupported -- and a source that only said that would be uncompositable,
/// blanking its layer whenever the allocator could not place it. The export is
/// what keeps it rescuable.
#[cfg(feature = "gbm")]
#[test]
#[ignore = "needs a DRM device; run under the vkms lane with --include-ignored"]
fn a_gbm_source_is_compositable_through_its_dma_buf_vkms() {
    let _guard = card_guard();
    let Some(device) = open_card() else { return };

    let mut source = match crate::GbmBufferSource::create(&device, 64, 64, XRGB8888, &[0]) {
        Ok(source) => source,
        Err(error) => {
            println!("note: skipped -- no GBM allocation on this card ({error})");
            return;
        }
    };

    assert!(
        matches!(
            source.map(drmkit_dumb::MapAccess::Read),
            Err(SourceError::Unsupported)
        ),
        "a GBM allocation has no meaningful CPU view to hand back"
    );
    assert!(
        source.export_dma_buf().is_ok(),
        "so the DMA-BUF export is the only thing keeping the layer compositable"
    );
}

// --- composability of imported sources ---------------------------------------

/// An imported buffer is compositable through its descriptors.
///
/// The trait's own documentation names this case as the reason
/// `export_dma_buf` exists -- "a source whose pixels never reach CPU memory
/// ... can still be composited by importing its DMA-BUF". This source is that
/// case. Without the export it is uncompositable, and its layer blanks
/// whenever the allocator cannot find it a plane.
#[test]
#[ignore = "needs a DRM device; run under the vkms lane with --include-ignored"]
fn an_imported_buffer_lends_its_descriptors_back_vkms() {
    let _guard = card_guard();
    let Some(device) = open_card() else { return };
    let (dma_buf, pitch) = real_dma_buf(&device, 64, 64).expect("export a real dma-buf");

    let format = SourceFormat {
        fourcc: XRGB8888,
        modifier: 0,
        width: 64,
        height: 64,
    };
    let mut source = ExternalDmaBufSource::create(
        &device,
        format,
        &[ExternalPlane {
            fd: std::os::fd::AsFd::as_fd(&dma_buf),
            offset: 0,
            pitch,
        }],
        None,
    )
    .expect("import");

    assert!(
        matches!(
            source.map(drmkit_dumb::MapAccess::Read),
            Err(SourceError::Unsupported)
        ),
        "a foreign buffer exposes no CPU mapping"
    );

    let exported = source
        .export_dma_buf()
        .expect("so it must lend descriptors");
    assert_eq!(exported.fds.len(), 1);
    assert_eq!(exported.pitches, vec![pitch]);
    assert_eq!(exported.offsets, vec![0]);
    assert_eq!(
        exported.format, format,
        "the descriptor describes the same buffer the framebuffer does"
    );
}

/// A ring describes the slot the last acquire handed out, not slot zero.
///
/// A ring rotates, so "the currently-acquired buffer" is a different slot each
/// frame. Answering with a fixed slot would describe the wrong pixels -- and
/// on a two-slot ring it would be right half the time, which is worse than
/// being wrong every time.
#[test]
#[ignore = "needs a DRM device; run under the vkms lane with --include-ignored"]
fn a_ring_describes_the_slot_it_just_handed_out_vkms() {
    let _guard = card_guard();
    let Some(device) = open_card() else { return };
    let (first_fd, first_pitch) = real_dma_buf(&device, 64, 64).expect("export a real dma-buf");
    let (second_fd, second_pitch) = real_dma_buf(&device, 64, 64).expect("export a real dma-buf");

    let format = SourceFormat {
        fourcc: XRGB8888,
        modifier: 0,
        width: 64,
        height: 64,
    };
    let plane_a = [ExternalPlane {
        fd: std::os::fd::AsFd::as_fd(&first_fd),
        offset: 0,
        pitch: first_pitch,
    }];
    let plane_b = [ExternalPlane {
        fd: std::os::fd::AsFd::as_fd(&second_fd),
        offset: 0,
        pitch: second_pitch,
    }];
    let mut ring = ExternalDmaBufRing::create(&device, format, &[&plane_a, &plane_b], None)
        .expect("build a two-slot ring");

    assert!(
        matches!(ring.export_dma_buf(), Err(SourceError::Unsupported)),
        "before the first acquire there is no acquired buffer to describe"
    );

    // The slots are distinguished by descriptor, not by shape: a ring holds one
    // format across every slot, so the strides are equal by construction and
    // only the import's own duplicated descriptor tells them apart.
    let mut seen = Vec::new();
    for slot in 0..2 {
        ring.submit(slot, None, &[]);
        let acquired = ring.acquire().expect("acquire");
        let exported = ring.export_dma_buf().expect("describe the acquired slot");
        assert_eq!(
            exported.pitches,
            vec![first_pitch],
            "both slots share a shape"
        );
        seen.push(std::os::fd::AsRawFd::as_raw_fd(&exported.fds[0]));
        ring.release(acquired);
    }

    assert_ne!(
        seen[0], seen[1],
        "two acquires described the same slot, so the ring answers with a fixed one"
    );
    assert_eq!(second_pitch, first_pitch, "the fixture allocated two alike");
}

// --- ExternalDmaBufRing, against a card ---------------------------------------
//
// Parity port of `tests/integration/test_external_dma_buf_ring_vkms.cpp`.

/// A ring with a fence deadline, plus the descriptors keeping its slots alive.
#[cfg(test)]
fn deadline_ring_of(
    device: &Device,
    slots: usize,
    deadline: Option<std::time::Duration>,
) -> Option<(ExternalDmaBufRing, Vec<OwnedFd>)> {
    let mut fds = Vec::new();
    let mut pitches = Vec::new();
    for _ in 0..slots {
        let (fd, pitch) = real_dma_buf(device, 64, 64)?;
        fds.push(fd);
        pitches.push(pitch);
    }
    let planes: Vec<Vec<ExternalPlane<'_>>> = fds
        .iter()
        .zip(&pitches)
        .map(|(fd, pitch)| {
            vec![ExternalPlane {
                fd: fd.as_fd(),
                offset: 0,
                pitch: *pitch,
            }]
        })
        .collect();
    let slots: Vec<&[ExternalPlane<'_>]> = planes.iter().map(Vec::as_slice).collect();

    let ring = ExternalDmaBufRing::create(
        device,
        SourceFormat {
            fourcc: XRGB8888,
            modifier: 0,
            width: 64,
            height: 64,
        },
        &slots,
        deadline,
    )
    .expect("import the ring");
    Some((ring, fds))
}

/// A pipe standing in for a fence, signaled or not.
///
/// A `sync_file` is waited on with `poll`, and so is a pipe: the read end is
/// unreadable until something is written, which is exactly an unsignaled
/// fence, and writing a byte signals it. Upstream uses the same trick, because
/// producing a genuinely unsignaled GPU fence needs a GPU.
///
/// The writer comes back so the caller can signal a fence it made unsignaled
/// -- and because dropping it would close the pipe, which `poll` reports as
/// readable and the wait would read as "signaled".
#[cfg(test)]
fn pipe_fence(signaled: bool) -> Option<(SyncFence, std::io::PipeWriter)> {
    let (read, write) = std::io::pipe().ok()?;
    if signaled {
        std::io::Write::write_all(&mut { &write }, b"x").ok()?;
    }
    let fence = SyncFence::import(std::os::fd::AsFd::as_fd(&read)).ok()?;
    Some((fence, write))
}

/// Slots rotate, a release fires once for the slot that left, and an idle
/// acquire re-presents the last frame without releasing it.
#[test]
#[ignore = "needs a DRM device; run under the vkms lane with --include-ignored"]
fn a_ring_rotates_its_slots_and_holds_the_last_when_idle_vkms() {
    let _guard = card_guard();
    let Some(device) = open_card() else { return };
    let Some((mut ring, _fds)) = ring_of(&device, 2) else {
        println!("note: skipped -- no importable dma-buf on this card");
        return;
    };

    // Arc, not Rc: the release callback is `Send` by contract, because a
    // producer may hand buffers back from its own thread.
    let released: std::sync::Arc<std::sync::Mutex<Vec<usize>>> = std::sync::Arc::default();
    let recorder = std::sync::Arc::clone(&released);
    ring.set_on_release(Box::new(move |slot, fence| {
        assert!(
            fence.is_none(),
            "the callback edge carries no fence until the scene wires OUT_FENCE"
        );
        recorder.lock().expect("record the release").push(slot);
    }));

    assert!(
        matches!(ring.acquire(), Err(SourceError::WouldBlock)),
        "a ring nothing has been submitted to has no frame, which is flow \
         control rather than failure"
    );

    ring.submit(0, None, &[]);
    let first = ring.acquire().expect("slot 0");
    let fb0 = first.fb_id;
    assert_ne!(fb0, 0);

    ring.submit(1, None, &[]);
    let second = ring.acquire().expect("slot 1");
    let fb1 = second.fb_id;
    assert_ne!(fb1, 0);
    assert_ne!(
        fb1, fb0,
        "two slots sharing a framebuffer id would make the rotation change \
         nothing on screen"
    );

    ring.release(first);
    assert_eq!(
        *released.lock().expect("read the releases"),
        vec![0],
        "releasing the displaced frame returns exactly its slot to the producer"
    );

    // Nothing new submitted: the ring re-presents what is up rather than
    // reporting no frame, and holding does not release it.
    let held = ring.acquire().expect("hold the last frame");
    assert_eq!(held.fb_id, fb1);
    assert!(held.acquire_fence.is_none());
    ring.release(held);
    assert_eq!(
        released.lock().expect("read the releases").len(),
        1,
        "releasing a held frame must not hand its slot back -- it is still on screen"
    );

    ring.submit(0, None, &[]);
    let third = ring.acquire().expect("slot 0 again");
    assert_eq!(
        third.fb_id, fb0,
        "the ring came back round to the first slot"
    );

    ring.release(second);
    assert_eq!(*released.lock().expect("read the releases"), vec![0, 1]);
    ring.release(third);
}

/// `RetiredRingReleasesItsScanningSlot`: a retired ring gets no newer frame,
/// so its scanning slot would never be displaced. `on_retired` lets it go with
/// the last acquisition.
#[test]
#[ignore = "needs a DRM device; run under the vkms lane with --include-ignored"]
fn a_retired_ring_releases_its_scanning_slot_vkms() {
    let _guard = card_guard();
    let Some(device) = open_card() else { return };
    let Some((mut ring, _fds)) = ring_of(&device, 2) else {
        println!("note: skipped -- no importable dma-buf on this card");
        return;
    };
    let released: std::sync::Arc<std::sync::Mutex<Vec<usize>>> = std::sync::Arc::default();
    let recorder = std::sync::Arc::clone(&released);
    ring.set_on_release(Box::new(move |slot, _fence| {
        recorder.lock().expect("record the release").push(slot);
    }));

    ring.submit(1, None, &[]);
    let live = ring.acquire().expect("slot 1");

    ring.on_retired();
    ring.release(live);
    assert_eq!(
        *released.lock().expect("read the releases"),
        vec![1],
        "the producer would never get its last frame's slot back"
    );
}

/// Damage rides with the frame it was submitted for, and only that frame.
///
/// A held frame reports none: nothing changed since it went up, so repeating
/// the previous frame's damage would make the driver repaint a region that is
/// already correct.
#[test]
#[ignore = "needs a DRM device; run under the vkms lane with --include-ignored"]
fn damage_rides_with_its_own_frame_and_no_other_vkms() {
    let _guard = card_guard();
    let Some(device) = open_card() else { return };
    let Some((mut ring, _fds)) = ring_of(&device, 2) else {
        println!("note: skipped -- no importable dma-buf on this card");
        return;
    };

    let two = [
        DamageRect {
            x: 1,
            y: 2,
            w: 3,
            h: 4,
        },
        DamageRect {
            x: 10,
            y: 20,
            w: 30,
            h: 40,
        },
    ];
    ring.submit(0, None, &two);
    let first = ring.acquire().expect("slot 0");
    assert_eq!(first.damage, two, "both rects, in the order submitted");

    let held = ring.acquire().expect("hold");
    assert!(
        held.damage.is_empty(),
        "a held frame changed nothing, so it damages nothing"
    );
    ring.release(held);

    let one = [DamageRect {
        x: 5,
        y: 6,
        w: 7,
        h: 8,
    }];
    ring.submit(1, None, &one);
    let second = ring.acquire().expect("slot 1");
    assert_eq!(
        second.damage, one,
        "this frame's damage, not the last one's"
    );

    ring.release(first);
    ring.release(second);

    ring.submit(0, None, &[]);
    let third = ring.acquire().expect("slot 0");
    assert!(
        third.damage.is_empty(),
        "submitting no damage means no damage, not the previous set"
    );
    ring.release(third);
}

/// With a deadline configured, a frame submitted without a fence still
/// advances, and no fence is ever handed to the kernel.
///
/// The deadline turns the producer's fence into a CPU pre-wait. A ring that
/// also passed it on as `IN_FENCE_FD` would make the kernel wait a second time
/// on a fence already known to have signaled.
#[test]
#[ignore = "needs a DRM device; run under the vkms lane with --include-ignored"]
fn a_deadline_ring_advances_on_a_frame_with_no_fence_vkms() {
    let _guard = card_guard();
    let Some(device) = open_card() else { return };
    let Some((mut ring, _fds)) =
        deadline_ring_of(&device, 2, Some(std::time::Duration::from_millis(5)))
    else {
        println!("note: skipped -- no importable dma-buf on this card");
        return;
    };

    ring.submit(0, None, &[]);
    let first = ring.acquire().expect("slot 0");
    let fb0 = first.fb_id;
    assert_ne!(fb0, 0);
    assert!(
        first.acquire_fence.is_none(),
        "under a deadline the fence is pre-waited here, never wired to KMS"
    );

    ring.submit(1, None, &[]);
    let second = ring.acquire().expect("slot 1");
    assert_ne!(second.fb_id, fb0, "the ring advanced");
    assert!(second.acquire_fence.is_none());

    ring.release(first);
    ring.release(second);
}

/// A fence that misses its deadline holds the last good frame, and the ring
/// recovers when a signaled one arrives.
///
/// Holding is the point: advancing to a slot whose producer has not finished
/// writing puts a half-rendered frame on screen. Missing the deadline is a
/// late frame, which is a dropped frame -- not a torn one.
#[test]
#[ignore = "needs a DRM device; run under the vkms lane with --include-ignored"]
fn a_missed_fence_deadline_holds_the_last_frame_then_recovers_vkms() {
    let _guard = card_guard();
    let Some(device) = open_card() else { return };
    let Some((mut ring, _fds)) =
        deadline_ring_of(&device, 2, Some(std::time::Duration::from_millis(30)))
    else {
        println!("note: skipped -- no importable dma-buf on this card");
        return;
    };

    ring.submit(0, None, &[]);
    let first = ring.acquire().expect("slot 0");
    let fb0 = first.fb_id;
    assert_ne!(fb0, 0);

    let Some((unsignaled, _writer)) = pipe_fence(false) else {
        println!("note: skipped -- no pipe to stand in for a fence");
        return;
    };
    ring.submit(1, Some(unsignaled), &[]);

    let held = ring.acquire().expect("a deadline miss is not an error");
    assert_eq!(
        held.fb_id, fb0,
        "a missed deadline holds the last good slot rather than advancing to \
         one the producer has not finished"
    );
    assert!(
        held.acquire_fence.is_none(),
        "the fence was pre-waited, so it is never handed to the kernel"
    );
    ring.release(held);

    // Resubmit the same slot behind a fence that has already signaled.
    let (signaled, _writer) = pipe_fence(true).expect("a signaled fence");
    ring.submit(1, Some(signaled), &[]);

    let recovered = ring.acquire().expect("recover");
    assert_ne!(
        recovered.fb_id, fb0,
        "with the fence signaled the ring advances to the frame it held back"
    );
    ring.release(first);
    ring.release(recovered);
}

/// A dropped frame's damage is unioned into the next one, and only the next.
///
/// The dropped frame's pixels were never scanned out, so the region it
/// declared is still stale on screen. If the next frame reported only its own
/// damage, the driver would repaint that region and leave the dropped one
/// showing the frame before it. Carrying it forever would be the other error:
/// it would over-report every frame from here on.
#[test]
#[ignore = "needs a DRM device; run under the vkms lane with --include-ignored"]
fn a_dropped_frames_damage_is_carried_into_the_next_one_only_vkms() {
    let _guard = card_guard();
    let Some(device) = open_card() else { return };
    let Some((mut ring, _fds)) =
        deadline_ring_of(&device, 2, Some(std::time::Duration::from_millis(30)))
    else {
        println!("note: skipped -- no importable dma-buf on this card");
        return;
    };

    ring.submit(0, None, &[]);
    let first = ring.acquire().expect("slot 0");

    let dropped = [
        DamageRect {
            x: 1,
            y: 1,
            w: 2,
            h: 2,
        },
        DamageRect {
            x: 3,
            y: 3,
            w: 4,
            h: 4,
        },
    ];
    let Some((unsignaled, _writer)) = pipe_fence(false) else {
        println!("note: skipped -- no pipe to stand in for a fence");
        return;
    };
    ring.submit(1, Some(unsignaled), &dropped);

    let held = ring.acquire().expect("the deadline miss holds");
    assert!(
        held.damage.is_empty(),
        "a held frame changed nothing since it went up"
    );
    ring.release(held);

    let arriving = [DamageRect {
        x: 5,
        y: 5,
        w: 6,
        h: 6,
    }];
    let (signaled, _writer) = pipe_fence(true).expect("a signaled fence");
    ring.submit(1, Some(signaled), &arriving);

    let advanced = ring.acquire().expect("advance");
    assert_eq!(
        advanced.damage,
        [dropped[0], dropped[1], arriving[0]],
        "the dropped frame's regions are still stale on screen, so they have \
         to be repainted alongside this frame's"
    );

    // One frame only: the carry was consumed above.
    ring.submit(0, None, &arriving);
    let plain = ring.acquire().expect("the frame after");
    assert_eq!(
        plain.damage, arriving,
        "carrying past one frame would over-report every frame from here on"
    );

    ring.release(first);
    ring.release(advanced);
    ring.release(plain);
}

/// Dropping a whole-frame update forces the next frame to whole-frame.
///
/// Empty damage means *everything changed*. There is no rect list that says
/// that, so a dropped whole-frame update cannot be unioned into the next
/// frame's rects -- carrying nothing would silently downgrade it to "only what
/// the next frame touched", leaving the rest of the screen stale.
#[test]
#[ignore = "needs a DRM device; run under the vkms lane with --include-ignored"]
fn a_dropped_whole_frame_forces_the_next_to_whole_frame_vkms() {
    let _guard = card_guard();
    let Some(device) = open_card() else { return };
    let Some((mut ring, _fds)) =
        deadline_ring_of(&device, 2, Some(std::time::Duration::from_millis(30)))
    else {
        println!("note: skipped -- no importable dma-buf on this card");
        return;
    };

    ring.submit(0, None, &[]);
    let first = ring.acquire().expect("slot 0");

    // Whole-frame, and dropped.
    let Some((unsignaled, _writer)) = pipe_fence(false) else {
        println!("note: skipped -- no pipe to stand in for a fence");
        return;
    };
    ring.submit(1, Some(unsignaled), &[]);
    let held = ring.acquire().expect("the deadline miss holds");
    ring.release(held);

    // The next frame declares a small region; the drop must override it.
    let (signaled, _writer) = pipe_fence(true).expect("a signaled fence");
    ring.submit(
        1,
        Some(signaled),
        &[DamageRect {
            x: 5,
            y: 5,
            w: 6,
            h: 6,
        }],
    );

    let advanced = ring.acquire().expect("advance");
    assert!(
        advanced.damage.is_empty(),
        "a dropped whole-frame update cannot be expressed as rects, so the \
         next frame must repaint everything"
    );

    ring.release(first);
    ring.release(advanced);
}

// --- ExternalDmaBufPool, against a card ---------------------------------------
//
// Parity port of `tests/integration/test_external_dma_buf_pool_vkms.cpp`.

/// One imported dma-buf, ready to submit under any key.
#[cfg(test)]
fn pool_planes(device: &Device) -> Option<(OwnedFd, u32)> {
    real_dma_buf(device, 64, 64)
}

/// A submitted key advances the pool; with nothing new, it holds what is up.
#[test]
#[ignore = "needs a DRM device; run under the vkms lane with --include-ignored"]
fn a_pool_advances_on_a_new_key_and_holds_when_idle_vkms() {
    let _guard = card_guard();
    let Some(device) = open_card() else { return };
    let Some((a_fd, a_pitch)) = pool_planes(&device) else {
        println!("note: skipped -- no importable dma-buf on this card");
        return;
    };
    let Some((b_fd, b_pitch)) = pool_planes(&device) else {
        return;
    };
    let a = [ExternalPlane {
        fd: a_fd.as_fd(),
        offset: 0,
        pitch: a_pitch,
    }];
    let b = [ExternalPlane {
        fd: b_fd.as_fd(),
        offset: 0,
        pitch: b_pitch,
    }];

    let mut pool = ExternalDmaBufPool::new(pool_format(), None);
    pool.submit(&device, 0xA, &a, None, &[]).expect("submit");
    let first = pool.acquire().expect("key A").fb_id;
    assert_ne!(first, 0);
    assert!(
        !pool.has_fresh_content(),
        "the frame was taken, so there is nothing fresh waiting behind it"
    );

    let held = pool.acquire().expect("hold");
    assert_eq!(
        held.fb_id, first,
        "with nothing new, the last frame stays up"
    );

    pool.submit(&device, 0xB, &b, None, &[]).expect("submit");
    assert!(
        pool.has_fresh_content(),
        "a submitted frame is what makes the scene bother committing"
    );
    let second = pool.acquire().expect("key B").fb_id;
    assert_ne!(second, 0);
    assert_ne!(second, first, "a different key is a different buffer");
}

/// Releasing a displaced buffer hands its key back; releasing the one still on
/// screen does not.
///
/// The producer reuses a buffer as soon as it hears about it. Firing for the
/// buffer still being scanned out would have it overwritten mid-frame.
#[test]
#[ignore = "needs a DRM device; run under the vkms lane with --include-ignored"]
fn a_pool_releases_the_displaced_key_and_not_the_live_one_vkms() {
    let _guard = card_guard();
    let Some(device) = open_card() else { return };
    let Some((a_fd, a_pitch)) = pool_planes(&device) else {
        println!("note: skipped -- no importable dma-buf on this card");
        return;
    };
    let Some((b_fd, b_pitch)) = pool_planes(&device) else {
        return;
    };
    let a = [ExternalPlane {
        fd: a_fd.as_fd(),
        offset: 0,
        pitch: a_pitch,
    }];
    let b = [ExternalPlane {
        fd: b_fd.as_fd(),
        offset: 0,
        pitch: b_pitch,
    }];

    let released: std::sync::Arc<std::sync::Mutex<Vec<usize>>> = std::sync::Arc::default();
    let recorder = std::sync::Arc::clone(&released);
    let mut pool = ExternalDmaBufPool::new(pool_format(), None);
    pool.set_on_release(Box::new(move |key, _fence| {
        recorder.lock().expect("record").push(key);
    }));
    assert!(
        pool.wants_release_fence(),
        "with a listener attached the scene is worth asking for an out-fence"
    );

    pool.submit(&device, 0xA, &a, None, &[]).expect("submit");
    let first = pool.acquire().expect("key A");
    pool.submit(&device, 0xB, &b, None, &[]).expect("submit");
    let second = pool.acquire().expect("key B");

    pool.release_with_fence(first, None);
    assert_eq!(
        *released.lock().expect("read"),
        vec![0xA],
        "A was displaced by B, so A is the producer's again"
    );

    pool.release_with_fence(second, None);
    assert_eq!(
        released.lock().expect("read").len(),
        1,
        "B is still on screen; handing it back would let the producer \
         overwrite what is being scanned out"
    );
}

/// `RetiredPoolReleasesItsScanningKey`: a retired pool (its layer removed)
/// gets no newer frame, so its scanning key would never be displaced.
/// `on_retired` lets it go with the last acquisition, once.
#[test]
#[ignore = "needs a DRM device; run under the vkms lane with --include-ignored"]
fn a_retired_pool_releases_its_scanning_key_vkms() {
    let _guard = card_guard();
    let Some(device) = open_card() else { return };
    let Some(buffers) = two_pool_buffers(&device) else {
        return;
    };
    let released: std::sync::Arc<std::sync::Mutex<Vec<usize>>> = std::sync::Arc::default();
    let recorder = std::sync::Arc::clone(&released);
    let mut pool = ExternalDmaBufPool::new(pool_format(), None);
    pool.set_on_release(Box::new(move |key, _fence| {
        recorder.lock().expect("record").push(key);
    }));

    pool.submit(&device, 0xA, &one_plane(&buffers[0]), None, &[])
        .expect("submit");
    let first = pool.acquire().expect("key A");
    let hold = pool.acquire().expect("an idle hold, same token");

    pool.release_with_fence(first, None);
    assert!(
        released.lock().expect("read").is_empty(),
        "A is still on screen"
    );

    pool.on_retired();
    pool.release_with_fence(hold, None);
    assert_eq!(
        *released.lock().expect("read"),
        vec![0xA],
        "a client making a new pool per geometry would lose a buffer to every \
         resize"
    );
}

/// Beyond the cap, the least recently used idle import is dropped.
///
/// Without this the pool grows for as long as the producer keeps minting keys,
/// and each entry holds a GEM handle, a framebuffer and a descriptor until the
/// pool itself drops.
#[test]
#[ignore = "needs a DRM device; run under the vkms lane with --include-ignored"]
fn a_pool_evicts_its_least_recently_used_idle_import_vkms() {
    let _guard = card_guard();
    let Some(device) = open_card() else { return };
    let Some((fd, pitch)) = pool_planes(&device) else {
        println!("note: skipped -- no importable dma-buf on this card");
        return;
    };
    let planes = [ExternalPlane {
        fd: fd.as_fd(),
        offset: 0,
        pitch,
    }];

    let mut pool = ExternalDmaBufPool::new(pool_format(), None);
    pool.set_max_pool(2);

    pool.submit(&device, 0xA, &planes, None, &[])
        .expect("submit");
    let first = pool.acquire().expect("key A");
    pool.submit(&device, 0xB, &planes, None, &[])
        .expect("submit");
    let second = pool.acquire().expect("key B");

    // A is now idle and unreferenced: displaced from the screen and released.
    pool.release_with_fence(first, None);
    assert_eq!(pool.cached_count(), 2);

    pool.submit(&device, 0xC, &planes, None, &[])
        .expect("submit");
    assert_eq!(
        pool.cached_count(),
        2,
        "the third key must displace the stalest one, not push the cache over \
         its cap"
    );
    let third = pool.acquire().expect("key C");
    pool.release_with_fence(second, None);
    pool.release_with_fence(third, None);
}

/// An import the kernel is still scanning out is not torn down to make room.
///
/// It is marked instead, and goes on the next acquire that finds it
/// unreferenced. Destroying a framebuffer mid-scanout is how a display tears.
#[test]
#[ignore = "needs a DRM device; run under the vkms lane with --include-ignored"]
fn eviction_waits_for_a_buffer_that_is_still_in_flight_vkms() {
    let _guard = card_guard();
    let Some(device) = open_card() else { return };
    let Some((fd, pitch)) = pool_planes(&device) else {
        println!("note: skipped -- no importable dma-buf on this card");
        return;
    };
    let planes = [ExternalPlane {
        fd: fd.as_fd(),
        offset: 0,
        pitch,
    }];

    let mut pool = ExternalDmaBufPool::new(pool_format(), None);
    pool.set_max_pool(1);

    pool.submit(&device, 0xA, &planes, None, &[])
        .expect("submit");
    let first = pool.acquire().expect("key A");

    pool.submit(&device, 0xB, &planes, None, &[])
        .expect("submit");
    let second = pool.acquire().expect("key B");
    assert_eq!(
        pool.cached_count(),
        2,
        "over the cap, but A's commit has not retired -- tearing it down here \
         would destroy a framebuffer the kernel is reading"
    );

    pool.release_with_fence(first, None);
    let held = pool.acquire().expect("hold B, and sweep");
    assert_eq!(
        pool.cached_count(),
        1,
        "with A's token retired the deferred eviction goes through"
    );

    pool.release_with_fence(held, None);
    pool.release_with_fence(second, None);
}

/// A new generation retires the old buffers, once nothing references them.
#[test]
#[ignore = "needs a DRM device; run under the vkms lane with --include-ignored"]
fn a_new_generation_retires_the_previous_buffers_vkms() {
    let _guard = card_guard();
    let Some(device) = open_card() else { return };
    let Some((fd, pitch)) = pool_planes(&device) else {
        println!("note: skipped -- no importable dma-buf on this card");
        return;
    };
    let Some((small_fd, small_pitch)) = real_dma_buf(&device, 32, 32) else {
        return;
    };
    let planes = [ExternalPlane {
        fd: fd.as_fd(),
        offset: 0,
        pitch,
    }];
    let small = [ExternalPlane {
        fd: small_fd.as_fd(),
        offset: 0,
        pitch: small_pitch,
    }];

    let mut pool = ExternalDmaBufPool::new(pool_format(), None);
    pool.submit(&device, 0xA, &planes, None, &[])
        .expect("submit");
    let first = pool.acquire().expect("key A");
    assert_eq!(pool.cached_count(), 1);

    let next = SourceFormat {
        fourcc: XRGB8888,
        modifier: 0,
        width: 32,
        height: 32,
    };
    pool.reset_generation(next);
    assert_eq!(
        LayerBufferSource::format(&pool),
        next,
        "future submits import at the new geometry"
    );
    assert_eq!(
        pool.cached_count(),
        1,
        "A is marked, not destroyed: the kernel is still scanning it out"
    );

    // The new generation must arrive under a fresh key.
    pool.submit(&device, 0xB, &small, None, &[])
        .expect("submit");
    let second = pool.acquire().expect("key B");
    assert_eq!(
        pool.cached_count(),
        2,
        "A's teardown is still deferred past its commit"
    );

    pool.release_with_fence(first, None);
    let held = pool.acquire().expect("hold, and sweep");
    assert_eq!(
        pool.cached_count(),
        1,
        "with A retired only the new generation is left"
    );

    pool.release_with_fence(held, None);
    pool.release_with_fence(second, None);
}

/// A submit the pool cannot import is skipped, and the last good frame stays.
///
/// A frozen layer beats a blank one, so the frame is dropped and what is on
/// screen stays. The caller hears why (drm-cxx `2c3bf65`): it may have
/// somewhere else to send the buffer.
#[test]
#[ignore = "needs a DRM device; run under the vkms lane with --include-ignored"]
fn a_submit_the_pool_cannot_import_holds_the_last_frame_vkms() {
    let _guard = card_guard();
    let Some(device) = open_card() else { return };
    let Some((fd, pitch)) = pool_planes(&device) else {
        println!("note: skipped -- no importable dma-buf on this card");
        return;
    };
    let planes = [ExternalPlane {
        fd: fd.as_fd(),
        offset: 0,
        pitch,
    }];

    let mut pool = ExternalDmaBufPool::new(pool_format(), None);
    pool.submit(&device, 0xA, &planes, None, &[])
        .expect("submit");
    let good = pool.acquire().expect("key A");
    let fb_a = good.fb_id;

    // A descriptor that is not a dma-buf at all: the PRIME import refuses it.
    let (not_a_buffer, _writer) = std::io::pipe().expect("a pipe is not a dma-buf");
    let bad = [ExternalPlane {
        fd: std::os::fd::AsFd::as_fd(&not_a_buffer),
        offset: 0,
        pitch,
    }];
    assert!(
        matches!(
            pool.submit(&device, 0xBAD, &bad, None, &[]),
            Err(ExternalError::Io(_))
        ),
        "an import the device refused must say so, so the caller can route the \
         buffer elsewhere"
    );
    assert_eq!(
        pool.cached_count(),
        1,
        "nothing was imported, so nothing is cached"
    );
    assert!(
        !pool.has_fresh_content(),
        "and it never reached the presenter, so there is no frame to commit"
    );

    let held = pool.acquire().expect("holding is not an error");
    assert_eq!(
        held.fb_id, fb_a,
        "the last good frame stays up rather than the layer going blank"
    );

    pool.release_with_fence(held, None);
    pool.release_with_fence(good, None);
}

/// Two imported dma-bufs for the retire cases, or `None` with a note.
#[cfg(test)]
fn two_pool_buffers(device: &Device) -> Option<[(OwnedFd, u32); 2]> {
    let pair = pool_planes(device).zip(pool_planes(device));
    if pair.is_none() {
        println!("note: skipped -- no importable dma-buf on this card");
    }
    pair.map(|(a, b)| [a, b])
}

/// One plane over `buffer`.
#[cfg(test)]
fn one_plane(buffer: &(OwnedFd, u32)) -> [ExternalPlane<'_>; 1] {
    [ExternalPlane {
        fd: buffer.0.as_fd(),
        offset: 0,
        pitch: buffer.1,
    }]
}

/// `RetireTearsDownAnIdleBuffer`: a retired buffer off screen is torn down at
/// the next sweep, without waiting for the cap.
#[test]
#[ignore = "needs a DRM device; run under the vkms lane with --include-ignored"]
fn retire_tears_down_an_idle_buffer_vkms() {
    let _guard = card_guard();
    let Some(device) = open_card() else { return };
    let Some(buffers) = two_pool_buffers(&device) else {
        return;
    };
    let mut pool = ExternalDmaBufPool::new(pool_format(), None);
    pool.submit(&device, 0xA, &one_plane(&buffers[0]), None, &[])
        .expect("submit A");
    pool.submit(&device, 0xB, &one_plane(&buffers[1]), None, &[])
        .expect("submit B");
    // B scanning; A was superseded before it was ever scanned out.
    let _b = pool.acquire().expect("key B");
    assert_eq!(pool.cached_count(), 2);

    pool.retire(0xA);
    assert_eq!(pool.cached_count(), 2, "torn down on the commit thread");
    let _held = pool.acquire().expect("the sweep");
    assert_eq!(pool.cached_count(), 1);
}

/// `RetireWaitsForTheBufferToLeaveScanout`: a retired buffer still on screen
/// stays until a later frame displaces it and the commits that scanned it
/// retire.
#[test]
#[ignore = "needs a DRM device; run under the vkms lane with --include-ignored"]
fn retire_waits_for_the_buffer_to_leave_scanout_vkms() {
    let _guard = card_guard();
    let Some(device) = open_card() else { return };
    let Some(buffers) = two_pool_buffers(&device) else {
        return;
    };
    let mut pool = ExternalDmaBufPool::new(pool_format(), None);
    pool.submit(&device, 0xA, &one_plane(&buffers[0]), None, &[])
        .expect("submit A");
    let a = pool.acquire().expect("key A");
    pool.retire(0xA);
    let still = pool.acquire().expect("A is held, still on screen");
    assert_eq!(still.fb_id, a.fb_id);
    assert_eq!(pool.cached_count(), 1);

    pool.submit(&device, 0xB, &one_plane(&buffers[1]), None, &[])
        .expect("submit B");
    let _b = pool.acquire().expect("B displaces A");
    assert_eq!(pool.cached_count(), 2, "A's commits have not retired");

    pool.release_with_fence(a, None);
    pool.release_with_fence(still, None);
    let _held = pool.acquire().expect("the sweep");
    assert_eq!(pool.cached_count(), 1, "nothing references A now");
}

/// `RetiredKeyImportsAfreshOnlyOnceTornDown`: a retired key may name a
/// different dma-buf when it comes back, so its cached import must not stand
/// in for it. Until the old import is gone the frame is refused, and after
/// that the key imports afresh.
#[test]
#[ignore = "needs a DRM device; run under the vkms lane with --include-ignored"]
fn a_retired_key_imports_afresh_only_once_torn_down_vkms() {
    let _guard = card_guard();
    let Some(device) = open_card() else { return };
    let Some(buffers) = two_pool_buffers(&device) else {
        return;
    };
    let mut pool = ExternalDmaBufPool::new(pool_format(), None);
    pool.submit(&device, 0xA, &one_plane(&buffers[0]), None, &[])
        .expect("submit A");
    let a = pool.acquire().expect("key A");
    pool.retire(0xA);

    // Key A again, now naming the other buffer, while the old import is on
    // screen: the frame is refused and the old buffer holds.
    assert!(matches!(
        pool.submit(&device, 0xA, &one_plane(&buffers[1]), None, &[]),
        Err(ExternalError::Retired)
    ));
    let held = pool.acquire().expect("the old A holds");
    assert_eq!(held.fb_id, a.fb_id);

    // Displace and retire the old import; then key A imports afresh.
    pool.submit(&device, 0xB, &one_plane(&buffers[1]), None, &[])
        .expect("submit B");
    let _b = pool.acquire().expect("key B");
    pool.release_with_fence(a, None);
    pool.release_with_fence(held, None);
    let _swept = pool.acquire().expect("tears the old A down");
    assert_eq!(pool.cached_count(), 1);

    pool.submit(&device, 0xA, &one_plane(&buffers[1]), None, &[])
        .expect("a fresh import under key A");
    assert_eq!(pool.cached_count(), 2);
    let fresh = pool.acquire().expect("the new A");
    assert_ne!(fresh.fb_id, 0);
}

/// `RetireOfAnUnknownKeyIsANoOp`: never imported, so never stale, and the
/// key imports normally afterwards.
#[test]
#[ignore = "needs a DRM device; run under the vkms lane with --include-ignored"]
fn retiring_an_unknown_key_is_a_no_op_vkms() {
    let _guard = card_guard();
    let Some(device) = open_card() else { return };
    let Some(buffer) = pool_planes(&device) else {
        println!("note: skipped -- no importable dma-buf on this card");
        return;
    };
    let pool = ExternalDmaBufPool::new(pool_format(), None);
    pool.retire(0x99);
    pool.submit(&device, 0x99, &one_plane(&buffer), None, &[])
        .expect("an unknown key was never retired");
    assert_eq!(pool.cached_count(), 1);
}

/// `SubmitReportsAFrameItCannotTake`: a modifier the device cannot scan out
/// is refused at import, and the caller hears about it instead of finding an
/// empty pool at commit time.
#[test]
#[ignore = "needs a DRM device; run under the vkms lane with --include-ignored"]
fn submit_reports_a_frame_it_cannot_take_vkms() {
    /// `DRM_FORMAT_MOD_BROADCOM_UIF`: vendor 0x07, value 6.
    const BROADCOM_UIF: u64 = (0x07 << 56) | 6;
    let _guard = card_guard();
    let Some(device) = open_card() else { return };
    let Some(buffer) = pool_planes(&device) else {
        println!("note: skipped -- no importable dma-buf on this card");
        return;
    };
    let tiled = SourceFormat {
        modifier: BROADCOM_UIF,
        ..pool_format()
    };
    let mut pool = ExternalDmaBufPool::new(tiled, None);
    let refused = pool.submit(&device, 0xA, &one_plane(&buffer), None, &[]);
    if refused.is_ok() {
        // vc4 scans UIF out: there the modifier is not one it refuses.
        println!("note: skipped -- this card accepts BROADCOM_UIF");
        return;
    }
    assert!(matches!(refused, Err(ExternalError::Io(_))), "{refused:?}");
    assert_eq!(pool.cached_count(), 0);
    assert!(matches!(pool.acquire(), Err(SourceError::WouldBlock)));
}

// --- DmaBufSourceCache, against a card ----------------------------------------
//
// Parity port of `tests/integration/test_dma_buf_source_cache_vkms.cpp`.

/// A key hits, a changed shape under the same key replaces it, and evicting
/// or clearing empties the cache.
///
/// The staleness rule is the one worth having on a card. A producer that
/// reallocates at a new resolution keeps its buffer keys -- a V4L2 index, a
/// slot number -- so a cache that only ever hit would hand back a framebuffer
/// describing the previous geometry, and the kernel would scan out the new
/// buffer through the old shape.
#[test]
#[ignore = "needs a DRM device; run under the vkms lane with --include-ignored"]
fn a_cached_key_hits_until_its_shape_changes_vkms() {
    let _guard = card_guard();
    let Some(device) = open_card() else { return };
    let Some((fd, pitch)) = real_dma_buf(&device, 64, 64) else {
        println!("note: skipped -- no importable dma-buf on this card");
        return;
    };
    let planes = [ExternalPlane {
        fd: fd.as_fd(),
        offset: 0,
        pitch,
    }];

    let mut cache = DmaBufSourceCache::new();
    assert!(cache.is_empty(), "a cache starts empty");

    let first = cache
        .get_or_create(7, &device, pool_format(), &planes)
        .expect("import")
        .fb_id();
    assert_eq!(cache.len(), 1);
    assert!(cache.find(7).is_some());

    let again = cache
        .get_or_create(7, &device, pool_format(), &planes)
        .expect("hit")
        .fb_id();
    assert_eq!(first, again, "the same key and shape must reuse the import");
    assert_eq!(cache.len(), 1, "and not import a second time");

    // Same key, new shape: the entry is stale and must be replaced.
    let smaller = SourceFormat {
        fourcc: XRGB8888,
        modifier: 0,
        width: 32,
        height: 32,
    };
    let replaced = cache
        .get_or_create(7, &device, smaller, &planes)
        .expect("re-import at the new shape");
    assert_eq!(
        LayerBufferSource::format(replaced),
        smaller,
        "a hit here would describe the new buffer with the old geometry"
    );
    assert_eq!(cache.len(), 1, "replaced, not accumulated");

    assert!(cache.evict(7));
    assert!(cache.is_empty());
    assert!(cache.find(7).is_none());

    cache.clear();
    assert!(cache.is_empty(), "clearing an empty cache is not an error");
}

/// An explicit modifier reaches the kernel, and so does its absence.
///
/// Which path each takes is `drmkit_core::framebuffer_modifier`'s call: the
/// `INVALID` sentinel always goes as "no modifier", and `LINEAR` is declared
/// exactly when the driver has `DRM_CAP_ADDFB2_MODIFIERS` -- upstream's rule
/// since `be147be`, after LCDIF-class drivers refused the declared form even
/// for linear. Both have to produce a framebuffer, and a cache that conflated
/// them would send one down the other's path.
#[test]
#[ignore = "needs a DRM device; run under the vkms lane with --include-ignored"]
fn an_explicit_modifier_and_its_absence_both_import_vkms() {
    let _guard = card_guard();
    let Some(device) = open_card() else { return };
    let Some((fd, pitch)) = real_dma_buf(&device, 64, 64) else {
        println!("note: skipped -- no importable dma-buf on this card");
        return;
    };
    let planes = [ExternalPlane {
        fd: fd.as_fd(),
        offset: 0,
        pitch,
    }];

    let mut cache = DmaBufSourceCache::new();

    // LINEAR: declared where the driver takes modifiers, otherwise not.
    let implicit = cache
        .get_or_create(1, &device, pool_format(), &planes)
        .expect("import with no declared modifier");
    let implicit_fb = implicit.acquire().expect("acquire").fb_id;
    assert_ne!(implicit_fb, 0);

    // The INVALID sentinel means "the producer is not saying", and takes the
    // same default path rather than being declared as a real layout.
    let unstated = SourceFormat {
        fourcc: XRGB8888,
        modifier: drmkit_fmt::Modifier::INVALID.0,
        width: 64,
        height: 64,
    };
    let sentinel = cache
        .get_or_create(2, &device, unstated, &planes)
        .expect("import with the INVALID sentinel");
    let sentinel_fb = sentinel.acquire().expect("acquire").fb_id;
    assert_ne!(
        sentinel_fb, 0,
        "declaring INVALID to the kernel as a layout would be refused"
    );

    assert_ne!(
        implicit_fb, sentinel_fb,
        "two keys are two imports, whatever they say about modifiers"
    );
    assert_eq!(cache.len(), 2);

    // GETFB2 is Linux 5.7; on an older kernel there is nothing to read back.
    let declared = |fb_id: u32| {
        let handle = drm::control::framebuffer::Handle::from(
            std::num::NonZeroU32::new(fb_id).expect("non-zero"),
        );
        drm::control::Device::get_planar_framebuffer(&device, handle)
            .ok()
            .map(|info| info.modifier().map(u64::from))
    };
    match declared(implicit_fb) {
        None => println!("note: no GETFB2 on this kernel; the readback is skipped"),
        Some(modifier) if drmkit_core::supports_framebuffer_modifiers(&device) => {
            assert_eq!(modifier, Some(0), "a LINEAR import is LINEAR");
        }
        Some(_) => {}
    }
}

/// The pool lends its acquired import's descriptors, like the other two.
///
/// This was the one of the three that could not, and the reason was
/// structural rather than an oversight: its imports live behind a `Mutex`,
/// and `DmaBufDesc` borrows what it describes, so a borrow taken inside the
/// guard cannot outlive it. Holding the acquired import as an `Arc` outside
/// the lock is what makes the borrow come from the pool. Recorded as P-29
/// while it was open.
#[test]
#[ignore = "needs a DRM device; run under the vkms lane with --include-ignored"]
fn a_pool_lends_its_acquired_descriptors_vkms() {
    let _guard = card_guard();
    let Some(device) = open_card() else { return };
    let Some((fd, pitch)) = pool_planes(&device) else {
        println!("note: skipped -- no importable dma-buf on this card");
        return;
    };
    let planes = [ExternalPlane {
        fd: fd.as_fd(),
        offset: 0,
        pitch,
    }];

    let mut pool = ExternalDmaBufPool::new(pool_format(), None);

    assert!(
        matches!(pool.export_dma_buf(), Err(SourceError::Unsupported)),
        "nothing has been acquired, so there is nothing to describe"
    );

    pool.submit(&device, 0xA, &planes, None, &[])
        .expect("submit");
    let acquired = pool.acquire().expect("key A");

    let exported = pool
        .export_dma_buf()
        .expect("the pool has to lend, like the others");
    assert_eq!(exported.fds.len(), 1);
    assert_eq!(exported.pitches, vec![pitch]);
    assert_eq!(exported.format, pool_format());

    assert!(
        matches!(
            pool.map(drmkit_dumb::MapAccess::Read),
            Err(SourceError::Unsupported)
        ),
        "and the CPU map is still correctly unsupported -- the export is what \
         keeps the layer compositable, not a mapping"
    );

    pool.release(acquired);
}

/// A session pause drops what the pool was lending.
///
/// The descriptors belong to a device that is going away. Continuing to
/// describe them would have composition read from a buffer whose backing is
/// gone.
#[test]
#[ignore = "needs a DRM device; run under the vkms lane with --include-ignored"]
fn a_paused_pool_lends_nothing_vkms() {
    let _guard = card_guard();
    let Some(device) = open_card() else { return };
    let Some((fd, pitch)) = pool_planes(&device) else {
        println!("note: skipped -- no importable dma-buf on this card");
        return;
    };
    let planes = [ExternalPlane {
        fd: fd.as_fd(),
        offset: 0,
        pitch,
    }];

    let mut pool = ExternalDmaBufPool::new(pool_format(), None);
    pool.submit(&device, 0xA, &planes, None, &[])
        .expect("submit");
    let acquired = pool.acquire().expect("key A");
    assert!(pool.export_dma_buf().is_ok());
    pool.release(acquired);

    pool.on_session_paused();

    assert!(
        matches!(pool.export_dma_buf(), Err(SourceError::Unsupported)),
        "the descriptors belong to a device that is going away"
    );
    assert_eq!(pool.cached_count(), 0, "and the imports went with it");
}