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

#include "igt.h"
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <poll.h>
#include <pthread.h>


IGT_TEST_DESCRIPTION("Test the Kernel's frontbuffer tracking mechanism and "
		     "its related features: FBC and PSR");

/*
 * One of the aspects of this test is that, for every subtest, we try different
 * combinations of the parameters defined by the struct below. Because of this,
 * a single addition of a new parameter or subtest function can lead to hundreds
 * of new subtests.
 *
 * In order to reduce the number combinations we cut the cases that don't make
 * sense, such as writing on the secondary screen when there is only a single
 * pipe, or flipping when the target is the offscreen buffer. We also hide some
 * combinations that are somewhat redundant and don't add much value to the
 * test. For example, since we already do the offscreen testing with a single
 * pipe enabled, there's no much value in doing it again with dual pipes. If you
 * still want to try these redundant tests, you need to use the --show-hidden
 * option.
 *
 * The most important hidden thing is the FEATURE_NONE set of tests. Whenever
 * you get a failure on any test, it is important to check whether the same test
 * fails with FEATURE_NONE - replace the feature name for "nop". If the nop test
 * also fails, then it's likely the problem will be on the IGT side instead of
 * the Kernel side. We don't expose this set of tests by default because (i)
 * they take a long time to test; and (ii) if the feature tests work, then it's
 * very likely that the nop tests will also work.
 */
struct test_mode {
	/* Are we going to enable just one monitor, or are we going to setup a
	 * dual screen environment for the test? */
	enum {
		PIPE_SINGLE = 0,
		PIPE_DUAL,
		PIPE_COUNT,
	} pipes;

	/* The primary screen is the one that's supposed to have the "feature"
	 * enabled on, but we have the option to draw on the secondary screen or
	 * on some offscreen buffer. We also only theck the CRC of the primary
	 * screen. */
	enum {
		SCREEN_PRIM = 0,
		SCREEN_SCND,
		SCREEN_OFFSCREEN,
		SCREEN_COUNT,
	} screen;

	/* When we draw, we can draw directly on the primary plane, on the
	 * cursor or on the sprite plane. */
	enum {
		PLANE_PRI = 0,
		PLANE_CUR,
		PLANE_SPR,
		PLANE_COUNT,
	} plane;

	/* We can organize the screens in a way that each screen has its own
	 * framebuffer, or in a way that all screens point to the same
	 * framebuffer, but on different places. This includes the offscreen
	 * screen. */
	enum {
		FBS_INDIVIDUAL = 0,
		FBS_SHARED,
		FBS_COUNT,
	} fbs;

	/* Which features are we going to test now? This is a mask!
	 * FEATURE_DEFAULT is a special value which instruct the test to just
	 * keep what's already enabled by default in the Kernel. */
	enum {
		FEATURE_NONE  = 0,
		FEATURE_FBC   = 1,
		FEATURE_PSR   = 2,
		FEATURE_COUNT = 4,
		FEATURE_DEFAULT = 4,
	} feature;

	/* Possible pixel formats. We just use FORMAT_DEFAULT for most tests and
	 * only test a few things on the other formats. */
	enum pixel_format {
		FORMAT_RGB888 = 0,
		FORMAT_RGB565,
		FORMAT_RGB101010,
		FORMAT_COUNT,
		FORMAT_DEFAULT = FORMAT_RGB888,
	} format;

	/* There are multiple APIs where we can do the equivalent of a page flip
	 * and they exercise slightly different codepaths inside the Kernel. */
	enum flip_type {
		FLIP_PAGEFLIP,
		FLIP_MODESET,
		FLIP_PLANES,
		FLIP_COUNT,
	} flip;

	enum igt_draw_method method;
};

enum color {
	COLOR_RED,
	COLOR_GREEN,
	COLOR_BLUE,
	COLOR_MAGENTA,
	COLOR_CYAN,
	COLOR_SCND_BG,
	COLOR_PRIM_BG = COLOR_BLUE,
	COLOR_OFFSCREEN_BG = COLOR_SCND_BG,
};

struct rect {
	int x;
	int y;
	int w;
	int h;
	uint32_t color;
};

#define MAX_CONNECTORS 32
#define MAX_PLANES 32
#define MAX_ENCODERS 32
struct {
	int fd;
	drmModeResPtr res;
	drmModeConnectorPtr connectors[MAX_CONNECTORS];
	drmModeEncoderPtr encoders[MAX_ENCODERS];
	drmModePlaneResPtr plane_res;
	drmModePlanePtr planes[MAX_PLANES];
	uint64_t plane_types[MAX_PLANES];
	drm_intel_bufmgr *bufmgr;
} drm;

struct {
	bool can_test;

	bool supports_last_action;

	struct timespec last_action;
} fbc = {
	.can_test = false,
	.supports_last_action = false,
};

struct {
	bool can_test;
} psr = {
	.can_test = false,
};


#define SINK_CRC_SIZE 12
typedef struct {
	char data[SINK_CRC_SIZE];
} sink_crc_t;

struct both_crcs {
	igt_crc_t pipe;
	sink_crc_t sink;
};

igt_pipe_crc_t *pipe_crc;
struct {
	bool initialized;
	struct both_crcs crc;
} blue_crcs[FORMAT_COUNT];
struct both_crcs *wanted_crc;

struct {
	int fd;
	bool supported;
	bool reliable;
} sink_crc = {
	.fd = -1,
	.supported = true,
	.reliable = true,
};

/* The goal of this structure is to easily allow us to deal with cases where we
 * have a big framebuffer and the CRTC is just displaying a subregion of this
 * big FB. */
struct fb_region {
	struct igt_fb *fb;
	int x;
	int y;
	int w;
	int h;
};

struct draw_pattern_info {
	bool frames_stack;
	int n_rects;
	struct rect (*get_rect)(struct fb_region *fb, int r);

	bool initialized[FORMAT_COUNT];
	struct both_crcs *crcs[FORMAT_COUNT];
};

/* Draw big rectangles on the screen. */
struct draw_pattern_info pattern1;
/* 64x64 rectangles at x:0,y:0, just so we can draw on the cursor and sprite. */
struct draw_pattern_info pattern2;
/* 64x64 rectangles at different positions, same color, for the move test. */
struct draw_pattern_info pattern3;
/* Just a fullscreen green square. */
struct draw_pattern_info pattern4;

/* Command line parameters. */
struct {
	bool check_status;
	bool check_crc;
	bool fbc_check_compression;
	bool fbc_check_last_action;
	bool no_edp;
	bool small_modes;
	bool show_hidden;
	int step;
	int only_pipes;
	int shared_fb_x_offset;
	int shared_fb_y_offset;
} opt = {
	.check_status = true,
	.check_crc = true,
	.fbc_check_compression = true,
	.fbc_check_last_action = true,
	.no_edp = false,
	.small_modes = false,
	.show_hidden= false,
	.step = 0,
	.only_pipes = PIPE_COUNT,
	.shared_fb_x_offset = 500,
	.shared_fb_y_offset = 500,
};

struct modeset_params {
	uint32_t crtc_id;
	uint32_t connector_id;
	uint32_t sprite_id;
	drmModeModeInfoPtr mode;
	struct fb_region fb;
	struct fb_region cursor;
	struct fb_region sprite;
};

struct modeset_params prim_mode_params;
struct modeset_params scnd_mode_params;
struct fb_region offscreen_fb;
struct screen_fbs {
	bool initialized;

	struct igt_fb prim_pri;
	struct igt_fb prim_cur;
	struct igt_fb prim_spr;

	struct igt_fb scnd_pri;
	struct igt_fb scnd_cur;
	struct igt_fb scnd_spr;

	struct igt_fb offscreen;
	struct igt_fb big;
} fbs[FORMAT_COUNT];

struct {
	pthread_t thread;
	bool stop;

	uint32_t handle;
	uint32_t size;
	uint32_t stride;
	int width;
	int height;
	uint32_t color;
	int bpp;
} busy_thread = {
	.stop = true,
};

drmModeModeInfo std_1024_mode = {
	.clock = 65000,
	.hdisplay = 1024,
	.hsync_start = 1048,
	.hsync_end = 1184,
	.htotal = 1344,
	.hskew = 0,
	.vdisplay = 768,
	.vsync_start = 771,
	.vsync_end = 777,
	.vtotal = 806,
	.vscan = 0,
	.vrefresh = 60,
	.flags = 0xA,
	.type = 0x40,
	.name = "Custom 1024x768",
};

static drmModeModeInfoPtr get_connector_smallest_mode(drmModeConnectorPtr c)
{
	int i;
	drmModeModeInfoPtr smallest = NULL;

	for (i = 0; i < c->count_modes; i++) {
		drmModeModeInfoPtr mode = &c->modes[i];

		if (!smallest)
			smallest = mode;

		if (mode->hdisplay * mode->vdisplay <
		    smallest->hdisplay * smallest->vdisplay)
			smallest = mode;
	}

	if (c->connector_type == DRM_MODE_CONNECTOR_eDP)
		smallest = &std_1024_mode;

	return smallest;
}

static drmModeConnectorPtr get_connector(uint32_t id)
{
	int i;

	for (i = 0; i < drm.res->count_connectors; i++)
		if (drm.res->connectors[i] == id)
			return drm.connectors[i];

	igt_assert(false);
}

static drmModeEncoderPtr get_encoder(uint32_t id)
{
	int i;

	for (i = 0; i < drm.res->count_encoders; i++)
		if (drm.res->encoders[i] == id)
			return drm.encoders[i];

	igt_assert(false);
}

static void print_mode_info(const char *screen, struct modeset_params *params)
{
	drmModeConnectorPtr c = get_connector(params->connector_id);

	igt_info("%s screen: %s %s, crtc %d\n",
		 screen,
		 kmstest_connector_type_str(c->connector_type),
		 params->mode->name,
		 kmstest_get_crtc_idx(drm.res, params->crtc_id));
}

static void init_mode_params(struct modeset_params *params, uint32_t crtc_id,
			     drmModeConnectorPtr connector,
			     drmModeModeInfoPtr mode)
{
	uint32_t overlay_plane_id = 0;
	int crtc_idx = kmstest_get_crtc_idx(drm.res, crtc_id);
	int i;

	for (i = 0; i < drm.plane_res->count_planes; i++)
		if ((drm.planes[i]->possible_crtcs & (1 << crtc_idx)) &&
		    drm.plane_types[i] == DRM_PLANE_TYPE_OVERLAY) {
			overlay_plane_id = drm.planes[i]->plane_id;
			break;
		}

	igt_require(overlay_plane_id);

	params->crtc_id = crtc_id;
	params->connector_id = connector->connector_id;
	params->mode = mode;
	params->sprite_id = overlay_plane_id;

	params->fb.fb = NULL;
	params->fb.w = mode->hdisplay;
	params->fb.h = mode->vdisplay;

	params->cursor.fb = NULL;
	params->cursor.x = 0;
	params->cursor.y = 0;
	params->cursor.w = 64;
	params->cursor.h = 64;

	params->sprite.fb = NULL;
	params->sprite.x = 0;
	params->sprite.y = 0;
	params->sprite.w = 64;
	params->sprite.h = 64;
}

static bool connector_get_mode(drmModeConnectorPtr c, drmModeModeInfoPtr *mode)
{
	*mode = NULL;

	if (c->connection != DRM_MODE_CONNECTED || !c->count_modes)
		return false;

	if (c->connector_type == DRM_MODE_CONNECTOR_eDP && opt.no_edp)
		return false;

	if (opt.small_modes)
		*mode = get_connector_smallest_mode(c);
	else
		*mode = &c->modes[0];

	 /* On HSW the CRC WA is so awful that it makes you think everything is
	  * bugged. */
	if (IS_HASWELL(intel_get_drm_devid(drm.fd)) &&
	    c->connector_type == DRM_MODE_CONNECTOR_eDP)
		*mode = &std_1024_mode;

	return true;
}

static bool connector_supports_pipe_a(drmModeConnectorPtr connector)
{
	int i;

	for (i = 0; i < connector->count_encoders; i++)
		if (get_encoder(connector->encoders[i])->possible_crtcs & 1)
			return true;

	return false;
}

static bool find_connector(bool edp_only, bool pipe_a, uint32_t forbidden_id,
			   drmModeConnectorPtr *ret_connector,
			   drmModeModeInfoPtr *ret_mode)
{
	drmModeConnectorPtr c = NULL;
	drmModeModeInfoPtr mode = NULL;
	int i;

	for (i = 0; i < drm.res->count_connectors; i++) {
		c = drm.connectors[i];

		if (edp_only && c->connector_type != DRM_MODE_CONNECTOR_eDP)
			continue;
		if (pipe_a && !connector_supports_pipe_a(c))
			continue;
		if (c->connector_id == forbidden_id)
			continue;
		if (!connector_get_mode(c, &mode))
			continue;

		*ret_connector = c;
		*ret_mode = mode;
		return true;
	}

	return false;
}

static bool init_modeset_cached_params(void)
{
	drmModeConnectorPtr prim_connector = NULL, scnd_connector = NULL;
	drmModeModeInfoPtr prim_mode = NULL, scnd_mode = NULL;
	uint32_t prim_crtc_id, scnd_crtc_id;

	/*
	 * We have this problem where PSR is only present on eDP monitors and
	 * FBC is only present on pipe A for some platforms. So we search first
	 * for the ideal case of eDP supporting pipe A, and try the less optimal
	 * configs later, sacrificing  one of the features.
	 * TODO: refactor the code in a way that allows us to have different
	 * sets of prim/scnd structs for different features.
	 */
	find_connector(true, true, 0, &prim_connector, &prim_mode);
	if (!prim_connector)
		find_connector(true, false, 0, &prim_connector, &prim_mode);
	if (!prim_connector)
		find_connector(false, true, 0, &prim_connector, &prim_mode);
	if (!prim_connector)
		find_connector(false, false, 0, &prim_connector, &prim_mode);

	if (!prim_connector)
		return false;

	find_connector(false, false, prim_connector->connector_id,
		       &scnd_connector, &scnd_mode);

	prim_crtc_id = kmstest_find_crtc_for_connector(drm.fd, drm.res,
						       prim_connector, 0);
	init_mode_params(&prim_mode_params, prim_crtc_id,
			 prim_connector, prim_mode);
	print_mode_info("Primary", &prim_mode_params);

	if (!scnd_connector) {
		scnd_mode_params.connector_id = 0;
		return true;
	}

	igt_require(drm.res->count_crtcs >= 2);
	scnd_crtc_id = kmstest_find_crtc_for_connector(drm.fd, drm.res,
						      scnd_connector,
			1 << kmstest_get_crtc_idx(drm.res, prim_crtc_id));
	init_mode_params(&scnd_mode_params, scnd_crtc_id,
			 scnd_connector, scnd_mode);
	print_mode_info("Secondary", &scnd_mode_params);

	return true;
}

static void create_fb(enum pixel_format pformat, int width, int height,
		      uint64_t tiling, int plane, struct igt_fb *fb)
{
	uint32_t format;
	unsigned int size, stride;
	int bpp;
	uint64_t tiling_for_size;

	switch (pformat) {
	case FORMAT_RGB888:
		if (plane == PLANE_CUR)
			format = DRM_FORMAT_ARGB8888;
		else
			format = DRM_FORMAT_XRGB8888;
		break;
	case FORMAT_RGB565:
		/* Only the primary plane supports 16bpp! */
		if (plane == PLANE_PRI)
			format = DRM_FORMAT_RGB565;
		else if (plane == PLANE_CUR)
			format = DRM_FORMAT_ARGB8888;
		else
			format = DRM_FORMAT_XRGB8888;
		break;
	case FORMAT_RGB101010:
		if (plane == PLANE_PRI)
			format = DRM_FORMAT_XRGB2101010;
		else if (plane == PLANE_CUR)
			format = DRM_FORMAT_ARGB8888;
		else
			format = DRM_FORMAT_XRGB8888;
		break;
	default:
		igt_assert(false);
	}

	/* We want all frontbuffers with the same width/height/format to have
	 * the same size regardless of tiling since we want to properly exercise
	 * the Kernel's specific tiling-checking code paths without accidentally
	 * hitting size-checking ones first. */
	bpp = igt_drm_format_to_bpp(format);
	if (plane == PLANE_CUR)
		tiling_for_size = LOCAL_DRM_FORMAT_MOD_NONE;
	else
		tiling_for_size = LOCAL_I915_FORMAT_MOD_X_TILED;

	igt_calc_fb_size(drm.fd, width, height, bpp, tiling_for_size, &size,
			 &stride);

	igt_create_fb_with_bo_size(drm.fd, width, height, format, tiling, fb,
				   size, stride);
}

static uint32_t pick_color(struct igt_fb *fb, enum color ecolor)
{
	uint32_t color, r, g, b, b2, a;
	bool alpha = false;

	switch (fb->drm_format) {
	case DRM_FORMAT_RGB565:
		a =  0x0;
		r =  0x1F << 11;
		g =  0x3F << 5;
		b =  0x1F;
		b2 = 0x10;
		break;
	case DRM_FORMAT_ARGB8888:
		alpha = true;
	case DRM_FORMAT_XRGB8888:
		a =  0xFF << 24;
		r =  0xFF << 16;
		g =  0xFF << 8;
		b =  0xFF;
		b2 = 0x80;
		break;
	case DRM_FORMAT_ARGB2101010:
		alpha = true;
	case DRM_FORMAT_XRGB2101010:
		a = 0x3 << 30;
		r = 0x3FF << 20;
		g = 0x3FF << 10;
		b = 0x3FF;
		b2 = 0x200;
		break;
	default:
		igt_assert(false);
	}

	switch (ecolor) {
	case COLOR_RED:
		color = r;
		break;
	case COLOR_GREEN:
		color = g;
		break;
	case COLOR_BLUE:
		color = b;
		break;
	case COLOR_MAGENTA:
		color = r | b;
		break;
	case COLOR_CYAN:
		color = g | b;
		break;
	case COLOR_SCND_BG:
		color = b2;
		break;
	default:
		igt_assert(false);
	}

	if (alpha)
		color |= a;

	return color;
}

static void fill_fb(struct igt_fb *fb, enum color ecolor)
{
	igt_draw_fill_fb(drm.fd, fb, pick_color(fb, ecolor));
}

/*
 * This is how the prim, scnd and offscreen FBs should be positioned inside the
 * shared FB. The prim buffer starts at the X and Y offsets defined by
 * opt.shared_fb_{x,y}_offset, then scnd starts at the same X pixel offset,
 * right after prim ends on the Y axis, then the offscreen fb starts after scnd
 * ends. Just like the picture:
 *
 * +-------------------------+
 * | shared fb               |
 * |   +------------------+  |
 * |   | prim             |  |
 * |   |                  |  |
 * |   |                  |  |
 * |   |                  |  |
 * |   +------------------+--+
 * |   | scnd                |
 * |   |                     |
 * |   |                     |
 * |   +---------------+-----+
 * |   | offscreen     |     |
 * |   |               |     |
 * |   |               |     |
 * +---+---------------+-----+
 *
 * We do it vertically instead of the more common horizontal case in order to
 * avoid super huge strides not supported by FBC.
 */
static void create_shared_fb(enum pixel_format format)
{
	int prim_w, prim_h, scnd_w, scnd_h, offs_w, offs_h, big_w, big_h;
	struct screen_fbs *s = &fbs[format];

	prim_w = prim_mode_params.mode->hdisplay;
	prim_h = prim_mode_params.mode->vdisplay;

	if (scnd_mode_params.connector_id) {
		scnd_w = scnd_mode_params.mode->hdisplay;
		scnd_h = scnd_mode_params.mode->vdisplay;
	} else {
		scnd_w = 0;
		scnd_h = 0;
	}
	offs_w = offscreen_fb.w;
	offs_h = offscreen_fb.h;

	big_w = prim_w;
	if (scnd_w > big_w)
		big_w = scnd_w;
	if (offs_w > big_w)
		big_w = offs_w;
	big_w += opt.shared_fb_x_offset;

	big_h = prim_h + scnd_h + offs_h + opt.shared_fb_y_offset;

	create_fb(format, big_w, big_h, LOCAL_I915_FORMAT_MOD_X_TILED,
		  PLANE_PRI, &s->big);
}

static void destroy_fbs(enum pixel_format format)
{
	struct screen_fbs *s = &fbs[format];

	if (!s->initialized)
		return;

	if (scnd_mode_params.connector_id) {
		igt_remove_fb(drm.fd, &s->scnd_pri);
		igt_remove_fb(drm.fd, &s->scnd_cur);
		igt_remove_fb(drm.fd, &s->scnd_spr);
	}
	igt_remove_fb(drm.fd, &s->prim_pri);
	igt_remove_fb(drm.fd, &s->prim_cur);
	igt_remove_fb(drm.fd, &s->prim_spr);
	igt_remove_fb(drm.fd, &s->offscreen);
	igt_remove_fb(drm.fd, &s->big);
}

static void create_fbs(enum pixel_format format)
{
	struct screen_fbs *s = &fbs[format];

	if (s->initialized)
		destroy_fbs(format);

	s->initialized = true;

	create_fb(format, prim_mode_params.mode->hdisplay,
		  prim_mode_params.mode->vdisplay,
		  LOCAL_I915_FORMAT_MOD_X_TILED, PLANE_PRI, &s->prim_pri);
	create_fb(format, prim_mode_params.cursor.w,
		  prim_mode_params.cursor.h, LOCAL_DRM_FORMAT_MOD_NONE,
		  PLANE_CUR, &s->prim_cur);
	create_fb(format, prim_mode_params.sprite.w,
		  prim_mode_params.sprite.h, LOCAL_I915_FORMAT_MOD_X_TILED,
		  PLANE_SPR, &s->prim_spr);

	create_fb(format, offscreen_fb.w, offscreen_fb.h,
		  LOCAL_I915_FORMAT_MOD_X_TILED, PLANE_PRI, &s->offscreen);

	create_shared_fb(format);

	if (!scnd_mode_params.connector_id)
		return;

	create_fb(format, scnd_mode_params.mode->hdisplay,
		  scnd_mode_params.mode->vdisplay,
		  LOCAL_I915_FORMAT_MOD_X_TILED, PLANE_PRI, &s->scnd_pri);
	create_fb(format, scnd_mode_params.cursor.w, scnd_mode_params.cursor.h,
		  LOCAL_DRM_FORMAT_MOD_NONE, PLANE_CUR, &s->scnd_cur);
	create_fb(format, scnd_mode_params.sprite.w, scnd_mode_params.sprite.h,
		  LOCAL_I915_FORMAT_MOD_X_TILED, PLANE_SPR, &s->scnd_spr);
}

static bool set_mode_for_params(struct modeset_params *params)
{
	int rc;

	rc = drmModeSetCrtc(drm.fd, params->crtc_id, params->fb.fb->fb_id,
			    params->fb.x, params->fb.y,
			    &params->connector_id, 1, params->mode);
	return (rc == 0);
}

static bool fbc_is_enabled(void)
{
	char buf[128];

	igt_debugfs_read(drm.fd, "i915_fbc_status", buf);
	return strstr(buf, "FBC enabled\n");
}

static void fbc_print_status(void)
{
	char buf[128];

	igt_debugfs_read(drm.fd, "i915_fbc_status", buf);
	igt_info("FBC status:\n%s\n", buf);
}

static bool psr_is_enabled(void)
{
	char buf[256];

	igt_debugfs_read(drm.fd, "i915_edp_psr_status", buf);
	return strstr(buf, "\nActive: yes\n") &&
	       strstr(buf, "\nHW Enabled & Active bit: yes\n");
}

static void psr_print_status(void)
{
	char buf[256];

	igt_debugfs_read(drm.fd, "i915_edp_psr_status", buf);
	igt_info("PSR status:\n%s\n", buf);
}

static struct timespec fbc_get_last_action(void)
{
	struct timespec ret = { 0, 0 };
	char buf[128];
	char *action;
	ssize_t n_read;

	igt_debugfs_read(drm.fd, "i915_fbc_status", buf);

	action = strstr(buf, "\nLast action:");
	igt_assert(action);

	n_read = sscanf(action, "Last action: %ld.%ld",
			&ret.tv_sec, &ret.tv_nsec);
	igt_assert(n_read == 2);

	return ret;
}

static bool fbc_last_action_changed(void)
{
	struct timespec t_new, t_old;

	t_old = fbc.last_action;
	t_new = fbc_get_last_action();

	fbc.last_action = t_new;

#if 0
	igt_info("old: %ld.%ld\n", t_old.tv_sec, t_old.tv_nsec);
	igt_info("new: %ld.%ld\n", t_new.tv_sec, t_new.tv_nsec);
#endif

	return t_old.tv_sec != t_new.tv_sec ||
	       t_old.tv_nsec != t_new.tv_nsec;
}

static void fbc_update_last_action(void)
{
	if (!fbc.supports_last_action)
		return;

	fbc.last_action = fbc_get_last_action();

#if 0
	igt_info("Last action: %ld.%ld\n",
		 fbc.last_action.tv_sec, fbc.last_action.tv_nsec);
#endif
}

static void fbc_setup_last_action(void)
{
	ssize_t n_read;
	char buf[128];
	char *action;

	igt_debugfs_read(drm.fd, "i915_fbc_status", buf);

	action = strstr(buf, "\nLast action:");
	if (!action) {
		igt_info("FBC last action not supported\n");
		return;
	}

	fbc.supports_last_action = true;

	n_read = sscanf(action, "Last action: %ld.%ld",
			&fbc.last_action.tv_sec, &fbc.last_action.tv_nsec);
	igt_assert(n_read == 2);
}

static bool fbc_is_compressing(void)
{
	char buf[128];

	igt_debugfs_read(drm.fd, "i915_fbc_status", buf);
	return strstr(buf, "\nCompressing: yes\n") != NULL;
}

static bool fbc_wait_for_compression(void)
{
	return igt_wait(fbc_is_compressing(), 2000, 1);
}

static bool fbc_not_enough_stolen(void)
{
	char buf[128];

	igt_debugfs_read(drm.fd, "i915_fbc_status", buf);
	return strstr(buf, "FBC disabled: not enough stolen memory\n");
}

static bool fbc_stride_not_supported(void)
{
	char buf[128];

	igt_debugfs_read(drm.fd, "i915_fbc_status", buf);
	return strstr(buf, "FBC disabled: framebuffer stride not supported\n");
}

static bool fbc_wait_until_enabled(void)
{
	return igt_wait(fbc_is_enabled(), 2000, 1);
}

static bool psr_wait_until_enabled(void)
{
	return igt_wait(psr_is_enabled(), 5000, 1);
}

#define fbc_enable() igt_set_module_param_int("enable_fbc", 1)
#define fbc_disable() igt_set_module_param_int("enable_fbc", 0)
#define psr_enable() igt_set_module_param_int("enable_psr", 1)
#define psr_disable() igt_set_module_param_int("enable_psr", 0)

static void get_sink_crc(sink_crc_t *crc, bool mandatory)
{
	int rc, errno_;

	if (!sink_crc.supported) {
		memcpy(crc, "unsupported!", SINK_CRC_SIZE);
		return;
	}

	lseek(sink_crc.fd, 0, SEEK_SET);

	rc = read(sink_crc.fd, crc->data, SINK_CRC_SIZE);
	errno_ = errno;

	if (rc == -1 && errno_ == ENOTTY) {
		igt_info("Sink CRC not supported: panel doesn't support it\n");
		sink_crc.supported = false;
	} else if (rc == -1 && errno_ == ETIMEDOUT) {
		if (sink_crc.reliable) {
			igt_info("Sink CRC is unreliable on this machine.\n");
			sink_crc.reliable = false;
		}

		if (mandatory)
			igt_skip("Sink CRC is unreliable on this machine.\n");
	} else {
		igt_assert_f(rc != -1, "Unexpected error: %d\n", errno_);
		igt_assert(rc == SINK_CRC_SIZE);
	}
}

static bool sink_crc_equal(sink_crc_t *a, sink_crc_t *b)
{
	return (memcmp(a->data, b->data, SINK_CRC_SIZE) == 0);
}

#define assert_sink_crc_equal(a, b) igt_assert(sink_crc_equal(a, b))

static struct rect pat1_get_rect(struct fb_region *fb, int r)
{
	struct rect rect;

	switch (r) {
	case 0:
		rect.x = 0;
		rect.y = 0;
		rect.w = fb->w / 8;
		rect.h = fb->h / 8;
		rect.color = pick_color(fb->fb, COLOR_GREEN);
		break;
	case 1:
		rect.x = fb->w / 8 * 4;
		rect.y = fb->h / 8 * 4;
		rect.w = fb->w / 8 * 2;
		rect.h = fb->h / 8 * 2;
		rect.color = pick_color(fb->fb, COLOR_RED);
		break;
	case 2:
		rect.x = fb->w / 16 + 1;
		rect.y = fb->h / 16 + 1;
		rect.w = fb->w / 8 + 1;
		rect.h = fb->h / 8 + 1;
		rect.color = pick_color(fb->fb, COLOR_MAGENTA);
		break;
	case 3:
		rect.x = fb->w - 1;
		rect.y = fb->h - 1;
		rect.w = 1;
		rect.h = 1;
		rect.color = pick_color(fb->fb, COLOR_CYAN);
		break;
	default:
		igt_assert(false);
	}

	return rect;
}

static struct rect pat2_get_rect(struct fb_region *fb, int r)
{
	struct rect rect;

	rect.x = 0;
	rect.y = 0;
	rect.w = 64;
	rect.h = 64;

	switch (r) {
	case 0:
		rect.color = pick_color(fb->fb, COLOR_GREEN);
		break;
	case 1:
		rect.x = 31;
		rect.y = 31;
		rect.w = 31;
		rect.h = 31;
		rect.color = pick_color(fb->fb, COLOR_RED);
		break;
	case 2:
		rect.x = 16;
		rect.y = 16;
		rect.w = 32;
		rect.h = 32;
		rect.color = pick_color(fb->fb, COLOR_MAGENTA);
		break;
	case 3:
		rect.color = pick_color(fb->fb, COLOR_CYAN);
		break;
	default:
		igt_assert(false);
	}

	return rect;
}

static struct rect pat3_get_rect(struct fb_region *fb, int r)
{
	struct rect rect;

	rect.w = 64;
	rect.h = 64;
	rect.color = pick_color(fb->fb, COLOR_GREEN);

	switch (r) {
	case 0:
		rect.x = 0;
		rect.y = 0;
		break;
	case 1:
		rect.x = 64;
		rect.y = 64;
		break;
	case 2:
		rect.x = 1;
		rect.y = 1;
		break;
	case 3:
		rect.x = fb->w - 64;
		rect.y = fb->h - 64;
		break;
	case 4:
		rect.x = fb->w / 2 - 32;
		rect.y = fb->h / 2 - 32;
		break;
	default:
		igt_assert(false);
	}

	return rect;
}

static struct rect pat4_get_rect(struct fb_region *fb, int r)
{
	struct rect rect;

	igt_assert_eq(r, 0);

	rect.x = 0;
	rect.y = 0;
	rect.w = fb->w;
	rect.h = fb->h;
	rect.color = pick_color(fb->fb, COLOR_GREEN);

	return rect;
}

static void fb_dirty_ioctl(struct fb_region *fb, struct rect *rect)
{
	int rc;
	drmModeClip clip = {
		.x1 = rect->x,
		.x2 = rect->x + rect->w,
		.y1 = rect->y,
		.y2 = rect->y + rect->h,
	};

	rc = drmModeDirtyFB(drm.fd, fb->fb->fb_id, &clip, 1);

	igt_assert(rc == 0 || rc == -ENOSYS);
}

static void draw_rect(struct draw_pattern_info *pattern, struct fb_region *fb,
		      enum igt_draw_method method, int r)
{
	struct rect rect = pattern->get_rect(fb, r);

	igt_draw_rect_fb(drm.fd, drm.bufmgr, NULL, fb->fb, method,
			 fb->x + rect.x, fb->y + rect.y,
			 rect.w, rect.h, rect.color);

	if (method == IGT_DRAW_MMAP_WC)
		fb_dirty_ioctl(fb, &rect);
}

static void draw_rect_igt_fb(struct draw_pattern_info *pattern,
			     struct igt_fb *fb, enum igt_draw_method method,
			     int r)
{
	struct fb_region region = {
		.fb = fb,
		.x = 0,
		.y = 0,
		.w = fb->width,
		.h = fb->height,
	};

	draw_rect(pattern, &region, method, r);
}

static void fill_fb_region(struct fb_region *region, enum color ecolor)
{
	uint32_t color = pick_color(region->fb, ecolor);

	igt_draw_rect_fb(drm.fd, drm.bufmgr, NULL, region->fb, IGT_DRAW_BLT,
			 region->x, region->y, region->w, region->h,
			 color);
}

static void unset_all_crtcs(void)
{
	int i, rc;

	for (i = 0; i < drm.res->count_crtcs; i++) {
		rc = drmModeSetCrtc(drm.fd, drm.res->crtcs[i], -1, 0, 0, NULL,
				    0, NULL);
		igt_assert_eq(rc, 0);

		rc = drmModeSetCursor(drm.fd, drm.res->crtcs[i], 0, 0, 0);
		igt_assert_eq(rc, 0);
	}

	for (i = 0; i < drm.plane_res->count_planes; i++) {
		rc = drmModeSetPlane(drm.fd, drm.plane_res->planes[i], 0, 0, 0,
				     0, 0, 0, 0, 0, 0, 0, 0);
		igt_assert_eq(rc, 0);
	}
}

static void disable_features(const struct test_mode *t)
{
	if (t->feature == FEATURE_DEFAULT)
		return;

	fbc_disable();
	psr_disable();
}

static void *busy_thread_func(void *data)
{
	while (!busy_thread.stop)
		igt_draw_rect(drm.fd, drm.bufmgr, NULL, busy_thread.handle,
			      busy_thread.size, busy_thread.stride,
			      IGT_DRAW_BLT, 0, 0, busy_thread.width,
			      busy_thread.height, busy_thread.color,
			      busy_thread.bpp);

	pthread_exit(0);
}

static void start_busy_thread(struct igt_fb *fb)
{
	int rc;

	igt_assert(busy_thread.stop == true);
	busy_thread.stop = false;
	busy_thread.handle = fb->gem_handle;
	busy_thread.size = fb->size;
	busy_thread.stride = fb->stride;
	busy_thread.width = fb->width;
	busy_thread.height = fb->height;
	busy_thread.color = pick_color(fb, COLOR_PRIM_BG);
	busy_thread.bpp = igt_drm_format_to_bpp(fb->drm_format);

	rc = pthread_create(&busy_thread.thread, NULL, busy_thread_func, NULL);
	igt_assert_eq(rc, 0);
}

static void stop_busy_thread(void)
{
	if (!busy_thread.stop) {
		busy_thread.stop = true;
		igt_assert(pthread_join(busy_thread.thread, NULL) == 0);
	}
}

static void print_crc(const char *str, struct both_crcs *crc)
{
	int i;
	char *pipe_str;

	pipe_str = igt_crc_to_string(&crc->pipe);

	igt_debug("%s pipe:[%s] sink:[", str, pipe_str);
	for (i = 0; i < SINK_CRC_SIZE; i++)
		igt_debug("%c", crc->sink.data[i]);
	igt_debug("]\n");

	free(pipe_str);
}

static void collect_crcs(struct both_crcs *crcs, bool mandatory_sink_crc)
{
	igt_pipe_crc_collect_crc(pipe_crc, &crcs->pipe);
	get_sink_crc(&crcs->sink, mandatory_sink_crc);
}

static void init_blue_crc(enum pixel_format format, bool mandatory_sink_crc)
{
	struct igt_fb blue;
	int rc;

	if (blue_crcs[format].initialized)
		return;

	create_fb(format, prim_mode_params.mode->hdisplay,
		  prim_mode_params.mode->vdisplay,
		  LOCAL_I915_FORMAT_MOD_X_TILED, PLANE_PRI, &blue);

	fill_fb(&blue, COLOR_PRIM_BG);

	rc = drmModeSetCrtc(drm.fd, prim_mode_params.crtc_id,
			    blue.fb_id, 0, 0, &prim_mode_params.connector_id, 1,
			    prim_mode_params.mode);
	igt_assert_eq(rc, 0);
	collect_crcs(&blue_crcs[format].crc, mandatory_sink_crc);

	print_crc("Blue CRC:  ", &blue_crcs[format].crc);

	unset_all_crtcs();

	igt_remove_fb(drm.fd, &blue);

	blue_crcs[format].initialized = true;
}

static void init_crcs(enum pixel_format format,
		      struct draw_pattern_info *pattern,
		      bool mandatory_sink_crc)
{
	int r, r_, rc;
	struct igt_fb tmp_fbs[pattern->n_rects];

	if (pattern->initialized[format])
		return;

	pattern->crcs[format] = calloc(pattern->n_rects,
				       sizeof(*(pattern->crcs[format])));

	for (r = 0; r < pattern->n_rects; r++)
		create_fb(format, prim_mode_params.mode->hdisplay,
			  prim_mode_params.mode->vdisplay,
			  LOCAL_I915_FORMAT_MOD_X_TILED, PLANE_PRI, &tmp_fbs[r]);

	for (r = 0; r < pattern->n_rects; r++)
		fill_fb(&tmp_fbs[r], COLOR_PRIM_BG);

	if (pattern->frames_stack) {
		for (r = 0; r < pattern->n_rects; r++)
			for (r_ = 0; r_ <= r; r_++)
				draw_rect_igt_fb(pattern, &tmp_fbs[r],
						 IGT_DRAW_PWRITE, r_);
	} else {
		for (r = 0; r < pattern->n_rects; r++)
			draw_rect_igt_fb(pattern, &tmp_fbs[r], IGT_DRAW_PWRITE,
					 r);
	}

	for (r = 0; r < pattern->n_rects; r++) {
		rc = drmModeSetCrtc(drm.fd, prim_mode_params.crtc_id,
				   tmp_fbs[r].fb_id, 0, 0,
				   &prim_mode_params.connector_id, 1,
				   prim_mode_params.mode);
		igt_assert_eq(rc, 0);
		collect_crcs(&pattern->crcs[format][r], mandatory_sink_crc);
	}

	for (r = 0; r < pattern->n_rects; r++) {
		igt_debug("Rect %d CRC:", r);
		print_crc("", &pattern->crcs[format][r]);
	}

	unset_all_crtcs();

	for (r = 0; r < pattern->n_rects; r++)
		igt_remove_fb(drm.fd, &tmp_fbs[r]);

	pattern->initialized[format] = true;
}

static uint64_t get_plane_type(uint32_t plane_id)
{
	bool found;
	uint64_t prop_value;
	drmModePropertyPtr prop;

	found = kmstest_get_property(drm.fd, plane_id, DRM_MODE_OBJECT_PLANE,
				     "type", NULL, &prop_value, &prop);
	igt_assert(found);
	igt_assert(prop->flags & DRM_MODE_PROP_ENUM);
	igt_assert(prop_value < prop->count_enums);

	drmModeFreeProperty(prop);
	return prop_value;
}

static void setup_drm(void)
{
	int i, rc;

	drm.fd = drm_open_driver_master(DRIVER_INTEL);

	drm.res = drmModeGetResources(drm.fd);
	igt_assert(drm.res->count_connectors <= MAX_CONNECTORS);
	igt_assert(drm.res->count_encoders <= MAX_ENCODERS);

	for (i = 0; i < drm.res->count_connectors; i++)
		drm.connectors[i] = drmModeGetConnectorCurrent(drm.fd,
						drm.res->connectors[i]);
	for (i = 0; i < drm.res->count_encoders; i++)
		drm.encoders[i] = drmModeGetEncoder(drm.fd,
						    drm.res->encoders[i]);

	rc = drmSetClientCap(drm.fd, DRM_CLIENT_CAP_UNIVERSAL_PLANES, 1);
	igt_require(rc == 0);

	drm.plane_res = drmModeGetPlaneResources(drm.fd);
	igt_assert(drm.plane_res->count_planes <= MAX_PLANES);

	for (i = 0; i < drm.plane_res->count_planes; i++) {
		drm.planes[i] = drmModeGetPlane(drm.fd, drm.plane_res->planes[i]);
		drm.plane_types[i] = get_plane_type(drm.plane_res->planes[i]);
	}

	drm.bufmgr = drm_intel_bufmgr_gem_init(drm.fd, 4096);
	igt_assert(drm.bufmgr);
	drm_intel_bufmgr_gem_enable_reuse(drm.bufmgr);
}

static void teardown_drm(void)
{
	int i;

	drm_intel_bufmgr_destroy(drm.bufmgr);

	for (i = 0; i < drm.plane_res->count_planes; i++)
		drmModeFreePlane(drm.planes[i]);
	drmModeFreePlaneResources(drm.plane_res);

	for (i = 0; i < drm.res->count_encoders; i++)
		drmModeFreeEncoder(drm.encoders[i]);
	for (i = 0; i < drm.res->count_connectors; i++)
		drmModeFreeConnector(drm.connectors[i]);

	drmModeFreeResources(drm.res);
	close(drm.fd);
}

static void setup_modeset(void)
{
	igt_require(init_modeset_cached_params());
	offscreen_fb.fb = NULL;
	offscreen_fb.w = 1024;
	offscreen_fb.h = 1024;
	create_fbs(FORMAT_DEFAULT);
	kmstest_set_vt_graphics_mode();
}

static void teardown_modeset(void)
{
	enum pixel_format f;

	for (f = 0; f < FORMAT_COUNT; f++)
		destroy_fbs(f);
}

static void setup_sink_crc(void)
{
	sink_crc_t crc;
	drmModeConnectorPtr c;

	c = get_connector(prim_mode_params.connector_id);
	if (c->connector_type != DRM_MODE_CONNECTOR_eDP) {
		igt_info("Sink CRC not supported: primary screen is not eDP\n");
		sink_crc.supported = false;
		return;
	}

	/* We need to make sure there's a mode set on the eDP screen and it's
	 * not on DPMS state, otherwise we fall into the "Unexpected sink CRC
	 * error" case. */
	prim_mode_params.fb.fb = &fbs[FORMAT_DEFAULT].prim_pri;
	prim_mode_params.fb.x = prim_mode_params.fb.y = 0;
	fill_fb_region(&prim_mode_params.fb, COLOR_PRIM_BG);
	set_mode_for_params(&prim_mode_params);

	sink_crc.fd = igt_debugfs_open(drm.fd, "i915_sink_crc_eDP1", O_RDONLY);
	igt_assert_lte(0, sink_crc.fd);

	/* Do a first read to try to detect if it's supported. */
	get_sink_crc(&crc, false);
}

static void setup_crcs(void)
{
	enum pixel_format f;
	int crtc_idx = kmstest_get_crtc_idx(drm.res, prim_mode_params.crtc_id);

	pipe_crc = igt_pipe_crc_new(drm.fd, crtc_idx, INTEL_PIPE_CRC_SOURCE_AUTO);

	setup_sink_crc();

	for (f = 0; f < FORMAT_COUNT; f++)
		blue_crcs[f].initialized = false;

	pattern1.frames_stack = true;
	pattern1.n_rects = 4;
	pattern1.get_rect = pat1_get_rect;
	for (f = 0; f < FORMAT_COUNT; f++) {
		pattern1.initialized[f] = false;
		pattern1.crcs[f] = NULL;
	}

	pattern2.frames_stack = true;
	pattern2.n_rects = 4;
	pattern2.get_rect = pat2_get_rect;
	for (f = 0; f < FORMAT_COUNT; f++) {
		pattern2.initialized[f] = false;
		pattern2.crcs[f] = NULL;
	}

	pattern3.frames_stack = false;
	pattern3.n_rects = 5;
	pattern3.get_rect = pat3_get_rect;
	for (f = 0; f < FORMAT_COUNT; f++) {
		pattern3.initialized[f] = false;
		pattern3.crcs[f] = NULL;
	}

	pattern4.frames_stack = false;
	pattern4.n_rects = 1;
	pattern4.get_rect = pat4_get_rect;
	for (f = 0; f < FORMAT_COUNT; f++) {
		pattern4.initialized[f] = false;
		pattern4.crcs[f] = NULL;
	}
}

static void teardown_crcs(void)
{
	enum pixel_format f;

	for (f = 0; f < FORMAT_COUNT; f++) {
		if (pattern1.crcs[f])
			free(pattern1.crcs[f]);
		if (pattern2.crcs[f])
			free(pattern2.crcs[f]);
		if (pattern3.crcs[f])
			free(pattern3.crcs[f]);
		if (pattern4.crcs[f])
			free(pattern4.crcs[f]);
	}

	if (sink_crc.fd != -1)
		close(sink_crc.fd);

	igt_pipe_crc_free(pipe_crc);
}

static bool fbc_supported_on_chipset(void)
{
	char buf[128];

	igt_debugfs_read(drm.fd, "i915_fbc_status", buf);
	return !strstr(buf, "FBC unsupported on this chipset\n");
}

static void setup_fbc(void)
{
	drmModeConnectorPtr c = get_connector(prim_mode_params.connector_id);

	if (!fbc_supported_on_chipset()) {
		igt_info("Can't test FBC: not supported on this chipset\n");
		return;
	}

	/*
	 * While some platforms do allow FBC on pipes B/C, this test suite
	 * is not prepared for that yet.
	 * TODO: solve this.
	 */
	if (!connector_supports_pipe_a(c)) {
		igt_info("Can't test FBC: primary connector doesn't support "
			 "pipe A\n");
		return;
	}
	fbc.can_test = true;

	fbc_setup_last_action();
}

static void teardown_fbc(void)
{
}

static bool psr_sink_has_support(void)
{
	char buf[256];

	igt_debugfs_read(drm.fd, "i915_edp_psr_status", buf);
	return strstr(buf, "Sink_Support: yes\n");
}

static void setup_psr(void)
{
	if (get_connector(prim_mode_params.connector_id)->connector_type !=
	    DRM_MODE_CONNECTOR_eDP) {
		igt_info("Can't test PSR: no usable eDP screen.\n");
		return;
	}

	if (!psr_sink_has_support()) {
		igt_info("Can't test PSR: not supported by sink.\n");
		return;
	}
	psr.can_test = true;
}

static void teardown_psr(void)
{
}

static void setup_environment(void)
{
	setup_drm();
	setup_modeset();

	setup_fbc();
	setup_psr();

	setup_crcs();
}

static void teardown_environment(void)
{
	stop_busy_thread();

	teardown_crcs();
	teardown_psr();
	teardown_fbc();
	teardown_modeset();
	teardown_drm();
}

static void wait_user(int step, const char *msg)
{
	if (opt.step < step)
		return;

	igt_info("%s Press enter...\n", msg);
	while (getchar() != '\n')
		;
}

static struct modeset_params *pick_params(const struct test_mode *t)
{
	switch (t->screen) {
	case SCREEN_PRIM:
		return &prim_mode_params;
	case SCREEN_SCND:
		return &scnd_mode_params;
	case SCREEN_OFFSCREEN:
		return NULL;
	default:
		igt_assert(false);
	}
}

static struct fb_region *pick_target(const struct test_mode *t,
				     struct modeset_params *params)
{
	if (!params)
		return &offscreen_fb;

	switch (t->plane) {
	case PLANE_PRI:
		return &params->fb;
	case PLANE_CUR:
		return &params->cursor;
	case PLANE_SPR:
		return &params->sprite;
	default:
		igt_assert(false);
	}
}

static void do_flush(const struct test_mode *t)
{
	struct modeset_params *params = pick_params(t);
	struct fb_region *target = pick_target(t, params);

	gem_set_domain(drm.fd, target->fb->gem_handle, I915_GEM_DOMAIN_GTT, 0);
}

#define DONT_ASSERT_CRC			(1 << 0)
#define DONT_ASSERT_FEATURE_STATUS	(1 << 1)

#define FBC_ASSERT_FLAGS		(0xF << 2)
#define ASSERT_FBC_ENABLED		(1 << 2)
#define ASSERT_FBC_DISABLED		(1 << 3)
#define ASSERT_LAST_ACTION_CHANGED	(1 << 4)
#define ASSERT_NO_ACTION_CHANGE		(1 << 5)

#define PSR_ASSERT_FLAGS		(3 << 6)
#define ASSERT_PSR_ENABLED		(1 << 6)
#define ASSERT_PSR_DISABLED		(1 << 7)

static int adjust_assertion_flags(const struct test_mode *t, int flags)
{
	if (!(flags & DONT_ASSERT_FEATURE_STATUS)) {
		if (!(flags & ASSERT_FBC_DISABLED))
			flags |= ASSERT_FBC_ENABLED;
		if (!(flags & ASSERT_PSR_DISABLED))
			flags |= ASSERT_PSR_ENABLED;
	}

	if ((t->feature & FEATURE_FBC) == 0)
		flags &= ~FBC_ASSERT_FLAGS;
	if ((t->feature & FEATURE_PSR) == 0)
		flags &= ~PSR_ASSERT_FLAGS;

	return flags;
}

#define do_crc_assertions(flags, mandatory_sink_crc) do {		\
	int flags__ = (flags);						\
	struct both_crcs crc_;						\
									\
	if (!opt.check_crc || (flags__ & DONT_ASSERT_CRC))		\
		break;							\
									\
	collect_crcs(&crc_, mandatory_sink_crc);			\
	print_crc("Calculated CRC:", &crc_);				\
									\
	igt_assert(wanted_crc);						\
	igt_assert_crc_equal(&crc_.pipe, &wanted_crc->pipe);		\
	if (mandatory_sink_crc)						\
		assert_sink_crc_equal(&crc_.sink, &wanted_crc->sink);	\
	else if (sink_crc.reliable &&					\
		 !sink_crc_equal(&crc_.sink, &wanted_crc->sink))	\
		igt_info("Sink CRC differ, but not required\n"); 	\
} while (0)

#define do_status_assertions(flags_) do {				\
	if (!opt.check_status) {					\
		/* Make sure we settle before continuing. */		\
		sleep(1);						\
		break;							\
	}								\
									\
	if (flags_ & ASSERT_FBC_ENABLED) {				\
		igt_require(!fbc_not_enough_stolen());			\
		igt_require(!fbc_stride_not_supported());		\
		if (!fbc_wait_until_enabled()) {			\
			fbc_print_status();				\
			igt_assert_f(false, "FBC disabled\n");		\
		}							\
									\
		if (opt.fbc_check_compression)				\
			igt_assert(fbc_wait_for_compression());		\
	} else if (flags_ & ASSERT_FBC_DISABLED) {			\
		igt_assert(!fbc_wait_until_enabled());			\
	}								\
									\
	if (flags_ & ASSERT_PSR_ENABLED) {				\
		if (!psr_wait_until_enabled()) {			\
			psr_print_status();				\
			igt_assert_f(false, "PSR disabled\n");		\
		}							\
	} else if (flags_ & ASSERT_PSR_DISABLED) {			\
		igt_assert(!psr_wait_until_enabled());			\
	}								\
} while (0)

#define do_assertions(flags) do {					\
	int flags_ = adjust_assertion_flags(t, (flags));		\
	bool mandatory_sink_crc = t->feature & FEATURE_PSR;		\
									\
	wait_user(2, "Paused before assertions.");			\
									\
	/* Check the CRC to make sure the drawing operations work	\
	 * immediately, independently of the features being enabled. */	\
	do_crc_assertions(flags_, mandatory_sink_crc);			\
									\
	/* Now we can flush things to make the test faster. */		\
	do_flush(t);							\
									\
	do_status_assertions(flags_);					\
									\
	/* Check CRC again to make sure the compressed screen is ok,	\
	 * except if we're not drawing on the primary screen. On this	\
	 * case, the first check should be enough and a new CRC check	\
	 * would only delay the test suite while adding no value to the	\
	 * test suite. */						\
	if (t->screen == SCREEN_PRIM)					\
		do_crc_assertions(flags_, mandatory_sink_crc);		\
									\
	if (fbc.supports_last_action && opt.fbc_check_last_action) {	\
		if (flags_ & ASSERT_LAST_ACTION_CHANGED)		\
			igt_assert(fbc_last_action_changed());		\
		else if (flags_ & ASSERT_NO_ACTION_CHANGE)		\
			igt_assert(!fbc_last_action_changed());		\
	}								\
									\
	wait_user(1, "Paused after assertions.");			\
} while (0)

static void enable_prim_screen_and_wait(const struct test_mode *t)
{
	fill_fb_region(&prim_mode_params.fb, COLOR_PRIM_BG);
	set_mode_for_params(&prim_mode_params);

	wanted_crc = &blue_crcs[t->format].crc;
	fbc_update_last_action();

	do_assertions(ASSERT_NO_ACTION_CHANGE);
}

static void enable_scnd_screen_and_wait(const struct test_mode *t)
{
	fill_fb_region(&scnd_mode_params.fb, COLOR_SCND_BG);
	set_mode_for_params(&scnd_mode_params);

	do_assertions(ASSERT_NO_ACTION_CHANGE);
}

static void set_cursor_for_test(const struct test_mode *t,
				struct modeset_params *params)
{
	int rc;

	fill_fb_region(&params->cursor, COLOR_PRIM_BG);

	rc = drmModeMoveCursor(drm.fd, params->crtc_id, 0, 0);
	igt_assert_eq(rc, 0);

	rc = drmModeSetCursor(drm.fd, params->crtc_id,
			      params->cursor.fb->gem_handle,
			      params->cursor.w,
			      params->cursor.h);
	igt_assert_eq(rc, 0);

	do_assertions(ASSERT_NO_ACTION_CHANGE);
}

static void set_sprite_for_test(const struct test_mode *t,
				struct modeset_params *params)
{
	int rc;

	fill_fb_region(&params->sprite, COLOR_PRIM_BG);

	rc = drmModeSetPlane(drm.fd, params->sprite_id, params->crtc_id,
			     params->sprite.fb->fb_id, 0, 0, 0,
			     params->sprite.w, params->sprite.h,
			     0, 0, params->sprite.w << 16,
			     params->sprite.h << 16);
	igt_assert_eq(rc, 0);

	do_assertions(ASSERT_NO_ACTION_CHANGE);
}

static void enable_features_for_test(const struct test_mode *t)
{
	if (t->feature == FEATURE_DEFAULT)
		return;

	if (t->feature & FEATURE_FBC)
		fbc_enable();
	if (t->feature & FEATURE_PSR)
		psr_enable();
}

static void check_test_requirements(const struct test_mode *t)
{
	if (t->pipes == PIPE_DUAL)
		igt_require_f(scnd_mode_params.connector_id,
			    "Can't test dual pipes with the current outputs\n");

	if (t->feature & FEATURE_FBC)
		igt_require_f(fbc.can_test,
			      "Can't test FBC with this chipset\n");

	if (t->feature & FEATURE_PSR) {
		igt_require_f(psr.can_test,
			      "Can't test PSR with the current outputs\n");
		igt_require_f(sink_crc.supported,
			      "Can't test PSR without sink CRCs\n");
	}

	if (opt.only_pipes != PIPE_COUNT)
		igt_require(t->pipes == opt.only_pipes);
}

static void set_crtc_fbs(const struct test_mode *t)
{
	struct screen_fbs *s = &fbs[t->format];

	create_fbs(t->format);

	switch (t->fbs) {
	case FBS_INDIVIDUAL:
		prim_mode_params.fb.fb = &s->prim_pri;
		scnd_mode_params.fb.fb = &s->scnd_pri;
		offscreen_fb.fb = &s->offscreen;

		prim_mode_params.fb.x = 0;
		scnd_mode_params.fb.x = 0;
		offscreen_fb.x = 0;

		prim_mode_params.fb.y = 0;
		scnd_mode_params.fb.y = 0;
		offscreen_fb.y = 0;
		break;
	case FBS_SHARED:
		/* Please see the comment at the top of create_shared_fb(). */
		prim_mode_params.fb.fb = &s->big;
		scnd_mode_params.fb.fb = &s->big;
		offscreen_fb.fb = &s->big;

		prim_mode_params.fb.x = opt.shared_fb_x_offset;
		scnd_mode_params.fb.x = opt.shared_fb_x_offset;
		offscreen_fb.x = opt.shared_fb_x_offset;

		prim_mode_params.fb.y = opt.shared_fb_y_offset;
		scnd_mode_params.fb.y = prim_mode_params.fb.y +
					prim_mode_params.fb.h;
		offscreen_fb.y = scnd_mode_params.fb.y + scnd_mode_params.fb.h;
		break;
	default:
		igt_assert(false);
	}

	prim_mode_params.cursor.fb = &s->prim_cur;
	prim_mode_params.sprite.fb = &s->prim_spr;
	scnd_mode_params.cursor.fb = &s->scnd_cur;
	scnd_mode_params.sprite.fb = &s->scnd_spr;
}

static void prepare_subtest_data(const struct test_mode *t,
				 struct draw_pattern_info *pattern)
{
	check_test_requirements(t);

	stop_busy_thread();

	disable_features(t);
	set_crtc_fbs(t);

	if (t->screen == SCREEN_OFFSCREEN)
		fill_fb_region(&offscreen_fb, COLOR_OFFSCREEN_BG);

	unset_all_crtcs();

	init_blue_crc(t->format, t->feature & FEATURE_PSR);
	if (pattern)
		init_crcs(t->format, pattern, t->feature & FEATURE_PSR);

	enable_features_for_test(t);
}

static void prepare_subtest_screens(const struct test_mode *t)
{
	enable_prim_screen_and_wait(t);
	if (t->screen == SCREEN_PRIM) {
		if (t->plane == PLANE_CUR)
			set_cursor_for_test(t, &prim_mode_params);
		if (t->plane == PLANE_SPR)
			set_sprite_for_test(t, &prim_mode_params);
	}

	if (t->pipes == PIPE_SINGLE)
		return;

	enable_scnd_screen_and_wait(t);
	if (t->screen == SCREEN_SCND) {
		if (t->plane == PLANE_CUR)
			set_cursor_for_test(t, &scnd_mode_params);
		if (t->plane == PLANE_SPR)
			set_sprite_for_test(t, &scnd_mode_params);
	}
}

static void prepare_subtest(const struct test_mode *t,
			    struct draw_pattern_info *pattern)
{
	prepare_subtest_data(t, pattern);
	prepare_subtest_screens(t);
}

/*
 * rte - the basic sanity test
 *
 * METHOD
 *   Just disable all screens, assert everything is disabled, then enable all
 *   screens - including primary, cursor and sprite planes - and assert that
 *   the tested feature is enabled.
 *
 * EXPECTED RESULTS
 *   Blue screens and t->feature enabled.
 *
 * FAILURES
 *   A failure here means that every other subtest will probably fail too. It
 *   probably means that the Kernel is just not enabling the feature we want.
 */
static void rte_subtest(const struct test_mode *t)
{
	prepare_subtest_data(t, NULL);

	unset_all_crtcs();
	do_assertions(ASSERT_FBC_DISABLED | ASSERT_PSR_DISABLED |
		      DONT_ASSERT_CRC);

	enable_prim_screen_and_wait(t);
	set_cursor_for_test(t, &prim_mode_params);
	set_sprite_for_test(t, &prim_mode_params);

	if (t->pipes == PIPE_SINGLE)
		return;

	enable_scnd_screen_and_wait(t);
	set_cursor_for_test(t, &scnd_mode_params);
	set_sprite_for_test(t, &scnd_mode_params);
}

static void update_wanted_crc(const struct test_mode *t, struct both_crcs *crc)
{
	if (t->screen == SCREEN_PRIM)
		wanted_crc = crc;
}

static bool op_disables_psr(const struct test_mode *t,
			    enum igt_draw_method method)
{
	if (method != IGT_DRAW_MMAP_GTT)
		return false;
	if (t->screen == SCREEN_PRIM)
		return true;
	/* On FBS_SHARED, even if the target is not the PSR screen
	 * (SCREEN_PRIM), all primary planes share the same frontbuffer, so a
	 * write to the second screen primary plane - or offscreen plane - will
	 * touch the framebuffer that's also used by the primary screen. */
	if (t->fbs == FBS_SHARED && t->plane == PLANE_PRI)
		return true;

	return false;
}

/*
 * draw - draw a set of rectangles on the screen using the provided method
 *
 * METHOD
 *   Just set the screens as appropriate and then start drawing a series of
 *   rectangles on the target screen. The important guy here is the drawing
 *   method used.
 *
 * EXPECTED RESULTS
 *   The feature either stays enabled or gets reenabled after the oprations. You
 *   will also see the rectangles on the target screen.
 *
 * FAILURES
 *   A failure here indicates a problem somewhere between the Kernel's
 *   frontbuffer tracking infrastructure or the feature itself. You need to pay
 *   attention to which drawing method is being used.
 */
static void draw_subtest(const struct test_mode *t)
{
	int r;
	int assertions = 0;
	struct draw_pattern_info *pattern;
	struct modeset_params *params = pick_params(t);
	struct fb_region *target;

	switch (t->screen) {
	case SCREEN_PRIM:
		if (t->method != IGT_DRAW_MMAP_GTT && t->plane == PLANE_PRI)
			assertions |= ASSERT_LAST_ACTION_CHANGED;
		else
			assertions |= ASSERT_NO_ACTION_CHANGE;
		break;
	case SCREEN_SCND:
	case SCREEN_OFFSCREEN:
		assertions |= ASSERT_NO_ACTION_CHANGE;
		break;
	default:
		igt_assert(false);
	}

	switch (t->plane) {
	case PLANE_PRI:
		pattern = &pattern1;
		break;
	case PLANE_CUR:
	case PLANE_SPR:
		pattern = &pattern2;
		break;
	default:
		igt_assert(false);
	}

	if (op_disables_psr(t, t->method))
		assertions |= ASSERT_PSR_DISABLED;

	prepare_subtest(t, pattern);
	target = pick_target(t, params);

	for (r = 0; r < pattern->n_rects; r++) {
		igt_debug("Drawing rect %d\n", r);
		draw_rect(pattern, target, t->method, r);
		update_wanted_crc(t, &pattern->crcs[t->format][r]);
		do_assertions(assertions);
	}
}

/*
 * multidraw - draw a set of rectangles on the screen using alternated drawing
 *             methods
 *
 * METHOD
 *   This is just like the draw subtest, but now we keep alternating between two
 *   drawing methods. Each time we run multidraw_subtest we will test all the
 *   possible pairs of drawing methods.
 *
 * EXPECTED RESULTS
 *   The same as the draw subtest.
 *
 * FAILURES
 *   If you get a failure here, first you need to check whether you also get
 *   failures on the individual draw subtests. If yes, then go fix every single
 *   draw subtest first. If all the draw subtests pass but this one fails, then
 *   you have to study how one drawing method is stopping the other from
 *   properly working.
 */
static void multidraw_subtest(const struct test_mode *t)
{
	int r;
	int assertions = 0;
	struct draw_pattern_info *pattern;
	struct modeset_params *params = pick_params(t);
	struct fb_region *target;
	enum igt_draw_method m1, m2, used_method;
	bool wc_used = false;

	switch (t->plane) {
	case PLANE_PRI:
		pattern = &pattern1;
		break;
	case PLANE_CUR:
	case PLANE_SPR:
		pattern = &pattern2;
		break;
	default:
		igt_assert(false);
	}

	prepare_subtest(t, pattern);
	target = pick_target(t, params);

	for (m1 = 0; m1 < IGT_DRAW_METHOD_COUNT; m1++) {
		for (m2 = m1 + 1; m2 < IGT_DRAW_METHOD_COUNT; m2++) {

			igt_debug("Methods %s and %s\n",
				  igt_draw_get_method_name(m1),
				  igt_draw_get_method_name(m2));
			for (r = 0; r < pattern->n_rects; r++) {
				used_method = (r % 2 == 0) ? m1 : m2;

				igt_debug("Used method %s\n",
					igt_draw_get_method_name(used_method));

				draw_rect(pattern, target, used_method, r);

				if (used_method == IGT_DRAW_MMAP_WC)
					wc_used = true;

				if (used_method == IGT_DRAW_MMAP_GTT &&
				    wc_used) {
					struct rect rect =
						pattern->get_rect(target, r);
					fb_dirty_ioctl(target, &rect);
				}

				update_wanted_crc(t,
						  &pattern->crcs[t->format][r]);

				assertions = used_method != IGT_DRAW_MMAP_GTT ?
					     ASSERT_LAST_ACTION_CHANGED :
					     ASSERT_NO_ACTION_CHANGE;
				if (op_disables_psr(t, used_method))
					assertions |= ASSERT_PSR_DISABLED;

				do_assertions(assertions);
			}

			fill_fb_region(target, COLOR_PRIM_BG);

			update_wanted_crc(t, &blue_crcs[t->format].crc);
			do_assertions(ASSERT_NO_ACTION_CHANGE);
		}
	}
}

static bool format_is_valid(int feature_flags,
			    enum pixel_format format)
{
	int devid = intel_get_drm_devid(drm.fd);

	if (!(feature_flags & FEATURE_FBC))
		return true;

	switch (format) {
	case FORMAT_RGB888:
		return true;
	case FORMAT_RGB565:
		if (IS_GEN2(devid) || IS_G4X(devid))
			return false;
		return true;
	case FORMAT_RGB101010:
		return false;
	default:
		igt_assert(false);
	}
}

/*
 * badformat - test pixel formats that are not supported by at least one feature
 *
 * METHOD
 *   We just do a modeset on a buffer with the given pixel format and check the
 *   status of the relevant features.
 *
 * EXPECTED RESULTS
 *   No assertion failures :)
 *
 * FAILURES
 *   If you get a feature enabled/disabled assertion failure, then you should
 *   probably check the Kernel code for the feature that checks the pixel
 *   formats. If you get a CRC assertion failure, then you should use the
 *   appropriate command line arguments that will allow you to look at the
 *   screen, then judge what to do based on what you see.
 */
static void badformat_subtest(const struct test_mode *t)
{
	bool fbc_valid = format_is_valid(FEATURE_FBC, t->format);
	bool psr_valid = format_is_valid(FEATURE_PSR, t->format);
	int assertions = ASSERT_NO_ACTION_CHANGE;

	prepare_subtest_data(t, NULL);

	fill_fb_region(&prim_mode_params.fb, COLOR_PRIM_BG);
	set_mode_for_params(&prim_mode_params);

	wanted_crc = &blue_crcs[t->format].crc;

	if (!fbc_valid)
		assertions |= ASSERT_FBC_DISABLED;
	if (!psr_valid)
		assertions |= ASSERT_PSR_DISABLED;
	do_assertions(assertions);
}

/*
 * format_draw - test pixel formats that are not FORMAT_DEFAULT
 *
 * METHOD
 *   The real subtest to be executed depends on whether the pixel format is
 *   supported by the features being tested or not. Check the documentation of
 *   each subtest.
 *
 * EXPECTED RESULTS
 *   See the documentation for each subtest.
 *
 * FAILURES
 *   See the documentation for each subtest.
 */
static void format_draw_subtest(const struct test_mode *t)
{
	if (format_is_valid(t->feature, t->format))
		draw_subtest(t);
	else
		badformat_subtest(t);
}

/*
 * slow_draw - sleep a little bit between drawing operations
 *
 * METHOD
 *   This test is basically the same as the draw subtest, except that we sleep a
 *   little bit after each drawing operation. The goal is to detect problems
 *   that can happen in case a drawing operation is done while the machine is in
 *   some deep sleep states.
 *
 * EXPECTED RESULTS
 *   The pattern appears on the screen as expected.
 *
 * FAILURES
 *   I've seen this happen in a SKL machine and still haven't investigated it.
 *   My guess would be that preventing deep sleep states fixes the problem.
 */
static void slow_draw_subtest(const struct test_mode *t)
{
	int r;
	struct draw_pattern_info *pattern = &pattern1;
	struct modeset_params *params = pick_params(t);
	struct fb_region *target;

	prepare_subtest(t, pattern);
	sleep(2);
	target = pick_target(t, params);

	for (r = 0; r < pattern->n_rects; r++) {
		sleep(2);
		draw_rect(pattern, target, t->method, r);
		sleep(2);

		update_wanted_crc(t, &pattern->crcs[t->format][r]);
		do_assertions(0);
	}
}

static void flip_handler(int fd, unsigned int sequence, unsigned int tv_sec,
			 unsigned int tv_usec, void *data)
{
	igt_debug("Flip event received.\n");
}

static void wait_flip_event(void)
{
	int rc;
	drmEventContext evctx;
	struct pollfd pfd;

	evctx.version = DRM_EVENT_CONTEXT_VERSION;
	evctx.vblank_handler = NULL;
	evctx.page_flip_handler = flip_handler;

	pfd.fd = drm.fd;
	pfd.events = POLLIN;
	pfd.revents = 0;

	rc = poll(&pfd, 1, 1000);
	switch (rc) {
	case 0:
		igt_assert_f(false, "Poll timeout\n");
		break;
	case 1:
		rc = drmHandleEvent(drm.fd, &evctx);
		igt_assert_eq(rc, 0);
		break;
	default:
		igt_assert_f(false, "Unexpected poll rc %d\n", rc);
		break;
	}
}

static void set_prim_plane_for_params(struct modeset_params *params)
{
	int rc, i;
	int crtc_idx = kmstest_get_crtc_idx(drm.res, params->crtc_id);
	uint32_t plane_id = 0;

	for (i = 0; i < drm.plane_res->count_planes; i++)
		if ((drm.planes[i]->possible_crtcs & (1 << crtc_idx)) &&
		    drm.plane_types[i] == DRM_PLANE_TYPE_PRIMARY)
			plane_id = drm.planes[i]->plane_id;
	igt_assert(plane_id);

	rc = drmModeSetPlane(drm.fd, plane_id, params->crtc_id,
			     params->fb.fb->fb_id, 0, 0, 0,
			     params->mode->hdisplay,
			     params->mode->vdisplay,
			     params->fb.x << 16, params->fb.y << 16,
			     params->fb.w << 16, params->fb.h << 16);
	igt_assert(rc == 0);
}

static void page_flip_for_params(struct modeset_params *params,
				 enum flip_type type)
{
	int rc;

	switch (type) {
	case FLIP_PAGEFLIP:
		rc = drmModePageFlip(drm.fd, params->crtc_id,
				     params->fb.fb->fb_id,
				     DRM_MODE_PAGE_FLIP_EVENT, NULL);
		igt_assert_eq(rc, 0);
		wait_flip_event();
		break;
	case FLIP_MODESET:
		set_mode_for_params(params);
		break;
	case FLIP_PLANES:
		set_prim_plane_for_params(params);
		break;
	default:
		igt_assert(false);
	}
}

/*
 * flip - just exercise page flips with the patterns we have
 *
 * METHOD
 *   We draw the pattern on a backbuffer using the provided method, then we
 *   flip, making this the frontbuffer. We can flip both using the dedicated
 *   pageflip IOCTL or the modeset IOCTL.
 *
 * EXPECTED RESULTS
 *   Everything works as expected, screen contents are properly updated.
 *
 * FAILURES
 *   On a failure here you need to go directly to the Kernel's flip code and see
 *   how it interacts with the feature being tested.
 */
static void flip_subtest(const struct test_mode *t)
{
	int r;
	int assertions = 0;
	struct igt_fb fb2, *orig_fb;
	struct modeset_params *params = pick_params(t);
	struct draw_pattern_info *pattern = &pattern1;
	enum color bg_color;

	switch (t->screen) {
	case SCREEN_PRIM:
		assertions |= ASSERT_LAST_ACTION_CHANGED;
		bg_color = COLOR_PRIM_BG;
		break;
	case SCREEN_SCND:
		assertions |= ASSERT_NO_ACTION_CHANGE;
		bg_color = COLOR_SCND_BG;
		break;
	default:
		igt_assert(false);
	}

	prepare_subtest(t, pattern);

	create_fb(t->format, params->fb.fb->width, params->fb.fb->height,
		  LOCAL_I915_FORMAT_MOD_X_TILED, t->plane, &fb2);
	fill_fb(&fb2, bg_color);
	orig_fb = params->fb.fb;

	for (r = 0; r < pattern->n_rects; r++) {
		params->fb.fb = (r % 2 == 0) ? &fb2 : orig_fb;

		if (r != 0)
			draw_rect(pattern, &params->fb, t->method, r - 1);
		draw_rect(pattern, &params->fb, t->method, r);
		update_wanted_crc(t, &pattern->crcs[t->format][r]);

		page_flip_for_params(params, t->flip);

		do_assertions(assertions);
	}

	igt_remove_fb(drm.fd, &fb2);
}

/*
 * fliptrack - check if the hardware tracking works after page flips
 *
 * METHOD
 *   Flip to a new buffer, then draw on it using MMAP_GTT and check the CRC to
 *   make sure the hardware tracking detected the write.
 *
 * EXPECTED RESULTS
 *   Everything works as expected, screen contents are properly updated.
 *
 * FAILURES
 *   First you need to check if the draw and flip subtests pass. Only after both
 *   are passing this test can be useful. If we're failing only on this subtest,
 *   then maybe we are not properly updating the hardware tracking registers
 *   during the flip operations.
 */
static void fliptrack_subtest(const struct test_mode *t, enum flip_type type)
{
	int r;
	struct igt_fb fb2, *orig_fb;
	struct modeset_params *params = pick_params(t);
	struct draw_pattern_info *pattern = &pattern1;

	prepare_subtest(t, pattern);

	create_fb(t->format, params->fb.fb->width, params->fb.fb->height,
		  LOCAL_I915_FORMAT_MOD_X_TILED, t->plane, &fb2);
	fill_fb(&fb2, COLOR_PRIM_BG);
	orig_fb = params->fb.fb;

	for (r = 0; r < pattern->n_rects; r++) {
		params->fb.fb = (r % 2 == 0) ? &fb2 : orig_fb;

		if (r != 0)
			draw_rect(pattern, &params->fb, t->method, r - 1);

		page_flip_for_params(params, type);
		do_assertions(0);

		draw_rect(pattern, &params->fb, t->method, r);
		update_wanted_crc(t, &pattern->crcs[t->format][r]);

		do_assertions(ASSERT_PSR_DISABLED);
	}

	igt_remove_fb(drm.fd, &fb2);
}

/*
 * move - just move the sprite or cursor around
 *
 * METHOD
 *   Move the surface around, following the defined pattern.
 *
 * EXPECTED RESULTS
 *   The move operations are properly detected by the Kernel, and the screen is
 *   properly updated every time.
 *
 * FAILURES
 *   If you get a failure here, check how the Kernel is enabling or disabling
 *   your feature when it moves the planes around.
 */
static void move_subtest(const struct test_mode *t)
{
	int r, rc;
	int assertions = ASSERT_NO_ACTION_CHANGE;
	struct modeset_params *params = pick_params(t);
	struct draw_pattern_info *pattern = &pattern3;
	bool repeat = false;

	prepare_subtest(t, pattern);

	/* Just paint the right color since we start at 0x0. */
	draw_rect(pattern, pick_target(t, params), t->method, 0);
	update_wanted_crc(t, &pattern->crcs[t->format][0]);

	do_assertions(assertions);

	for (r = 1; r < pattern->n_rects; r++) {
		struct rect rect = pattern->get_rect(&params->fb, r);

		switch (t->plane) {
		case PLANE_CUR:
			rc = drmModeMoveCursor(drm.fd, params->crtc_id, rect.x,
					       rect.y);
			igt_assert_eq(rc, 0);
			break;
		case PLANE_SPR:
			rc = drmModeSetPlane(drm.fd, params->sprite_id,
					     params->crtc_id,
					     params->sprite.fb->fb_id, 0,
					     rect.x, rect.y, rect.w,
					     rect.h, 0, 0, rect.w << 16,
					     rect.h << 16);
			igt_assert_eq(rc, 0);
			break;
		default:
			igt_assert(false);
		}
		update_wanted_crc(t, &pattern->crcs[t->format][r]);

		do_assertions(assertions);

		/* "Move" the last rect to the same position just to make sure
		 * this works too. */
		if (r+1 == pattern->n_rects && !repeat) {
			repeat = true;
			r--;
		}
	}
}

/*
 * onoff - just enable and disable the sprite or cursor plane a few times
 *
 * METHOD
 *   Just enable and disable the desired plane a few times.
 *
 * EXPECTED RESULTS
 *   Everything is properly detected by the Kernel and the screen contents are
 *   accurate.
 *
 * FAILURES
 *   As usual, if you get a failure here you need to check how the feature is
 *   being handled when the planes are enabled or disabled.
 */
static void onoff_subtest(const struct test_mode *t)
{
	int r, rc;
	int assertions = ASSERT_NO_ACTION_CHANGE;
	struct modeset_params *params = pick_params(t);
	struct draw_pattern_info *pattern = &pattern3;

	prepare_subtest(t, pattern);

	/* Just paint the right color since we start at 0x0. */
	draw_rect(pattern, pick_target(t, params), t->method, 0);
	update_wanted_crc(t, &pattern->crcs[t->format][0]);
	do_assertions(assertions);

	for (r = 0; r < 4; r++) {
		if (r % 2 == 0) {
			switch (t->plane) {
			case PLANE_CUR:
				rc = drmModeSetCursor(drm.fd, params->crtc_id,
						      0, 0, 0);
				igt_assert_eq(rc, 0);
				break;
			case PLANE_SPR:
				rc = drmModeSetPlane(drm.fd, params->sprite_id,
						     0, 0, 0, 0, 0, 0, 0, 0, 0,
						     0, 0);
				igt_assert_eq(rc, 0);
				break;
			default:
				igt_assert(false);
			}
			update_wanted_crc(t, &blue_crcs[t->format].crc);

		} else {
			switch (t->plane) {
			case PLANE_CUR:
				rc = drmModeSetCursor(drm.fd, params->crtc_id,
						  params->cursor.fb->gem_handle,
						  params->cursor.w,
						  params->cursor.h);
				igt_assert_eq(rc, 0);
				break;
			case PLANE_SPR:
				rc = drmModeSetPlane(drm.fd, params->sprite_id,
						     params->crtc_id,
						     params->sprite.fb->fb_id,
						     0, 0, 0, params->sprite.w,
						     params->sprite.h, 0,
						     0,
						     params->sprite.w << 16,
						     params->sprite.h << 16);
				igt_assert_eq(rc, 0);
				break;
			default:
				igt_assert(false);
			}
			update_wanted_crc(t, &pattern->crcs[t->format][0]);

		}

		do_assertions(assertions);
	}
}

static bool prim_plane_disabled(void)
{
	int i, rc;
	bool disabled, found = false;
	int crtc_idx = kmstest_get_crtc_idx(drm.res, prim_mode_params.crtc_id);

	for (i = 0; i < drm.plane_res->count_planes; i++) {
		if ((drm.planes[i]->possible_crtcs & (1 << crtc_idx)) &&
		    drm.plane_types[i] == DRM_PLANE_TYPE_PRIMARY) {
			found = true;
			disabled = (drm.planes[i]->crtc_id == 0);
		}
	}

	igt_assert(found);

	rc = drmSetClientCap(drm.fd, DRM_CLIENT_CAP_UNIVERSAL_PLANES, 0);
	igt_assert_eq(rc, 0);

	return disabled;
}

/*
 * fullscreen_plane - put a fullscreen plane covering the whole screen
 *
 * METHOD
 *   As simple as the description above.
 *
 * EXPECTED RESULTS
 *   It depends on the feature being tested. FBC gets disabled, but PSR doesn't.
 *
 * FAILURES
 *   Again, if you get failures here you need to dig into the Kernel code, see
 *   how it is handling your feature on this specific case.
 */
static void fullscreen_plane_subtest(const struct test_mode *t)
{
	struct draw_pattern_info *pattern = &pattern4;
	struct igt_fb fullscreen_fb;
	struct rect rect;
	struct modeset_params *params = pick_params(t);
	int assertions;
	int rc;

	prepare_subtest(t, pattern);

	rect = pattern->get_rect(&params->fb, 0);
	create_fb(t->format, rect.w, rect.h, LOCAL_I915_FORMAT_MOD_X_TILED,
		  t->plane, &fullscreen_fb);
	/* Call pick_color() again since PRI and SPR may not support the same
	 * pixel formats. */
	rect.color = pick_color(&fullscreen_fb, COLOR_GREEN);
	igt_draw_fill_fb(drm.fd, &fullscreen_fb, rect.color);

	rc = drmModeSetPlane(drm.fd, params->sprite_id, params->crtc_id,
			     fullscreen_fb.fb_id, 0, 0, 0, fullscreen_fb.width,
			     fullscreen_fb.height, 0, 0,
			     fullscreen_fb.width << 16,
			     fullscreen_fb.height << 16);
	igt_assert_eq(rc, 0);
	update_wanted_crc(t, &pattern->crcs[t->format][0]);

	switch (t->screen) {
	case SCREEN_PRIM:
		assertions = ASSERT_LAST_ACTION_CHANGED;

		if (prim_plane_disabled())
			assertions |= ASSERT_FBC_DISABLED;
		break;
	case SCREEN_SCND:
		assertions = ASSERT_NO_ACTION_CHANGE;
		break;
	default:
		igt_assert(false);
	}
	do_assertions(assertions);

	rc = drmModeSetPlane(drm.fd, params->sprite_id, 0, 0, 0, 0, 0, 0, 0, 0,
			     0, 0, 0);
	igt_assert_eq(rc, 0);

	if (t->screen == SCREEN_PRIM)
		assertions = ASSERT_LAST_ACTION_CHANGED;
	update_wanted_crc(t, &blue_crcs[t->format].crc);
	do_assertions(assertions);

	igt_remove_fb(drm.fd, &fullscreen_fb);
}

/*
 * scaledprimary - try different primary plane scaling strategies
 *
 * METHOD
 *    Enable the primary plane, use drmModeSetPlane to force scaling in
 *    different ways.
 *
 * EXPECTED RESULTS
 *   SKIP on platforms that don't support primary plane scaling. Success on all
 *   others.
 *
 * FAILURES
 *   TODO: although we're exercising the code here, we're not really doing
 *   assertions in order to check if things are working properly. The biggest
 *   issue this code would be able to find would be an incorrectly calculated
 *   CFB size, and today we don't have means to assert this. One day we might
 *   implement some sort of stolen memory checking mechanism, then we'll be able
 *   to force it to run after every drmModeSetPlane call here, so we'll be
 *   checking if the expected CFB size is actually what we think it is.
 */
static void scaledprimary_subtest(const struct test_mode *t)
{
	struct igt_fb new_fb, *old_fb;
	struct modeset_params *params = pick_params(t);
	int i, rc;
	uint32_t plane_id;
	int prim_crtc_idx = kmstest_get_crtc_idx(drm.res,
						 prim_mode_params.crtc_id);

	igt_require_f(intel_gen(intel_get_drm_devid(drm.fd)) >= 9,
		      "Can't test primary plane scaling before gen 9\n");

	prepare_subtest(t, NULL);

	old_fb = params->fb.fb;

	create_fb(t->format, params->fb.fb->width, params->fb.fb->height,
		  LOCAL_I915_FORMAT_MOD_X_TILED,
		  t->plane, &new_fb);
	fill_fb(&new_fb, COLOR_BLUE);

	igt_draw_rect_fb(drm.fd, drm.bufmgr, NULL, &new_fb, t->method,
			 params->fb.x, params->fb.y,
			 params->fb.w / 2, params->fb.h / 2,
			 pick_color(&new_fb, COLOR_GREEN));
	igt_draw_rect_fb(drm.fd, drm.bufmgr, NULL, &new_fb, t->method,
			 params->fb.x + params->fb.w / 2,
			 params->fb.y + params->fb.h / 2,
			 params->fb.w / 2, params->fb.h / 2,
			 pick_color(&new_fb, COLOR_RED));
	igt_draw_rect_fb(drm.fd, drm.bufmgr, NULL, &new_fb, t->method,
			 params->fb.x + params->fb.w / 2,
			 params->fb.y + params->fb.h / 2,
			 params->fb.w / 4, params->fb.h / 4,
			 pick_color(&new_fb, COLOR_MAGENTA));

	for (i = 0; i < drm.plane_res->count_planes; i++)
		if ((drm.planes[i]->possible_crtcs & (1 << prim_crtc_idx)) &&
		    drm.plane_types[i] == DRM_PLANE_TYPE_PRIMARY)
			plane_id = drm.planes[i]->plane_id;

	/* No scaling. */
	rc = drmModeSetPlane(drm.fd, plane_id, params->crtc_id,
			     new_fb.fb_id, 0,
			     0, 0,
			     params->mode->hdisplay, params->mode->vdisplay,
			     params->fb.x << 16, params->fb.y << 16,
			     params->fb.w << 16, params->fb.h << 16);
	igt_assert(rc == 0);
	do_assertions(DONT_ASSERT_CRC);

	/* Source upscaling. */
	rc = drmModeSetPlane(drm.fd, plane_id, params->crtc_id,
			     new_fb.fb_id, 0,
			     0, 0,
			     params->mode->hdisplay, params->mode->vdisplay,
			     params->fb.x << 16, params->fb.y << 16,
			     (params->fb.w / 2) << 16,
			     (params->fb.h / 2) << 16);
	igt_assert(rc == 0);
	do_assertions(DONT_ASSERT_CRC);

	/* Destination doesn't fill the entire CRTC, no scaling. */
	rc = drmModeSetPlane(drm.fd, plane_id, params->crtc_id,
			     new_fb.fb_id, 0,
			     params->mode->hdisplay / 4,
			     params->mode->vdisplay / 4,
			     params->mode->hdisplay / 2,
			     params->mode->vdisplay / 2,
			     params->fb.x << 16, params->fb.y << 16,
			     (params->fb.w / 2) << 16,
			     (params->fb.h / 2) << 16);
	igt_assert(rc == 0);
	do_assertions(DONT_ASSERT_CRC);

	/* Destination doesn't fill the entire CRTC, upscaling. */
	rc = drmModeSetPlane(drm.fd, plane_id, params->crtc_id,
			     new_fb.fb_id, 0,
			     params->mode->hdisplay / 4,
			     params->mode->vdisplay / 4,
			     params->mode->hdisplay / 2,
			     params->mode->vdisplay / 2,
			     (params->fb.x + params->fb.w / 2) << 16,
			     (params->fb.y + params->fb.h / 2) << 16,
			     (params->fb.w / 4) << 16,
			     (params->fb.h / 4) << 16);
	igt_assert(rc == 0);
	do_assertions(DONT_ASSERT_CRC);

	/* Back to the good and old blue fb. */
	rc = drmModeSetPlane(drm.fd, plane_id, params->crtc_id,
			     old_fb->fb_id, 0,
			     0, 0,
			     params->mode->hdisplay, params->mode->vdisplay,
			     params->fb.x << 16, params->fb.y << 16,
			     params->fb.w << 16, params->fb.h << 16);
	igt_assert(rc == 0);
	do_assertions(0);

	igt_remove_fb(drm.fd, &new_fb);
}
/**
 * modesetfrombusy - modeset from a busy buffer to a non-busy buffer
 *
 * METHOD
 *   Set a mode, make the frontbuffer busy using BLT writes, do a modeset to a
 *   non-busy buffer, then check if the features are enabled. The goal of this
 *   test is to exercise a bug we had on the frontbuffer tracking infrastructure
 *   code.
 *
 * EXPECTED RESULTS
 *   No assertions fail.
 *
 * FAILURES
 *   If you're failing this test, then you probably need "drm/i915: Clear
 *   fb_tracking.busy_bits also for synchronous flips" or any other patch that
 *   properly updates dev_priv->fb_tracking.busy_bits when we're alternating
 *   between buffers with different busyness.
 */
static void modesetfrombusy_subtest(const struct test_mode *t)
{
	struct modeset_params *params = pick_params(t);
	struct igt_fb fb2;

	prepare_subtest(t, NULL);

	create_fb(t->format, params->fb.fb->width, params->fb.fb->height,
		  LOCAL_I915_FORMAT_MOD_X_TILED, t->plane, &fb2);
	fill_fb(&fb2, COLOR_PRIM_BG);

	start_busy_thread(params->fb.fb);
	usleep(10000);

	unset_all_crtcs();
	params->fb.fb = &fb2;
	set_mode_for_params(params);

	do_assertions(0);

	stop_busy_thread();

	igt_remove_fb(drm.fd, &fb2);
}

/**
 * suspend - make sure suspend/resume keeps us on the same state
 *
 * METHOD
 *   Set a mode, assert FBC is there, suspend, resume, assert FBC is still
 *   there. Unset modes, assert FBC is disabled, resuspend, resume, assert FBC
 *   is still disabled.
 *
 * EXPECTED RESULTS
 *   Suspend/resume doesn't affect the FBC state.
 *
 * FAILURES
 *   A lot of different things could lead to a bug here, you'll have to check
 *   the Kernel code.
 */
static void suspend_subtest(const struct test_mode *t)
{
	struct modeset_params *params = pick_params(t);

	prepare_subtest(t, NULL);
	sleep(5);
	igt_system_suspend_autoresume(SUSPEND_STATE_MEM, SUSPEND_TEST_NONE);
	sleep(5);
	do_assertions(0);

	unset_all_crtcs();
	sleep(5);
	igt_system_suspend_autoresume(SUSPEND_STATE_MEM, SUSPEND_TEST_NONE);
	sleep(5);
	do_assertions(ASSERT_FBC_DISABLED | ASSERT_PSR_DISABLED |
		      DONT_ASSERT_CRC);

	set_mode_for_params(params);
	do_assertions(0);
}

/**
 * farfromfence - test drawing as far from the fence start as possible
 *
 * METHOD
 *   One of the possible problems with FBC is that if the mode being displayed
 *   is very far away from the fence we might setup the hardware frontbuffer
 *   tracking in the wrong way. So this test tries to set a really tall FB,
 *   makes the CRTC point to the bottom of that FB, then it tries to exercise
 *   the hardware frontbuffer tracking through GTT mmap operations.
 *
 * EXPECTED RESULTS
 *   Everything succeeds.
 *
 * FAILURES
 *   If you're getting wrong CRC calulations, then the hardware tracking might
 *   be misconfigured and needs to be checked. If we're failing because FBC is
 *   disabled and the reason is that there's not enough stolen memory, then the
 *   Kernel might be calculating the amount of stolen memory needed based on the
 *   whole framebuffer size, and not just on the needed size: in this case, you
 *   need a newer Kernel.
 */
static void farfromfence_subtest(const struct test_mode *t)
{
	int r;
	struct igt_fb tall_fb;
	struct modeset_params *params = pick_params(t);
	struct draw_pattern_info *pattern = &pattern1;
	struct fb_region *target;
	int max_height, assertions = 0;
	int gen = intel_gen(intel_get_drm_devid(drm.fd));

	switch (gen) {
	case 2:
		max_height = 2048;
		break;
	case 3:
		max_height = 4096;
		break;
	default:
		max_height = 8192;
		break;
	}

	/* Gen 9 doesn't do the same dspaddr_offset magic as the older
	 * gens, so FBC may not be enabled there. */
	if (gen >= 9)
		assertions |= DONT_ASSERT_FEATURE_STATUS;

	prepare_subtest(t, pattern);
	target = pick_target(t, params);

	create_fb(t->format, params->mode->hdisplay, max_height,
		  LOCAL_I915_FORMAT_MOD_X_TILED, t->plane, &tall_fb);

	fill_fb(&tall_fb, COLOR_PRIM_BG);

	params->fb.fb = &tall_fb;
	params->fb.x = 0;
	params->fb.y = max_height - params->mode->vdisplay;
	set_mode_for_params(params);
	do_assertions(assertions);

	for (r = 0; r < pattern->n_rects; r++) {
		draw_rect(pattern, target, t->method, r);
		update_wanted_crc(t, &pattern->crcs[t->format][r]);

		/* GTT draws disable PSR. */
		do_assertions(assertions | ASSERT_PSR_DISABLED);
	}

	igt_remove_fb(drm.fd, &tall_fb);
}

static void try_invalid_strides(void)
{
	uint32_t gem_handle;
	int rc;

	/* Sizes that the Kernel shouldn't even allow for tiled */
	gem_handle = gem_create(drm.fd, 2048);

	/* Smaller than 512, yet still 64-byte aligned. */
	rc = __gem_set_tiling(drm.fd, gem_handle, I915_TILING_X, 448);
	igt_assert_eq(rc, -EINVAL);

	/* Bigger than 512, but not 64-byte aligned. */
	rc = __gem_set_tiling(drm.fd, gem_handle, I915_TILING_X, 1022);
	igt_assert_eq(rc, -EINVAL);

	/* Just make sure something actually works. */
	rc = __gem_set_tiling(drm.fd, gem_handle, I915_TILING_X, 1024);
	igt_assert_eq(rc, 0);

	gem_close(drm.fd, gem_handle);
}

/**
 * badstride - try to use buffers with strides that are not supported
 *
 * METHOD
 *   First we try to create buffers with strides that are not allowed for tiled
 *   surfaces and assert the Kernel rejects them. Then we create buffers with
 *   strides that are allowed by the Kernel, but that are incompatible with FBC
 *   and we assert that FBC stays disabled after we set a mode on those buffers.
 *
 * EXPECTED RESULTS
 *   The invalid strides are rejected, and the valid strides that are
 *   incompatible with FBC result in FBC disabled.
 *
 * FAILURES
 *   There are two possible places where the Kernel can be broken: either the
 *   code that checks valid strides for tiled buffers or the code that checks
 *   the valid strides for FBC.
 */
static void badstride_subtest(const struct test_mode *t)
{
	struct igt_fb wide_fb, *old_fb;
	struct modeset_params *params = pick_params(t);
	int rc;

	try_invalid_strides();

	prepare_subtest(t, NULL);

	old_fb = params->fb.fb;

	create_fb(t->format, params->fb.fb->width + 4096, params->fb.fb->height,
		  LOCAL_I915_FORMAT_MOD_X_TILED, t->plane, &wide_fb);
	igt_assert(wide_fb.stride > 16384);

	fill_fb(&wide_fb, COLOR_PRIM_BG);

	/* Try a simple modeset with the new fb. */
	params->fb.fb = &wide_fb;
	set_mode_for_params(params);
	do_assertions(ASSERT_FBC_DISABLED);

	/* Go back to the old fb so FBC works again. */
	params->fb.fb = old_fb;
	set_mode_for_params(params);
	do_assertions(0);

	/* We're doing the equivalent of a modeset, but with the planes API. */
	params->fb.fb = &wide_fb;
	set_prim_plane_for_params(params);
	do_assertions(ASSERT_FBC_DISABLED);

	params->fb.fb = old_fb;
	set_mode_for_params(params);
	do_assertions(0);

	/*
	 * We previously couldn't use the page flip IOCTL to flip to a buffer
	 * with a different stride. With the atomic page flip helper we can,
	 * so allow page flip to fail and succeed.
	 */
	rc = drmModePageFlip(drm.fd, params->crtc_id, wide_fb.fb_id, 0, NULL);
	igt_assert(rc == -EINVAL || rc == 0);
	do_assertions(rc == 0 ? ASSERT_FBC_DISABLED : 0);

	igt_remove_fb(drm.fd, &wide_fb);
}

/**
 * stridechange - change the frontbuffer stride by doing a modeset
 *
 * METHOD
 *   This test sets a mode on a CRTC, then creates a buffer with a different
 *   stride - still compatible with FBC -, and sets the mode on it. The Kernel
 *   currently shortcuts the modeset path for this case, so it won't trigger
 *   calls to xx_crtc_enable or xx_crtc_disable, and that could lead to
 *   problems, so test the case.
 *
 * EXPECTED RESULTS
 *   With the current Kernel, FBC may or may not remain enabled on this case,
 *   but we can still check the CRC values.
 *
 * FAILURES
 *   A bad Kernel may just not resize the CFB while keeping FBC enabled, and
 *   this can lead to underruns or stolen memory corruption. Underruns usually
 *   lead to CRC check errors, and stolen memory corruption can't be easily
 *   checked currently. A bad Kernel may also just throw some WARNs on dmesg.
 */
static void stridechange_subtest(const struct test_mode *t)
{
	struct igt_fb new_fb, *old_fb;
	struct modeset_params *params = pick_params(t);
	int rc;

	prepare_subtest(t, NULL);

	old_fb = params->fb.fb;

	create_fb(t->format, params->fb.fb->width + 512, params->fb.fb->height,
		  LOCAL_I915_FORMAT_MOD_X_TILED, t->plane, &new_fb);
	fill_fb(&new_fb, COLOR_PRIM_BG);

	igt_assert(old_fb->stride != new_fb.stride);

	/* We can't assert that FBC will be enabled since there may not be
	 * enough space for the CFB, but we can check the CRC. */
	params->fb.fb = &new_fb;
	set_mode_for_params(params);
	do_assertions(DONT_ASSERT_FEATURE_STATUS);

	/* Go back to the fb that can have FBC. */
	params->fb.fb = old_fb;
	set_mode_for_params(params);
	do_assertions(0);

	/* This operation is the same as above, but with the planes API. */
	params->fb.fb = &new_fb;
	set_prim_plane_for_params(params);
	do_assertions(DONT_ASSERT_FEATURE_STATUS);

	params->fb.fb = old_fb;
	set_prim_plane_for_params(params);
	do_assertions(0);

	/*
	 * Try to set a new stride. with the page flip api. This is allowed
	 * with the atomic page flip helper, but not with the legacy page flip.
	 */
	rc = drmModePageFlip(drm.fd, params->crtc_id, new_fb.fb_id, 0, NULL);
	igt_assert(rc == -EINVAL || rc == 0);
	do_assertions(0);

	igt_remove_fb(drm.fd, &new_fb);
}

/**
 * tilingchange - alternate between tiled and untiled in multiple ways
 *
 * METHOD
 *   This test alternates between tiled and untiled frontbuffers of the same
 *   size and format through multiple different APIs: the page flip IOCTL,
 *   normal modesets and the plane APIs.
 *
 * EXPECTED RESULTS
 *   FBC gets properly disabled for the untiled FB and reenabled for the
 *   tiled FB.
 *
 * FAILURES
 *   Bad Kernels may somehow leave FBC enabled, which can cause FIFO underruns
 *   that lead to CRC assertion failures.
 */
static void tilingchange_subtest(const struct test_mode *t)
{
	struct igt_fb new_fb, *old_fb;
	struct modeset_params *params = pick_params(t);
	enum flip_type flip_type;

	prepare_subtest(t, NULL);

	old_fb = params->fb.fb;

	create_fb(t->format, params->fb.fb->width, params->fb.fb->height,
		  LOCAL_DRM_FORMAT_MOD_NONE, t->plane, &new_fb);
	fill_fb(&new_fb, COLOR_PRIM_BG);

	for (flip_type = 0; flip_type < FLIP_COUNT; flip_type++) {
		igt_debug("Flip type: %d\n", flip_type);

		/* Set a buffer with no tiling. */
		params->fb.fb = &new_fb;
		page_flip_for_params(params, flip_type);
		do_assertions(ASSERT_FBC_DISABLED);

		/* Put FBC back in a working state. */
		params->fb.fb = old_fb;
		page_flip_for_params(params, flip_type);
		do_assertions(0);
	}

	igt_remove_fb(drm.fd, &new_fb);
}

/*
 * basic - do some basic operations regardless of which features are enabled
 *
 * METHOD
 *   This subtest does page flips and draw operations and checks the CRCs of the
 *   results. The big difference between this and the others is that here we
 *   don't enable/disable any features such as FBC or PSR: we go with whatever
 *   the Kernel has enabled by default for us. This subtest only does things
 *   that are exercised by the other subtests and in a less exhaustive way: it's
 *   completely redundant. On the other hand, it is very quick and was created
 *   with the CI system in mind: it's a quick way to detect regressions, so if
 *   it fails, then we can run the other subtests to find out why.
 *
 * EXPECTED RESULTS
 *   Passed CRC assertions.
 *
 * FAILURES
 *   If you get a failure here, you should run the more specific draw and flip
 *   subtests of each feature in order to discover what exactly is failing and
 *   why.
 *
 * TODO: do sink CRC assertions in case sink_crc.supported. Only do this after
 * our sink CRC code gets 100% reliable, in order to avoid CI false negatives.
 */
static void basic_subtest(const struct test_mode *t)
{
	struct draw_pattern_info *pattern = &pattern1;
	struct modeset_params *params = pick_params(t);
	enum igt_draw_method method;
	struct igt_fb *fb1, fb2;
	int r;
	int assertions = DONT_ASSERT_FEATURE_STATUS;

	prepare_subtest(t, pattern);

	create_fb(t->format, params->fb.fb->width, params->fb.fb->height,
		  LOCAL_I915_FORMAT_MOD_X_TILED, t->plane, &fb2);
	fb1 = params->fb.fb;

	for (r = 0, method = 0; method < IGT_DRAW_METHOD_COUNT; method++, r++) {
		if (r == pattern->n_rects) {
			params->fb.fb = (params->fb.fb == fb1) ? &fb2 : fb1;

			fill_fb_region(&params->fb, COLOR_PRIM_BG);
			update_wanted_crc(t, &blue_crcs[t->format].crc);

			page_flip_for_params(params, t->flip);
			do_assertions(assertions);

			r = 0;
		}

		draw_rect(pattern, &params->fb, method, r);
		update_wanted_crc(t, &pattern->crcs[t->format][r]);
		do_assertions(assertions);
	}

	igt_remove_fb(drm.fd, &fb2);
}

static int opt_handler(int option, int option_index, void *data)
{
	switch (option) {
	case 's':
		opt.check_status = false;
		break;
	case 'c':
		opt.check_crc = false;
		break;
	case 'o':
		opt.fbc_check_compression = false;
		break;
	case 'a':
		opt.fbc_check_last_action = false;
		break;
	case 'e':
		opt.no_edp = true;
		break;
	case 'm':
		opt.small_modes = true;
		break;
	case 'i':
		opt.show_hidden = true;
		break;
	case 't':
		opt.step++;
		break;
	case 'x':
		errno = 0;
		opt.shared_fb_x_offset = strtol(optarg, NULL, 0);
		igt_assert(errno == 0);
		break;
	case 'y':
		errno = 0;
		opt.shared_fb_y_offset = strtol(optarg, NULL, 0);
		igt_assert(errno == 0);
		break;
	case '1':
		igt_assert_eq(opt.only_pipes, PIPE_COUNT);
		opt.only_pipes = PIPE_SINGLE;
		break;
	case '2':
		igt_assert_eq(opt.only_pipes, PIPE_COUNT);
		opt.only_pipes = PIPE_DUAL;
		break;
	default:
		igt_assert(false);
	}

	return 0;
}

const char *help_str =
"  --no-status-check           Don't check for enable/disable status\n"
"  --no-crc-check              Don't check for CRC values\n"
"  --no-fbc-compression-check  Don't check for the FBC compression status\n"
"  --no-fbc-action-check       Don't check for the FBC last action\n"
"  --no-edp                    Don't use eDP monitors\n"
"  --use-small-modes           Use smaller resolutions for the modes\n"
"  --show-hidden               Show hidden subtests\n"
"  --step                      Stop on each step so you can check the screen\n"
"  --shared-fb-x offset        Use 'offset' as the X offset for the shared FB\n"
"  --shared-fb-y offset        Use 'offset' as the Y offset for the shared FB\n"
"  --1p-only                   Only run subtests that use 1 pipe\n"
"  --2p-only                   Only run subtests that use 2 pipes\n";

static const char *pipes_str(int pipes)
{
	switch (pipes) {
	case PIPE_SINGLE:
		return "1p";
	case PIPE_DUAL:
		return "2p";
	default:
		igt_assert(false);
	}
}

static const char *screen_str(int screen)
{
	switch (screen) {
	case SCREEN_PRIM:
		return "primscrn";
	case SCREEN_SCND:
		return "scndscrn";
	case SCREEN_OFFSCREEN:
		return "offscren";
	default:
		igt_assert(false);
	}
}

static const char *plane_str(int plane)
{
	switch (plane) {
	case PLANE_PRI:
		return "pri";
	case PLANE_CUR:
		return "cur";
	case PLANE_SPR:
		return "spr";
	default:
		igt_assert(false);
	}
}

static const char *fbs_str(int fb)
{
	switch (fb) {
	case FBS_INDIVIDUAL:
		return "indfb";
	case FBS_SHARED:
		return "shrfb";
	default:
		igt_assert(false);
	}
}

static const char *feature_str(int feature)
{
	switch (feature) {
	case FEATURE_NONE:
		return "nop";
	case FEATURE_FBC:
		return "fbc";
	case FEATURE_PSR:
		return "psr";
	case FEATURE_FBC | FEATURE_PSR:
		return "fbcpsr";
	default:
		igt_assert(false);
	}
}

static const char *format_str(enum pixel_format format)
{
	switch (format) {
	case FORMAT_RGB888:
		return "rgb888";
	case FORMAT_RGB565:
		return "rgb565";
	case FORMAT_RGB101010:
		return "rgb101010";
	default:
		igt_assert(false);
	}
}

static const char *flip_str(enum flip_type flip)
{
	switch (flip) {
	case FLIP_PAGEFLIP:
		return "pg";
	case FLIP_MODESET:
		return "ms";
	case FLIP_PLANES:
		return "pl";
	default:
		igt_assert(false);
	}
}

#define TEST_MODE_ITER_BEGIN(t) \
	t.format = FORMAT_DEFAULT;					   \
	t.flip = FLIP_PAGEFLIP;						   \
	for (t.feature = 0; t.feature < FEATURE_COUNT; t.feature++) {	   \
	for (t.pipes = 0; t.pipes < PIPE_COUNT; t.pipes++) {		   \
	for (t.screen = 0; t.screen < SCREEN_COUNT; t.screen++) {	   \
	for (t.plane = 0; t.plane < PLANE_COUNT; t.plane++) {		   \
	for (t.fbs = 0; t.fbs < FBS_COUNT; t.fbs++) {			   \
	for (t.method = 0; t.method < IGT_DRAW_METHOD_COUNT; t.method++) { \
		if (t.pipes == PIPE_SINGLE && t.screen == SCREEN_SCND)	   \
			continue;					   \
		if (t.screen == SCREEN_OFFSCREEN && t.plane != PLANE_PRI)  \
			continue;					   \
		if (!opt.show_hidden && t.pipes == PIPE_DUAL &&		   \
		    t.screen == SCREEN_OFFSCREEN)			   \
			continue;					   \
		if (!opt.show_hidden && t.feature == FEATURE_NONE)	   \
			continue;					   \
		if (!opt.show_hidden && t.fbs == FBS_SHARED &&		   \
		    (t.plane == PLANE_CUR || t.plane == PLANE_SPR))	   \
			continue;


#define TEST_MODE_ITER_END } } } } } }

int main(int argc, char *argv[])
{
	struct test_mode t;
	struct option long_options[] = {
		{ "no-status-check",          0, 0, 's'},
		{ "no-crc-check",             0, 0, 'c'},
		{ "no-fbc-compression-check", 0, 0, 'o'},
		{ "no-fbc-action-check",      0, 0, 'a'},
		{ "no-edp",                   0, 0, 'e'},
		{ "use-small-modes",          0, 0, 'm'},
		{ "show-hidden",              0, 0, 'i'},
		{ "step",                     0, 0, 't'},
		{ "shared-fb-x",              1, 0, 'x'},
		{ "shared-fb-y",              1, 0, 'y'},
		{ "1p-only",                  0, 0, '1'},
		{ "2p-only",                  0, 0, '2'},
		{ 0, 0, 0, 0 }
	};

	igt_subtest_init_parse_opts(&argc, argv, "", long_options, help_str,
				    opt_handler, NULL);

	igt_fixture
		setup_environment();

	for (t.feature = 0; t.feature < FEATURE_COUNT; t.feature++) {
		if (!opt.show_hidden && t.feature == FEATURE_NONE)
			continue;
		for (t.pipes = 0; t.pipes < PIPE_COUNT; t.pipes++) {
			t.screen = SCREEN_PRIM;
			t.plane = PLANE_PRI;
			t.fbs = FBS_INDIVIDUAL;
			t.format = FORMAT_DEFAULT;
			/* Make sure nothing is using these values. */
			t.flip = -1;
			t.method = -1;

			igt_subtest_f("%s-%s-rte",
				      feature_str(t.feature),
				      pipes_str(t.pipes))
				rte_subtest(&t);
		}
	}

	TEST_MODE_ITER_BEGIN(t)
		igt_subtest_f("%s-%s-%s-%s-%s-draw-%s",
			      feature_str(t.feature),
			      pipes_str(t.pipes),
			      screen_str(t.screen),
			      plane_str(t.plane),
			      fbs_str(t.fbs),
			      igt_draw_get_method_name(t.method))
			draw_subtest(&t);
	TEST_MODE_ITER_END

	TEST_MODE_ITER_BEGIN(t)
		if (t.plane != PLANE_PRI ||
		    t.screen == SCREEN_OFFSCREEN ||
		    (!opt.show_hidden && t.method != IGT_DRAW_BLT))
			continue;

		for (t.flip = 0; t.flip < FLIP_COUNT; t.flip++)
			igt_subtest_f("%s-%s-%s-%s-%sflip-%s",
				      feature_str(t.feature),
				      pipes_str(t.pipes),
				      screen_str(t.screen),
				      fbs_str(t.fbs),
				      flip_str(t.flip),
				      igt_draw_get_method_name(t.method))
				flip_subtest(&t);
	TEST_MODE_ITER_END

	TEST_MODE_ITER_BEGIN(t)
		if (t.plane != PLANE_PRI ||
		    t.screen != SCREEN_PRIM ||
		    t.method != IGT_DRAW_MMAP_GTT ||
		    (t.feature & FEATURE_FBC) == 0)
			continue;

		igt_subtest_f("%s-%s-%s-fliptrack",
			      feature_str(t.feature),
			      pipes_str(t.pipes),
			      fbs_str(t.fbs))
			fliptrack_subtest(&t, FLIP_PAGEFLIP);
	TEST_MODE_ITER_END

	TEST_MODE_ITER_BEGIN(t)
		if (t.screen == SCREEN_OFFSCREEN ||
		    t.method != IGT_DRAW_BLT ||
		    t.plane == PLANE_PRI)
			continue;

		igt_subtest_f("%s-%s-%s-%s-%s-move",
			      feature_str(t.feature),
			      pipes_str(t.pipes),
			      screen_str(t.screen),
			      plane_str(t.plane),
			      fbs_str(t.fbs))
			move_subtest(&t);

		igt_subtest_f("%s-%s-%s-%s-%s-onoff",
			      feature_str(t.feature),
			      pipes_str(t.pipes),
			      screen_str(t.screen),
			      plane_str(t.plane),
			      fbs_str(t.fbs))
			onoff_subtest(&t);
	TEST_MODE_ITER_END

	TEST_MODE_ITER_BEGIN(t)
		if (t.screen == SCREEN_OFFSCREEN ||
		    t.method != IGT_DRAW_BLT ||
		    t.plane != PLANE_SPR)
			continue;

		igt_subtest_f("%s-%s-%s-%s-%s-fullscreen",
			      feature_str(t.feature),
			      pipes_str(t.pipes),
			      screen_str(t.screen),
			      plane_str(t.plane),
			      fbs_str(t.fbs))
			fullscreen_plane_subtest(&t);
	TEST_MODE_ITER_END

	TEST_MODE_ITER_BEGIN(t)
		if (t.screen != SCREEN_PRIM ||
		    t.method != IGT_DRAW_BLT ||
		    (!opt.show_hidden && t.plane != PLANE_PRI) ||
		    (!opt.show_hidden && t.fbs != FBS_INDIVIDUAL))
			continue;

		igt_subtest_f("%s-%s-%s-%s-multidraw",
			      feature_str(t.feature),
			      pipes_str(t.pipes),
			      plane_str(t.plane),
			      fbs_str(t.fbs))
			multidraw_subtest(&t);
	TEST_MODE_ITER_END

	TEST_MODE_ITER_BEGIN(t)
		if (t.pipes != PIPE_SINGLE ||
		    t.screen != SCREEN_PRIM ||
		    t.plane != PLANE_PRI ||
		    t.fbs != FBS_INDIVIDUAL ||
		    t.method != IGT_DRAW_MMAP_GTT)
			continue;

		igt_subtest_f("%s-farfromfence", feature_str(t.feature))
			farfromfence_subtest(&t);
	TEST_MODE_ITER_END

	TEST_MODE_ITER_BEGIN(t)
		if (t.pipes != PIPE_SINGLE ||
		    t.screen != SCREEN_PRIM ||
		    t.plane != PLANE_PRI ||
		    t.fbs != FBS_INDIVIDUAL)
			continue;

		for (t.format = 0; t.format < FORMAT_COUNT; t.format++) {
			/* Skip what we already tested. */
			if (t.format == FORMAT_DEFAULT)
				continue;

			igt_subtest_f("%s-%s-draw-%s",
				      feature_str(t.feature),
				      format_str(t.format),
				      igt_draw_get_method_name(t.method))
				format_draw_subtest(&t);
		}
	TEST_MODE_ITER_END

	TEST_MODE_ITER_BEGIN(t)
		if (t.pipes != PIPE_SINGLE ||
		    t.screen != SCREEN_PRIM ||
		    t.plane != PLANE_PRI ||
		    t.method != IGT_DRAW_BLT)
			continue;
		igt_subtest_f("%s-%s-scaledprimary",
			      feature_str(t.feature),
			      fbs_str(t.fbs))
			scaledprimary_subtest(&t);
	TEST_MODE_ITER_END

	TEST_MODE_ITER_BEGIN(t)
		if (t.pipes != PIPE_SINGLE ||
		    t.screen != SCREEN_PRIM ||
		    t.plane != PLANE_PRI ||
		    t.fbs != FBS_INDIVIDUAL ||
		    t.method != IGT_DRAW_BLT)
			continue;

		igt_subtest_f("%s-modesetfrombusy", feature_str(t.feature))
			modesetfrombusy_subtest(&t);

		if (t.feature & FEATURE_FBC) {
			igt_subtest_f("%s-badstride", feature_str(t.feature))
				badstride_subtest(&t);

			igt_subtest_f("%s-stridechange", feature_str(t.feature))
				stridechange_subtest(&t);

			igt_subtest_f("%s-tilingchange", feature_str(t.feature))
				tilingchange_subtest(&t);
		}

		if (t.feature & FEATURE_PSR)
			igt_subtest_f("%s-slowdraw", feature_str(t.feature))
				slow_draw_subtest(&t);

		igt_subtest_f("%s-suspend", feature_str(t.feature))
			suspend_subtest(&t);
	TEST_MODE_ITER_END

	t.pipes = PIPE_SINGLE;
	t.screen = SCREEN_PRIM;
	t.plane = PLANE_PRI;
	t.fbs = FBS_INDIVIDUAL;
	t.feature = FEATURE_DEFAULT;
	t.format = FORMAT_DEFAULT;
	t.flip = FLIP_PAGEFLIP;
	igt_subtest("basic")
		basic_subtest(&t);

	igt_fixture
		teardown_environment();

	igt_exit();
}