summaryrefslogtreecommitdiff
path: root/lib/igt_fb.c
blob: 25a07b0dfa3909793b2ed349ea35b5e00242dc66 (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
/*
 * Copyright © 2013,2014 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:
 * 	Daniel Vetter <daniel.vetter@ffwll.ch>
 * 	Damien Lespiau <damien.lespiau@intel.com>
 */

#include <stdio.h>
#include <math.h>
#include <wchar.h>
#include <inttypes.h>
#include <pixman.h>

#include "drmtest.h"
#include "igt_aux.h"
#include "igt_color_encoding.h"
#include "igt_fb.h"
#include "igt_kms.h"
#include "igt_matrix.h"
#include "igt_vc4.h"
#include "igt_x86.h"
#include "ioctl_wrappers.h"
#include "intel_batchbuffer.h"
#include "intel_chipset.h"

/**
 * SECTION:igt_fb
 * @short_description: Framebuffer handling and drawing library
 * @title: Framebuffer
 * @include: igt.h
 *
 * This library contains helper functions for handling kms framebuffer objects
 * using #igt_fb structures to track all the metadata.  igt_create_fb() creates
 * a basic framebuffer and igt_remove_fb() cleans everything up again.
 *
 * It also supports drawing using the cairo library and provides some simplified
 * helper functions to easily draw test patterns. The main function to create a
 * cairo drawing context for a framebuffer object is igt_get_cairo_ctx().
 *
 * Finally it also pulls in the drm fourcc headers and provides some helper
 * functions to work with these pixel format codes.
 */

#define PIXMAN_invalid	0

#if CAIRO_VERSION < CAIRO_VERSION_ENCODE(1, 17, 2)
/*
 * We need cairo 1.17.2 to use HDR formats, but the only thing added is a value
 * to cairo_format_t.
 *
 * To prevent going outside the enum, make cairo_format_t an int and define
 * ourselves.
 */

#define CAIRO_FORMAT_RGB96F (6)
#define CAIRO_FORMAT_RGBA128F (7)
#define cairo_format_t int
#endif

/* drm fourcc/cairo format maps */
static const struct format_desc_struct {
	const char *name;
	uint32_t drm_id;
	cairo_format_t cairo_id;
	pixman_format_code_t pixman_id;
	int depth;
	int num_planes;
	int plane_bpp[4];
	uint8_t hsub;
	uint8_t vsub;
} format_desc[] = {
	{ .name = "ARGB1555", .depth = -1, .drm_id = DRM_FORMAT_ARGB1555,
	  .cairo_id = CAIRO_FORMAT_INVALID,
	  .pixman_id = PIXMAN_a1r5g5b5,
	  .num_planes = 1, .plane_bpp = { 16, },
	  .hsub = 1, .vsub = 1,
	},
	{ .name = "XRGB1555", .depth = -1, .drm_id = DRM_FORMAT_XRGB1555,
	  .cairo_id = CAIRO_FORMAT_INVALID,
	  .pixman_id = PIXMAN_x1r5g5b5,
	  .num_planes = 1, .plane_bpp = { 16, },
	  .hsub = 1, .vsub = 1,
	},
	{ .name = "RGB565", .depth = 16, .drm_id = DRM_FORMAT_RGB565,
	  .cairo_id = CAIRO_FORMAT_RGB16_565,
	  .pixman_id = PIXMAN_r5g6b5,
	  .num_planes = 1, .plane_bpp = { 16, },
	  .hsub = 1, .vsub = 1,
	},
	{ .name = "BGR565", .depth = -1, .drm_id = DRM_FORMAT_BGR565,
	  .cairo_id = CAIRO_FORMAT_INVALID,
	  .pixman_id = PIXMAN_b5g6r5,
	  .num_planes = 1, .plane_bpp = { 16, },
	  .hsub = 1, .vsub = 1,
	},
	{ .name = "BGR888", .depth = -1, .drm_id = DRM_FORMAT_BGR888,
	  .cairo_id = CAIRO_FORMAT_INVALID,
	  .pixman_id = PIXMAN_b8g8r8,
	  .num_planes = 1, .plane_bpp = { 24, },
	  .hsub = 1, .vsub = 1,
	},
	{ .name = "RGB888", .depth = -1, .drm_id = DRM_FORMAT_RGB888,
	  .cairo_id = CAIRO_FORMAT_INVALID,
	  .pixman_id = PIXMAN_r8g8b8,
	  .num_planes = 1, .plane_bpp = { 24, },
	  .hsub = 1, .vsub = 1,
	},
	{ .name = "XYUV8888", .depth = -1, .drm_id = DRM_FORMAT_XYUV8888,
	  .cairo_id = CAIRO_FORMAT_RGB24,
	  .num_planes = 1, .plane_bpp = { 32, },
	  .hsub = 1, .vsub = 1,
	},
	{ .name = "XRGB8888", .depth = 24, .drm_id = DRM_FORMAT_XRGB8888,
	  .cairo_id = CAIRO_FORMAT_RGB24,
	  .pixman_id = PIXMAN_x8r8g8b8,
	  .num_planes = 1, .plane_bpp = { 32, },
	  .hsub = 1, .vsub = 1,
	},
	{ .name = "XBGR8888", .depth = -1, .drm_id = DRM_FORMAT_XBGR8888,
	  .cairo_id = CAIRO_FORMAT_INVALID,
	  .pixman_id = PIXMAN_x8b8g8r8,
	  .num_planes = 1, .plane_bpp = { 32, },
	  .hsub = 1, .vsub = 1,
	},
	{ .name = "XRGB2101010", .depth = 30, .drm_id = DRM_FORMAT_XRGB2101010,
	  .cairo_id = CAIRO_FORMAT_RGB30,
	  .pixman_id = PIXMAN_x2r10g10b10,
	  .num_planes = 1, .plane_bpp = { 32, },
	  .hsub = 1, .vsub = 1,
	},
	{ .name = "ARGB8888", .depth = 32, .drm_id = DRM_FORMAT_ARGB8888,
	  .cairo_id = CAIRO_FORMAT_ARGB32,
	  .pixman_id = PIXMAN_a8r8g8b8,
	  .num_planes = 1, .plane_bpp = { 32, },
	  .hsub = 1, .vsub = 1,
	},
	{ .name = "ABGR8888", .depth = -1, .drm_id = DRM_FORMAT_ABGR8888,
	  .cairo_id = CAIRO_FORMAT_INVALID,
	  .pixman_id = PIXMAN_a8b8g8r8,
	  .num_planes = 1, .plane_bpp = { 32, },
	  .hsub = 1, .vsub = 1,
	},
	{ .name = "NV12", .depth = -1, .drm_id = DRM_FORMAT_NV12,
	  .cairo_id = CAIRO_FORMAT_RGB24,
	  .num_planes = 2, .plane_bpp = { 8, 16, },
	  .hsub = 2, .vsub = 2,
	},
	{ .name = "NV16", .depth = -1, .drm_id = DRM_FORMAT_NV16,
	  .cairo_id = CAIRO_FORMAT_RGB24,
	  .num_planes = 2, .plane_bpp = { 8, 16, },
	  .hsub = 2, .vsub = 1,
	},
	{ .name = "NV21", .depth = -1, .drm_id = DRM_FORMAT_NV21,
	  .cairo_id = CAIRO_FORMAT_RGB24,
	  .num_planes = 2, .plane_bpp = { 8, 16, },
	  .hsub = 2, .vsub = 2,
	},
	{ .name = "NV61", .depth = -1, .drm_id = DRM_FORMAT_NV61,
	  .cairo_id = CAIRO_FORMAT_RGB24,
	  .num_planes = 2, .plane_bpp = { 8, 16, },
	  .hsub = 2, .vsub = 1,
	},
	{ .name = "YUYV", .depth = -1, .drm_id = DRM_FORMAT_YUYV,
	  .cairo_id = CAIRO_FORMAT_RGB24,
	  .num_planes = 1, .plane_bpp = { 16, },
	  .hsub = 2, .vsub = 1,
	},
	{ .name = "YVYU", .depth = -1, .drm_id = DRM_FORMAT_YVYU,
	  .cairo_id = CAIRO_FORMAT_RGB24,
	  .num_planes = 1, .plane_bpp = { 16, },
	  .hsub = 2, .vsub = 1,
	},
	{ .name = "UYVY", .depth = -1, .drm_id = DRM_FORMAT_UYVY,
	  .cairo_id = CAIRO_FORMAT_RGB24,
	  .num_planes = 1, .plane_bpp = { 16, },
	  .hsub = 2, .vsub = 1,
	},
	{ .name = "VYUY", .depth = -1, .drm_id = DRM_FORMAT_VYUY,
	  .cairo_id = CAIRO_FORMAT_RGB24,
	  .num_planes = 1, .plane_bpp = { 16, },
	  .hsub = 2, .vsub = 1,
	},
	{ .name = "YU12", .depth = -1, .drm_id = DRM_FORMAT_YUV420,
	  .cairo_id = CAIRO_FORMAT_RGB24,
	  .num_planes = 3, .plane_bpp = { 8, 8, 8, },
	  .hsub = 2, .vsub = 2,
	},
	{ .name = "YU16", .depth = -1, .drm_id = DRM_FORMAT_YUV422,
	  .cairo_id = CAIRO_FORMAT_RGB24,
	  .num_planes = 3, .plane_bpp = { 8, 8, 8, },
	  .hsub = 2, .vsub = 1,
	},
	{ .name = "YV12", .depth = -1, .drm_id = DRM_FORMAT_YVU420,
	  .cairo_id = CAIRO_FORMAT_RGB24,
	  .num_planes = 3, .plane_bpp = { 8, 8, 8, },
	  .hsub = 2, .vsub = 2,
	},
	{ .name = "YV16", .depth = -1, .drm_id = DRM_FORMAT_YVU422,
	  .cairo_id = CAIRO_FORMAT_RGB24,
	  .num_planes = 3, .plane_bpp = { 8, 8, 8, },
	  .hsub = 2, .vsub = 1,
	},
	{ .name = "P010", .depth = -1, .drm_id = DRM_FORMAT_P010,
	  .cairo_id = CAIRO_FORMAT_RGB96F,
	  .num_planes = 2, .plane_bpp = { 16, 32 },
	  .vsub = 2, .hsub = 2,
	},
	{ .name = "P012", .depth = -1, .drm_id = DRM_FORMAT_P012,
	  .cairo_id = CAIRO_FORMAT_RGB96F,
	  .num_planes = 2, .plane_bpp = { 16, 32 },
	  .vsub = 2, .hsub = 2,
	},
	{ .name = "P016", .depth = -1, .drm_id = DRM_FORMAT_P016,
	  .cairo_id = CAIRO_FORMAT_RGB96F,
	  .num_planes = 2, .plane_bpp = { 16, 32 },
	  .vsub = 2, .hsub = 2,
	},
	{ .name = "IGT-FLOAT", .depth = -1, .drm_id = IGT_FORMAT_FLOAT,
	  .cairo_id = CAIRO_FORMAT_INVALID,
	  .num_planes = 1, .plane_bpp = { 128 },
	},
};
#define for_each_format(f)	\
	for (f = format_desc; f - format_desc < ARRAY_SIZE(format_desc); f++)

static const struct format_desc_struct *lookup_drm_format(uint32_t drm_format)
{
	const struct format_desc_struct *format;

	for_each_format(format) {
		if (format->drm_id != drm_format)
			continue;

		return format;
	}

	return NULL;
}

/**
 * igt_get_fb_tile_size:
 * @fd: the DRM file descriptor
 * @tiling: tiling layout of the framebuffer (as framebuffer modifier)
 * @fb_bpp: bits per pixel of the framebuffer
 * @width_ret: width of the tile in bytes
 * @height_ret: height of the tile in lines
 *
 * This function returns width and height of a tile based on the given tiling
 * format.
 */
void igt_get_fb_tile_size(int fd, uint64_t tiling, int fb_bpp,
			  unsigned *width_ret, unsigned *height_ret)
{
	uint32_t vc4_tiling_param = 0;

	if (is_vc4_device(fd)) {
		vc4_tiling_param = fourcc_mod_broadcom_param(tiling);
		tiling = fourcc_mod_broadcom_mod(tiling);
	}

	switch (tiling) {
	case LOCAL_DRM_FORMAT_MOD_NONE:
		if (is_i915_device(fd))
			*width_ret = 64;
		else
			*width_ret = 1;

		*height_ret = 1;
		break;
	case LOCAL_I915_FORMAT_MOD_X_TILED:
		igt_require_intel(fd);
		if (intel_gen(intel_get_drm_devid(fd)) == 2) {
			*width_ret = 128;
			*height_ret = 16;
		} else {
			*width_ret = 512;
			*height_ret = 8;
		}
		break;
	case LOCAL_I915_FORMAT_MOD_Y_TILED:
		igt_require_intel(fd);
		if (intel_gen(intel_get_drm_devid(fd)) == 2) {
			*width_ret = 128;
			*height_ret = 16;
		} else if (IS_915(intel_get_drm_devid(fd))) {
			*width_ret = 512;
			*height_ret = 8;
		} else {
			*width_ret = 128;
			*height_ret = 32;
		}
		break;
	case LOCAL_I915_FORMAT_MOD_Yf_TILED:
		igt_require_intel(fd);
		switch (fb_bpp) {
		case 8:
			*width_ret = 64;
			*height_ret = 64;
			break;
		case 16:
		case 32:
			*width_ret = 128;
			*height_ret = 32;
			break;
		case 64:
		case 128:
			*width_ret = 256;
			*height_ret = 16;
			break;
		default:
			igt_assert(false);
		}
		break;
	case DRM_FORMAT_MOD_BROADCOM_VC4_T_TILED:
		igt_require_vc4(fd);
		*width_ret = 128;
		*height_ret = 32;
		break;
	case DRM_FORMAT_MOD_BROADCOM_SAND32:
		igt_require_vc4(fd);
		*width_ret = 32;
		*height_ret = vc4_tiling_param;
		break;
	case DRM_FORMAT_MOD_BROADCOM_SAND64:
		igt_require_vc4(fd);
		*width_ret = 64;
		*height_ret = vc4_tiling_param;
		break;
	case DRM_FORMAT_MOD_BROADCOM_SAND128:
		igt_require_vc4(fd);
		*width_ret = 128;
		*height_ret = vc4_tiling_param;
		break;
	case DRM_FORMAT_MOD_BROADCOM_SAND256:
		igt_require_vc4(fd);
		*width_ret = 256;
		*height_ret = vc4_tiling_param;
		break;
	default:
		igt_assert(false);
	}
}

static unsigned fb_plane_width(const struct igt_fb *fb, int plane)
{
	const struct format_desc_struct *format = lookup_drm_format(fb->drm_format);

	if (plane == 0)
		return fb->width;

	return DIV_ROUND_UP(fb->width, format->hsub);
}

static unsigned fb_plane_bpp(const struct igt_fb *fb, int plane)
{
	const struct format_desc_struct *format = lookup_drm_format(fb->drm_format);

	return format->plane_bpp[plane];
}

static unsigned fb_plane_height(const struct igt_fb *fb, int plane)
{
	const struct format_desc_struct *format = lookup_drm_format(fb->drm_format);

	if (plane == 0)
		return fb->height;

	return DIV_ROUND_UP(fb->height, format->vsub);
}

static int fb_num_planes(const struct igt_fb *fb)
{
	const struct format_desc_struct *format = lookup_drm_format(fb->drm_format);

	return format->num_planes;
}

static void fb_init(struct igt_fb *fb,
		    int fd, int width, int height,
		    uint32_t drm_format,
		    uint64_t modifier,
		    enum igt_color_encoding color_encoding,
		    enum igt_color_range color_range)
{
	const struct format_desc_struct *f = lookup_drm_format(drm_format);

	igt_assert_f(f, "DRM format %08x not found\n", drm_format);

	memset(fb, 0, sizeof(*fb));

	fb->width = width;
	fb->height = height;
	fb->tiling = modifier;
	fb->drm_format = drm_format;
	fb->fd = fd;
	fb->num_planes = fb_num_planes(fb);
	fb->color_encoding = color_encoding;
	fb->color_range = color_range;

	for (int i = 0; i < fb->num_planes; i++) {
		fb->plane_bpp[i] = fb_plane_bpp(fb, i);
		fb->plane_height[i] = fb_plane_height(fb, i);
		fb->plane_width[i] = fb_plane_width(fb, i);
	}
}

static uint32_t calc_plane_stride(struct igt_fb *fb, int plane)
{
	uint32_t min_stride = fb->plane_width[plane] *
		(fb->plane_bpp[plane] / 8);

	if (fb->tiling != LOCAL_DRM_FORMAT_MOD_NONE &&
	    is_i915_device(fb->fd) &&
	    intel_gen(intel_get_drm_devid(fb->fd)) <= 3) {
		uint32_t stride;

		/* Round the tiling up to the next power-of-two and the region
		 * up to the next pot fence size so that this works on all
		 * generations.
		 *
		 * This can still fail if the framebuffer is too large to be
		 * tiled. But then that failure is expected.
		 */

		stride = max(min_stride, 512);
		stride = roundup_power_of_two(stride);

		return stride;
	} else {
		unsigned int tile_width, tile_height;

		igt_get_fb_tile_size(fb->fd, fb->tiling, fb->plane_bpp[plane],
				     &tile_width, &tile_height);

		return ALIGN(min_stride, tile_width);
	}
}

static uint64_t calc_plane_size(struct igt_fb *fb, int plane)
{
	if (fb->tiling != LOCAL_DRM_FORMAT_MOD_NONE &&
	    is_i915_device(fb->fd) &&
	    intel_gen(intel_get_drm_devid(fb->fd)) <= 3) {
		uint64_t min_size = (uint64_t) fb->strides[plane] *
			fb->plane_height[plane];
		uint64_t size;

		/* Round the tiling up to the next power-of-two and the region
		 * up to the next pot fence size so that this works on all
		 * generations.
		 *
		 * This can still fail if the framebuffer is too large to be
		 * tiled. But then that failure is expected.
		 */

		size = max(min_size, 1024*1024);
		size = roundup_power_of_two(size);

		return size;
	} else {
		unsigned int tile_width, tile_height;

		igt_get_fb_tile_size(fb->fd, fb->tiling, fb->plane_bpp[plane],
				     &tile_width, &tile_height);

		/* Special case where the "tile height" represents a
		 * height-based stride, such as with VC4 SAND tiling modes.
		 */

		if (tile_height > fb->plane_height[plane])
			return fb->strides[plane] * tile_height;

		return (uint64_t) fb->strides[plane] *
			ALIGN(fb->plane_height[plane], tile_height);
	}
}

static uint64_t calc_fb_size(struct igt_fb *fb)
{
	uint64_t size = 0;
	int plane;

	for (plane = 0; plane < fb->num_planes; plane++) {
		/* respect the stride requested by the caller */
		if (!fb->strides[plane])
			fb->strides[plane] = calc_plane_stride(fb, plane);

		fb->offsets[plane] = size;

		size += calc_plane_size(fb, plane);
	}

	return size;
}

/**
 * igt_calc_fb_size:
 * @fd: the DRM file descriptor
 * @width: width of the framebuffer in pixels
 * @height: height of the framebuffer in pixels
 * @format: drm fourcc pixel format code
 * @tiling: tiling layout of the framebuffer (as framebuffer modifier)
 * @size_ret: returned size for the framebuffer
 * @stride_ret: returned stride for the framebuffer
 *
 * This function returns valid stride and size values for a framebuffer with the
 * specified parameters.
 */
void igt_calc_fb_size(int fd, int width, int height, uint32_t drm_format, uint64_t tiling,
		      uint64_t *size_ret, unsigned *stride_ret)
{
	struct igt_fb fb;

	fb_init(&fb, fd, width, height, drm_format, tiling,
		IGT_COLOR_YCBCR_BT709, IGT_COLOR_YCBCR_LIMITED_RANGE);

	fb.size = calc_fb_size(&fb);

	if (size_ret)
		*size_ret = fb.size;
	if (stride_ret)
		*stride_ret = fb.strides[0];
}

/**
 * igt_fb_mod_to_tiling:
 * @modifier: DRM framebuffer modifier
 *
 * This function converts a DRM framebuffer modifier to its corresponding
 * tiling constant.
 *
 * Returns:
 * A tiling constant
 */
uint64_t igt_fb_mod_to_tiling(uint64_t modifier)
{
	switch (modifier) {
	case LOCAL_DRM_FORMAT_MOD_NONE:
		return I915_TILING_NONE;
	case LOCAL_I915_FORMAT_MOD_X_TILED:
		return I915_TILING_X;
	case LOCAL_I915_FORMAT_MOD_Y_TILED:
		return I915_TILING_Y;
	case LOCAL_I915_FORMAT_MOD_Yf_TILED:
		return I915_TILING_Yf;
	default:
		igt_assert(0);
	}
}

/**
 * igt_fb_tiling_to_mod:
 * @tiling: DRM framebuffer tiling
 *
 * This function converts a DRM framebuffer tiling to its corresponding
 * modifier constant.
 *
 * Returns:
 * A modifier constant
 */
uint64_t igt_fb_tiling_to_mod(uint64_t tiling)
{
	switch (tiling) {
	case I915_TILING_NONE:
		return LOCAL_DRM_FORMAT_MOD_NONE;
	case I915_TILING_X:
		return LOCAL_I915_FORMAT_MOD_X_TILED;
	case I915_TILING_Y:
		return LOCAL_I915_FORMAT_MOD_Y_TILED;
	case I915_TILING_Yf:
		return LOCAL_I915_FORMAT_MOD_Yf_TILED;
	default:
		igt_assert(0);
	}
}

static void clear_yuv_buffer(struct igt_fb *fb)
{
	bool full_range = fb->color_range == IGT_COLOR_YCBCR_FULL_RANGE;
	void *ptr;

	igt_assert(igt_format_is_yuv(fb->drm_format));

	/* Ensure the framebuffer is preallocated */
	ptr = igt_fb_map_buffer(fb->fd, fb);
	igt_assert(*(uint32_t *)ptr == 0);

	switch (fb->drm_format) {
	case DRM_FORMAT_NV12:
		memset(ptr + fb->offsets[0],
		       full_range ? 0x00 : 0x10,
		       fb->strides[0] * fb->plane_height[0]);
		memset(ptr + fb->offsets[1],
		       0x80,
		       fb->strides[1] * fb->plane_height[1]);
		break;
	case DRM_FORMAT_XYUV8888:
		wmemset(ptr + fb->offsets[0], full_range ? 0x00008080 : 0x00108080,
			fb->strides[0] * fb->plane_height[0] / sizeof(wchar_t));
		break;
	case DRM_FORMAT_YUYV:
	case DRM_FORMAT_YVYU:
		wmemset(ptr + fb->offsets[0],
			full_range ? 0x80008000 : 0x80108010,
			fb->strides[0] * fb->plane_height[0] / sizeof(wchar_t));
		break;
	case DRM_FORMAT_UYVY:
	case DRM_FORMAT_VYUY:
		wmemset(ptr + fb->offsets[0],
			full_range ? 0x00800080 : 0x10801080,
			fb->strides[0] * fb->plane_height[0] / sizeof(wchar_t));
		break;
	case DRM_FORMAT_P010:
	case DRM_FORMAT_P012:
	case DRM_FORMAT_P016:
		wmemset(ptr, full_range ? 0 : 0x10001000,
			fb->offsets[1] / sizeof(wchar_t));
		wmemset(ptr + fb->offsets[1], 0x80008000,
			fb->strides[1] * fb->plane_height[1] / sizeof(wchar_t));
		break;
	}

	igt_fb_unmap_buffer(fb, ptr);
}

/* helpers to create nice-looking framebuffers */
static int create_bo_for_fb(struct igt_fb *fb)
{
	const struct format_desc_struct *fmt = lookup_drm_format(fb->drm_format);
	unsigned int bpp = 0;
	unsigned int plane;
	unsigned *strides = &fb->strides[0];
	bool device_bo = false;
	int fd = fb->fd;
	uint64_t size;

	/*
	 * The current dumb buffer allocation API doesn't really allow to
	 * specify a custom size or stride. Yet the caller is free to specify
	 * them, so we need to make sure to use a device BO then.
	 */
	if (fb->tiling || fb->size || fb->strides[0] ||
	    (is_i915_device(fd) && igt_format_is_yuv(fb->drm_format)))
		device_bo = true;

	/* Sets offets and stride if necessary. */
	size = calc_fb_size(fb);

	/* Respect the size requested by the caller. */
	if (fb->size == 0)
		fb->size = size;

	if (device_bo) {
		fb->is_dumb = false;

		if (is_i915_device(fd)) {
			fb->gem_handle = gem_create(fd, fb->size);
			gem_set_tiling(fd, fb->gem_handle,
				       igt_fb_mod_to_tiling(fb->tiling),
				       fb->strides[0]);
		} else if (is_vc4_device(fd)) {
			fb->gem_handle = igt_vc4_create_bo(fd, fb->size);

			if (fb->tiling == DRM_FORMAT_MOD_BROADCOM_VC4_T_TILED)
				igt_vc4_set_tiling(fd, fb->gem_handle,
						   fb->tiling);
		} else {
			igt_assert(false);
		}

		goto out;
	}

	for (plane = 0; plane < fb->num_planes; plane++)
		bpp += DIV_ROUND_UP(fb->plane_bpp[plane],
				    plane ? fmt->hsub * fmt->vsub : 1);

	fb->is_dumb = true;

	/*
	 * We can't really pass the stride array here since the dumb
	 * buffer allocation is assuming that it operates on one
	 * plane, and therefore will calculate the stride as if each
	 * pixel was stored on a single plane.
	 *
	 * This might cause issues at some point on drivers that would
	 * change the stride of YUV buffers, but we haven't
	 * encountered any yet.
	 */
	if (fb->num_planes > 1)
		strides = NULL;

	fb->gem_handle = kmstest_dumb_create(fd, fb->width, fb->height,
					     bpp, strides, &fb->size);

out:
	if (igt_format_is_yuv(fb->drm_format))
		clear_yuv_buffer(fb);

	return fb->gem_handle;
}

/**
 * igt_create_bo_with_dimensions:
 * @fd: open drm file descriptor
 * @width: width of the buffer object in pixels
 * @height: height of the buffer object in pixels
 * @format: drm fourcc pixel format code
 * @modifier: modifier corresponding to the tiling layout of the buffer object
 * @stride: stride of the buffer object in bytes (0 for automatic stride)
 * @size_ret: size of the buffer object as created by the kernel
 * @stride_ret: stride of the buffer object as created by the kernel
 * @is_dumb: whether the created buffer object is a dumb buffer or not
 *
 * This function allocates a gem buffer object matching the requested
 * properties.
 *
 * Returns:
 * The kms id of the created buffer object.
 */
int igt_create_bo_with_dimensions(int fd, int width, int height,
				  uint32_t format, uint64_t modifier,
				  unsigned stride, uint64_t *size_ret,
				  unsigned *stride_ret, bool *is_dumb)
{
	struct igt_fb fb;

	fb_init(&fb, fd, width, height, format, modifier,
		IGT_COLOR_YCBCR_BT709, IGT_COLOR_YCBCR_LIMITED_RANGE);

	for (int i = 0; i < fb.num_planes; i++)
		fb.strides[i] = stride;

	create_bo_for_fb(&fb);

	if (size_ret)
		*size_ret = fb.size;
	if (stride_ret)
		*stride_ret = fb.strides[0];
	if (is_dumb)
		*is_dumb = fb.is_dumb;

	return fb.gem_handle;
}

/**
 * igt_paint_color:
 * @cr: cairo drawing context
 * @x: pixel x-coordination of the fill rectangle
 * @y: pixel y-coordination of the fill rectangle
 * @w: width of the fill rectangle
 * @h: height of the fill rectangle
 * @r: red value to use as fill color
 * @g: green value to use as fill color
 * @b: blue value to use as fill color
 *
 * This functions draws a solid rectangle with the given color using the drawing
 * context @cr.
 */
void igt_paint_color(cairo_t *cr, int x, int y, int w, int h,
		     double r, double g, double b)
{
	cairo_rectangle(cr, x, y, w, h);
	cairo_set_source_rgb(cr, r, g, b);
	cairo_fill(cr);
}

/**
 * igt_paint_color_alpha:
 * @cr: cairo drawing context
 * @x: pixel x-coordination of the fill rectangle
 * @y: pixel y-coordination of the fill rectangle
 * @w: width of the fill rectangle
 * @h: height of the fill rectangle
 * @r: red value to use as fill color
 * @g: green value to use as fill color
 * @b: blue value to use as fill color
 * @a: alpha value to use as fill color
 *
 * This functions draws a rectangle with the given color and alpha values using
 * the drawing context @cr.
 */
void igt_paint_color_alpha(cairo_t *cr, int x, int y, int w, int h,
			   double r, double g, double b, double a)
{
	cairo_rectangle(cr, x, y, w, h);
	cairo_set_source_rgba(cr, r, g, b, a);
	cairo_fill(cr);
}

/**
 * igt_paint_color_gradient:
 * @cr: cairo drawing context
 * @x: pixel x-coordination of the fill rectangle
 * @y: pixel y-coordination of the fill rectangle
 * @w: width of the fill rectangle
 * @h: height of the fill rectangle
 * @r: red value to use as fill color
 * @g: green value to use as fill color
 * @b: blue value to use as fill color
 *
 * This functions draws a gradient into the rectangle which fades in from black
 * to the given values using the drawing context @cr.
 */
void
igt_paint_color_gradient(cairo_t *cr, int x, int y, int w, int h,
			 int r, int g, int b)
{
	cairo_pattern_t *pat;

	pat = cairo_pattern_create_linear(x, y, x + w, y + h);
	cairo_pattern_add_color_stop_rgba(pat, 1, 0, 0, 0, 1);
	cairo_pattern_add_color_stop_rgba(pat, 0, r, g, b, 1);

	cairo_rectangle(cr, x, y, w, h);
	cairo_set_source(cr, pat);
	cairo_fill(cr);
	cairo_pattern_destroy(pat);
}

/**
 * igt_paint_color_gradient_range:
 * @cr: cairo drawing context
 * @x: pixel x-coordination of the fill rectangle
 * @y: pixel y-coordination of the fill rectangle
 * @w: width of the fill rectangle
 * @h: height of the fill rectangle
 * @sr: red value to use as start gradient color
 * @sg: green value to use as start gradient color
 * @sb: blue value to use as start gradient color
 * @er: red value to use as end gradient color
 * @eg: green value to use as end gradient color
 * @eb: blue value to use as end gradient color
 *
 * This functions draws a gradient into the rectangle which fades in
 * from one color to the other using the drawing context @cr.
 */
void
igt_paint_color_gradient_range(cairo_t *cr, int x, int y, int w, int h,
			       double sr, double sg, double sb,
			       double er, double eg, double eb)
{
	cairo_pattern_t *pat;

	pat = cairo_pattern_create_linear(x, y, x + w, y + h);
	cairo_pattern_add_color_stop_rgba(pat, 1, sr, sg, sb, 1);
	cairo_pattern_add_color_stop_rgba(pat, 0, er, eg, eb, 1);

	cairo_rectangle(cr, x, y, w, h);
	cairo_set_source(cr, pat);
	cairo_fill(cr);
	cairo_pattern_destroy(pat);
}

static void
paint_test_patterns(cairo_t *cr, int width, int height)
{
	double gr_height, gr_width;
	int x, y;

	y = height * 0.10;
	gr_width = width * 0.75;
	gr_height = height * 0.08;
	x = (width / 2) - (gr_width / 2);

	igt_paint_color_gradient(cr, x, y, gr_width, gr_height, 1, 0, 0);

	y += gr_height;
	igt_paint_color_gradient(cr, x, y, gr_width, gr_height, 0, 1, 0);

	y += gr_height;
	igt_paint_color_gradient(cr, x, y, gr_width, gr_height, 0, 0, 1);

	y += gr_height;
	igt_paint_color_gradient(cr, x, y, gr_width, gr_height, 1, 1, 1);
}

/**
 * igt_cairo_printf_line:
 * @cr: cairo drawing context
 * @align: text alignment
 * @yspacing: additional y-direction feed after this line
 * @fmt: format string
 * @...: optional arguments used in the format string
 *
 * This is a little helper to draw text onto framebuffers. All the initial setup
 * (like setting the font size and the moving to the starting position) still
 * needs to be done manually with explicit cairo calls on @cr.
 *
 * Returns:
 * The width of the drawn text.
 */
int igt_cairo_printf_line(cairo_t *cr, enum igt_text_align align,
				double yspacing, const char *fmt, ...)
{
	double x, y, xofs, yofs;
	cairo_text_extents_t extents;
	char *text;
	va_list ap;
	int ret;

	va_start(ap, fmt);
	ret = vasprintf(&text, fmt, ap);
	igt_assert(ret >= 0);
	va_end(ap);

	cairo_text_extents(cr, text, &extents);

	xofs = yofs = 0;
	if (align & align_right)
		xofs = -extents.width;
	else if (align & align_hcenter)
		xofs = -extents.width / 2;

	if (align & align_top)
		yofs = extents.height;
	else if (align & align_vcenter)
		yofs = extents.height / 2;

	cairo_get_current_point(cr, &x, &y);
	if (xofs || yofs)
		cairo_rel_move_to(cr, xofs, yofs);

	cairo_text_path(cr, text);
	cairo_set_source_rgb(cr, 0, 0, 0);
	cairo_stroke_preserve(cr);
	cairo_set_source_rgb(cr, 1, 1, 1);
	cairo_fill(cr);

	cairo_move_to(cr, x, y + extents.height + yspacing);

	free(text);

	return extents.width;
}

static void
paint_marker(cairo_t *cr, int x, int y)
{
	enum igt_text_align align;
	int xoff, yoff;

	cairo_move_to(cr, x, y - 20);
	cairo_line_to(cr, x, y + 20);
	cairo_move_to(cr, x - 20, y);
	cairo_line_to(cr, x + 20, y);
	cairo_new_sub_path(cr);
	cairo_arc(cr, x, y, 10, 0, M_PI * 2);
	cairo_set_line_width(cr, 4);
	cairo_set_source_rgb(cr, 0, 0, 0);
	cairo_stroke_preserve(cr);
	cairo_set_source_rgb(cr, 1, 1, 1);
	cairo_set_line_width(cr, 2);
	cairo_stroke(cr);

	xoff = x ? -20 : 20;
	align = x ? align_right : align_left;

	yoff = y ? -20 : 20;
	align |= y ? align_bottom : align_top;

	cairo_move_to(cr, x + xoff, y + yoff);
	cairo_set_font_size(cr, 18);
	igt_cairo_printf_line(cr, align, 0, "(%d, %d)", x, y);
}

/**
 * igt_paint_test_pattern:
 * @cr: cairo drawing context
 * @width: width of the visible area
 * @height: height of the visible area
 *
 * This functions draws an entire set of test patterns for the given visible
 * area using the drawing context @cr. This is useful for manual visual
 * inspection of displayed framebuffers.
 *
 * The test patterns include
 *  - corner markers to check for over/underscan and
 *  - a set of color and b/w gradients.
 */
void igt_paint_test_pattern(cairo_t *cr, int width, int height)
{
	paint_test_patterns(cr, width, height);

	cairo_set_line_cap(cr, CAIRO_LINE_CAP_SQUARE);

	/* Paint corner markers */
	paint_marker(cr, 0, 0);
	paint_marker(cr, width, 0);
	paint_marker(cr, 0, height);
	paint_marker(cr, width, height);

	igt_assert(!cairo_status(cr));
}

static cairo_status_t
stdio_read_func(void *closure, unsigned char* data, unsigned int size)
{
	if (fread(data, 1, size, (FILE*)closure) != size)
		return CAIRO_STATUS_READ_ERROR;

	return CAIRO_STATUS_SUCCESS;
}

cairo_surface_t *igt_cairo_image_surface_create_from_png(const char *filename)
{
	cairo_surface_t *image;
	FILE *f;

	f = igt_fopen_data(filename);
	image = cairo_image_surface_create_from_png_stream(&stdio_read_func, f);
	fclose(f);

	return image;
}

/**
 * igt_paint_image:
 * @cr: cairo drawing context
 * @filename: filename of the png image to draw
 * @dst_x: pixel x-coordination of the destination rectangle
 * @dst_y: pixel y-coordination of the destination rectangle
 * @dst_width: width of the destination rectangle
 * @dst_height: height of the destination rectangle
 *
 * This function can be used to draw a scaled version of the supplied png image,
 * which is loaded from the package data directory.
 */
void igt_paint_image(cairo_t *cr, const char *filename,
		     int dst_x, int dst_y, int dst_width, int dst_height)
{
	cairo_surface_t *image;
	int img_width, img_height;
	double scale_x, scale_y;

	image = igt_cairo_image_surface_create_from_png(filename);
	igt_assert(cairo_surface_status(image) == CAIRO_STATUS_SUCCESS);

	img_width = cairo_image_surface_get_width(image);
	img_height = cairo_image_surface_get_height(image);

	scale_x = (double)dst_width / img_width;
	scale_y = (double)dst_height / img_height;

	cairo_save(cr);

	cairo_translate(cr, dst_x, dst_y);
	cairo_scale(cr, scale_x, scale_y);
	cairo_set_source_surface(cr, image, 0, 0);
	cairo_paint(cr);

	cairo_surface_destroy(image);

	cairo_restore(cr);
}

/**
 * igt_create_fb_with_bo_size:
 * @fd: open i915 drm file descriptor
 * @width: width of the framebuffer in pixel
 * @height: height of the framebuffer in pixel
 * @format: drm fourcc pixel format code
 * @tiling: tiling layout of the framebuffer (as framebuffer modifier)
 * @fb: pointer to an #igt_fb structure
 * @bo_size: size of the backing bo (0 for automatic size)
 * @bo_stride: stride of the backing bo (0 for automatic stride)
 *
 * This function allocates a gem buffer object suitable to back a framebuffer
 * with the requested properties and then wraps it up in a drm framebuffer
 * object of the requested size. All metadata is stored in @fb.
 *
 * The backing storage of the framebuffer is filled with all zeros, i.e. black
 * for rgb pixel formats.
 *
 * Returns:
 * The kms id of the created framebuffer.
 */
unsigned int
igt_create_fb_with_bo_size(int fd, int width, int height,
			   uint32_t format, uint64_t tiling,
			   struct igt_fb *fb, uint64_t bo_size,
			   unsigned bo_stride)
{
	/* FIXME allow the caller to pass these in */
	enum igt_color_encoding color_encoding = IGT_COLOR_YCBCR_BT709;
	enum igt_color_range color_range = IGT_COLOR_YCBCR_LIMITED_RANGE;
	uint32_t flags = 0;

	fb_init(fb, fd, width, height, format, tiling,
		color_encoding, color_range);

	for (int i = 0; i < fb->num_planes; i++)
		fb->strides[i] = bo_stride;

	fb->size = bo_size;

	igt_debug("%s(width=%d, height=%d, format=0x%x, tiling=0x%"PRIx64", size=%"PRIu64")\n",
		  __func__, width, height, format, tiling, bo_size);

	create_bo_for_fb(fb);
	igt_assert(fb->gem_handle > 0);

	igt_debug("%s(handle=%d, pitch=%d)\n",
		  __func__, fb->gem_handle, fb->strides[0]);

	if (fb->tiling || igt_has_fb_modifiers(fd))
		flags = LOCAL_DRM_MODE_FB_MODIFIERS;

	do_or_die(__kms_addfb(fb->fd, fb->gem_handle,
			      fb->width, fb->height,
			      fb->drm_format, fb->tiling,
			      fb->strides, fb->offsets, fb->num_planes, flags,
			      &fb->fb_id));

	return fb->fb_id;
}

/**
 * igt_create_fb:
 * @fd: open i915 drm file descriptor
 * @width: width of the framebuffer in pixel
 * @height: height of the framebuffer in pixel
 * @format: drm fourcc pixel format code
 * @tiling: tiling layout of the framebuffer
 * @fb: pointer to an #igt_fb structure
 *
 * This function allocates a gem buffer object suitable to back a framebuffer
 * with the requested properties and then wraps it up in a drm framebuffer
 * object. All metadata is stored in @fb.
 *
 * The backing storage of the framebuffer is filled with all zeros, i.e. black
 * for rgb pixel formats.
 *
 * Returns:
 * The kms id of the created framebuffer.
 */
unsigned int igt_create_fb(int fd, int width, int height, uint32_t format,
			   uint64_t tiling, struct igt_fb *fb)
{
	return igt_create_fb_with_bo_size(fd, width, height, format, tiling, fb,
					  0, 0);
}

/**
 * igt_create_color_fb:
 * @fd: open i915 drm file descriptor
 * @width: width of the framebuffer in pixel
 * @height: height of the framebuffer in pixel
 * @format: drm fourcc pixel format code
 * @tiling: tiling layout of the framebuffer
 * @r: red value to use as fill color
 * @g: green value to use as fill color
 * @b: blue value to use as fill color
 * @fb: pointer to an #igt_fb structure
 *
 * This function allocates a gem buffer object suitable to back a framebuffer
 * with the requested properties and then wraps it up in a drm framebuffer
 * object. All metadata is stored in @fb.
 *
 * Compared to igt_create_fb() this function also fills the entire framebuffer
 * with the given color, which is useful for some simple pipe crc based tests.
 *
 * Returns:
 * The kms id of the created framebuffer on success or a negative error code on
 * failure.
 */
unsigned int igt_create_color_fb(int fd, int width, int height,
				 uint32_t format, uint64_t tiling,
				 double r, double g, double b,
				 struct igt_fb *fb /* out */)
{
	unsigned int fb_id;
	cairo_t *cr;

	fb_id = igt_create_fb(fd, width, height, format, tiling, fb);
	igt_assert(fb_id);

	cr = igt_get_cairo_ctx(fd, fb);
	igt_paint_color(cr, 0, 0, width, height, r, g, b);
	igt_put_cairo_ctx(fd, fb, cr);

	return fb_id;
}

/**
 * igt_create_pattern_fb:
 * @fd: open i915 drm file descriptor
 * @width: width of the framebuffer in pixel
 * @height: height of the framebuffer in pixel
 * @format: drm fourcc pixel format code
 * @tiling: tiling layout of the framebuffer
 * @fb: pointer to an #igt_fb structure
 *
 * This function allocates a gem buffer object suitable to back a framebuffer
 * with the requested properties and then wraps it up in a drm framebuffer
 * object. All metadata is stored in @fb.
 *
 * Compared to igt_create_fb() this function also draws the standard test pattern
 * into the framebuffer.
 *
 * Returns:
 * The kms id of the created framebuffer on success or a negative error code on
 * failure.
 */
unsigned int igt_create_pattern_fb(int fd, int width, int height,
				   uint32_t format, uint64_t tiling,
				   struct igt_fb *fb /* out */)
{
	unsigned int fb_id;
	cairo_t *cr;

	fb_id = igt_create_fb(fd, width, height, format, tiling, fb);
	igt_assert(fb_id);

	cr = igt_get_cairo_ctx(fd, fb);
	igt_paint_test_pattern(cr, width, height);
	igt_put_cairo_ctx(fd, fb, cr);

	return fb_id;
}

/**
 * igt_create_color_pattern_fb:
 * @fd: open i915 drm file descriptor
 * @width: width of the framebuffer in pixel
 * @height: height of the framebuffer in pixel
 * @format: drm fourcc pixel format code
 * @tiling: tiling layout of the framebuffer
 * @r: red value to use as fill color
 * @g: green value to use as fill color
 * @b: blue value to use as fill color
 * @fb: pointer to an #igt_fb structure
 *
 * This function allocates a gem buffer object suitable to back a framebuffer
 * with the requested properties and then wraps it up in a drm framebuffer
 * object. All metadata is stored in @fb.
 *
 * Compared to igt_create_fb() this function also fills the entire framebuffer
 * with the given color, and then draws the standard test pattern into the
 * framebuffer.
 *
 * Returns:
 * The kms id of the created framebuffer on success or a negative error code on
 * failure.
 */
unsigned int igt_create_color_pattern_fb(int fd, int width, int height,
					 uint32_t format, uint64_t tiling,
					 double r, double g, double b,
					 struct igt_fb *fb /* out */)
{
	unsigned int fb_id;
	cairo_t *cr;

	fb_id = igt_create_fb(fd, width, height, format, tiling, fb);
	igt_assert(fb_id);

	cr = igt_get_cairo_ctx(fd, fb);
	igt_paint_color(cr, 0, 0, width, height, r, g, b);
	igt_paint_test_pattern(cr, width, height);
	igt_put_cairo_ctx(fd, fb, cr);

	return fb_id;
}

/**
 * igt_create_image_fb:
 * @drm_fd: open i915 drm file descriptor
 * @width: width of the framebuffer in pixel or 0
 * @height: height of the framebuffer in pixel or 0
 * @format: drm fourcc pixel format code
 * @tiling: tiling layout of the framebuffer
 * @filename: filename of the png image to draw
 * @fb: pointer to an #igt_fb structure
 *
 * Create a framebuffer with the specified image. If @width is zero the
 * image width will be used. If @height is zero the image height will be used.
 *
 * Returns:
 * The kms id of the created framebuffer on success or a negative error code on
 * failure.
 */
unsigned int igt_create_image_fb(int fd, int width, int height,
				 uint32_t format, uint64_t tiling,
				 const char *filename,
				 struct igt_fb *fb /* out */)
{
	cairo_surface_t *image;
	uint32_t fb_id;
	cairo_t *cr;

	image = igt_cairo_image_surface_create_from_png(filename);
	igt_assert(cairo_surface_status(image) == CAIRO_STATUS_SUCCESS);
	if (width == 0)
		width = cairo_image_surface_get_width(image);
	if (height == 0)
		height = cairo_image_surface_get_height(image);
	cairo_surface_destroy(image);

	fb_id = igt_create_fb(fd, width, height, format, tiling, fb);

	cr = igt_get_cairo_ctx(fd, fb);
	igt_paint_image(cr, filename, 0, 0, width, height);
	igt_put_cairo_ctx(fd, fb, cr);

	return fb_id;
}

struct box {
	int x, y, width, height;
};

struct stereo_fb_layout {
	int fb_width, fb_height;
	struct box left, right;
};

static void box_init(struct box *box, int x, int y, int bwidth, int bheight)
{
	box->x = x;
	box->y = y;
	box->width = bwidth;
	box->height = bheight;
}


static void stereo_fb_layout_from_mode(struct stereo_fb_layout *layout,
				       drmModeModeInfo *mode)
{
	unsigned int format = mode->flags & DRM_MODE_FLAG_3D_MASK;
	const int hdisplay = mode->hdisplay, vdisplay = mode->vdisplay;
	int middle;

	switch (format) {
	case DRM_MODE_FLAG_3D_TOP_AND_BOTTOM:
		layout->fb_width = hdisplay;
		layout->fb_height = vdisplay;

		middle = vdisplay / 2;
		box_init(&layout->left, 0, 0, hdisplay, middle);
		box_init(&layout->right,
			 0, middle, hdisplay, vdisplay - middle);
		break;
	case DRM_MODE_FLAG_3D_SIDE_BY_SIDE_HALF:
		layout->fb_width = hdisplay;
		layout->fb_height = vdisplay;

		middle = hdisplay / 2;
		box_init(&layout->left, 0, 0, middle, vdisplay);
		box_init(&layout->right,
			 middle, 0, hdisplay - middle, vdisplay);
		break;
	case DRM_MODE_FLAG_3D_FRAME_PACKING:
	{
		int vactive_space = mode->vtotal - vdisplay;

		layout->fb_width = hdisplay;
		layout->fb_height = 2 * vdisplay + vactive_space;

		box_init(&layout->left,
			 0, 0, hdisplay, vdisplay);
		box_init(&layout->right,
			 0, vdisplay + vactive_space, hdisplay, vdisplay);
		break;
	}
	default:
		igt_assert(0);
	}
}

/**
 * igt_create_stereo_fb:
 * @drm_fd: open i915 drm file descriptor
 * @mode: A stereo 3D mode.
 * @format: drm fourcc pixel format code
 * @tiling: tiling layout of the framebuffer
 *
 * Create a framebuffer for use with the stereo 3D mode specified by @mode.
 *
 * Returns:
 * The kms id of the created framebuffer on success or a negative error code on
 * failure.
 */
unsigned int igt_create_stereo_fb(int drm_fd, drmModeModeInfo *mode,
				  uint32_t format, uint64_t tiling)
{
	struct stereo_fb_layout layout;
	cairo_t *cr;
	uint32_t fb_id;
	struct igt_fb fb;

	stereo_fb_layout_from_mode(&layout, mode);
	fb_id = igt_create_fb(drm_fd, layout.fb_width, layout.fb_height, format,
			      tiling, &fb);
	cr = igt_get_cairo_ctx(drm_fd, &fb);

	igt_paint_image(cr, "1080p-left.png",
			layout.left.x, layout.left.y,
			layout.left.width, layout.left.height);
	igt_paint_image(cr, "1080p-right.png",
			layout.right.x, layout.right.y,
			layout.right.width, layout.right.height);

	igt_put_cairo_ctx(drm_fd, &fb, cr);

	return fb_id;
}

static pixman_format_code_t drm_format_to_pixman(uint32_t drm_format)
{
	const struct format_desc_struct *f;

	for_each_format(f)
		if (f->drm_id == drm_format)
			return f->pixman_id;

	igt_assert_f(0, "can't find a pixman format for %08x (%s)\n",
		     drm_format, igt_format_str(drm_format));
}

static cairo_format_t drm_format_to_cairo(uint32_t drm_format)
{
	const struct format_desc_struct *f;

	for_each_format(f)
		if (f->drm_id == drm_format)
			return f->cairo_id;

	igt_assert_f(0, "can't find a cairo format for %08x (%s)\n",
		     drm_format, igt_format_str(drm_format));
}

struct fb_blit_linear {
	struct igt_fb fb;
	uint8_t *map;
};

struct fb_blit_upload {
	int fd;
	struct igt_fb *fb;
	struct fb_blit_linear linear;
};

static void blitcopy(const struct igt_fb *dst_fb,
		     const struct igt_fb *src_fb)
{
	igt_assert_eq(dst_fb->fd, src_fb->fd);
	igt_assert_eq(dst_fb->num_planes, src_fb->num_planes);

	for (int i = 0; i < dst_fb->num_planes; i++) {
		igt_assert_eq(dst_fb->plane_bpp[i], src_fb->plane_bpp[i]);
		igt_assert_eq(dst_fb->plane_width[i], src_fb->plane_width[i]);
		igt_assert_eq(dst_fb->plane_height[i], src_fb->plane_height[i]);

		igt_blitter_fast_copy__raw(dst_fb->fd,
					   src_fb->gem_handle,
					   src_fb->offsets[i],
					   src_fb->strides[i],
					   igt_fb_mod_to_tiling(src_fb->tiling),
					   0, 0, /* src_x, src_y */
					   dst_fb->plane_width[i], dst_fb->plane_height[i],
					   dst_fb->plane_bpp[i],
					   dst_fb->gem_handle,
					   dst_fb->offsets[i],
					   dst_fb->strides[i],
					   igt_fb_mod_to_tiling(dst_fb->tiling),
					   0, 0 /* dst_x, dst_y */);
	}
}

static void free_linear_mapping(struct fb_blit_upload *blit)
{
	int fd = blit->fd;
	struct igt_fb *fb = blit->fb;
	struct fb_blit_linear *linear = &blit->linear;

	gem_munmap(linear->map, linear->fb.size);
	gem_set_domain(fd, linear->fb.gem_handle,
		       I915_GEM_DOMAIN_GTT, 0);

	blitcopy(fb, &linear->fb);

	gem_sync(fd, linear->fb.gem_handle);
	gem_close(fd, linear->fb.gem_handle);
}

static void destroy_cairo_surface__blit(void *arg)
{
	struct fb_blit_upload *blit = arg;

	blit->fb->cairo_surface = NULL;

	free_linear_mapping(blit);

	free(blit);
}

static void setup_linear_mapping(int fd, struct igt_fb *fb, struct fb_blit_linear *linear)
{
	/*
	 * We create a linear BO that we'll map for the CPU to write to (using
	 * cairo). This linear bo will be then blitted to its final
	 * destination, tiling it at the same time.
	 */

	fb_init(&linear->fb, fb->fd, fb->width, fb->height,
		fb->drm_format, LOCAL_DRM_FORMAT_MOD_NONE,
		fb->color_encoding, fb->color_range);

	create_bo_for_fb(&linear->fb);

	igt_assert(linear->fb.gem_handle > 0);

	/* Copy fb content to linear BO */
	gem_set_domain(fd, linear->fb.gem_handle,
			I915_GEM_DOMAIN_GTT, 0);

	blitcopy(&linear->fb, fb);

	gem_sync(fd, linear->fb.gem_handle);

	gem_set_domain(fd, linear->fb.gem_handle,
		       I915_GEM_DOMAIN_CPU, I915_GEM_DOMAIN_CPU);

	/* Setup cairo context */
	linear->map = gem_mmap__cpu(fd, linear->fb.gem_handle,
				    0, linear->fb.size, PROT_READ | PROT_WRITE);
}

static void create_cairo_surface__blit(int fd, struct igt_fb *fb)
{
	struct fb_blit_upload *blit;
	cairo_format_t cairo_format;

	blit = malloc(sizeof(*blit));
	igt_assert(blit);

	blit->fd = fd;
	blit->fb = fb;
	setup_linear_mapping(fd, fb, &blit->linear);

	cairo_format = drm_format_to_cairo(fb->drm_format);
	fb->cairo_surface =
		cairo_image_surface_create_for_data(blit->linear.map,
						    cairo_format,
						    fb->width, fb->height,
						    blit->linear.fb.strides[0]);
	fb->domain = I915_GEM_DOMAIN_GTT;

	cairo_surface_set_user_data(fb->cairo_surface,
				    (cairo_user_data_key_t *)create_cairo_surface__blit,
				    blit, destroy_cairo_surface__blit);
}

/**
 * igt_dirty_fb:
 * @fd: open drm file descriptor
 * @fb: pointer to an #igt_fb structure
 *
 * Flushes out the whole framebuffer.
 *
 * Returns: 0 upon success.
 */
int igt_dirty_fb(int fd, struct igt_fb *fb)
{
	return drmModeDirtyFB(fb->fd, fb->fb_id, NULL, 0);
}

static void unmap_bo(struct igt_fb *fb, void *ptr)
{
	gem_munmap(ptr, fb->size);

	if (fb->is_dumb)
		igt_dirty_fb(fb->fd, fb);
}

static void destroy_cairo_surface__gtt(void *arg)
{
	struct igt_fb *fb = arg;

	unmap_bo(fb, cairo_image_surface_get_data(fb->cairo_surface));
	fb->cairo_surface = NULL;
}

static void *map_bo(int fd, struct igt_fb *fb)
{
	void *ptr;

	if (is_i915_device(fd))
		gem_set_domain(fd, fb->gem_handle,
			       I915_GEM_DOMAIN_GTT, I915_GEM_DOMAIN_GTT);

	if (fb->is_dumb)
		ptr = kmstest_dumb_map_buffer(fd, fb->gem_handle, fb->size,
					      PROT_READ | PROT_WRITE);
	else if (is_i915_device(fd))
		ptr = gem_mmap__gtt(fd, fb->gem_handle, fb->size,
				    PROT_READ | PROT_WRITE);
	else if (is_vc4_device(fd))
		ptr = igt_vc4_mmap_bo(fd, fb->gem_handle, fb->size,
				      PROT_READ | PROT_WRITE);
	else
		igt_assert(false);

	return ptr;
}

static void create_cairo_surface__gtt(int fd, struct igt_fb *fb)
{
	void *ptr = map_bo(fd, fb);

	fb->cairo_surface =
		cairo_image_surface_create_for_data(ptr,
						    drm_format_to_cairo(fb->drm_format),
						    fb->width, fb->height, fb->strides[0]);
	igt_require_f(cairo_surface_status(fb->cairo_surface) == CAIRO_STATUS_SUCCESS,
		      "Unable to create a cairo surface: %s\n",
		      cairo_status_to_string(cairo_surface_status(fb->cairo_surface)));

	fb->domain = I915_GEM_DOMAIN_GTT;

	cairo_surface_set_user_data(fb->cairo_surface,
				    (cairo_user_data_key_t *)create_cairo_surface__gtt,
				    fb, destroy_cairo_surface__gtt);
}

struct fb_convert_blit_upload {
	struct fb_blit_upload base;

	struct igt_fb shadow_fb;
	uint8_t *shadow_ptr;
};

static void *igt_fb_create_cairo_shadow_buffer(int fd,
					       unsigned drm_format,
					       unsigned int width,
					       unsigned int height,
					       struct igt_fb *shadow)
{
	void *ptr;

	igt_assert(shadow);

	fb_init(shadow, fd, width, height,
		drm_format, LOCAL_DRM_FORMAT_MOD_NONE,
		IGT_COLOR_YCBCR_BT709, IGT_COLOR_YCBCR_LIMITED_RANGE);

	shadow->strides[0] = ALIGN(width * shadow->plane_bpp[0], 16);
	shadow->size = ALIGN(shadow->strides[0] * height,
			     sysconf(_SC_PAGESIZE));
	ptr = mmap(NULL, shadow->size, PROT_READ | PROT_WRITE,
		   MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
	igt_assert(ptr != MAP_FAILED);

	return ptr;
}

static void igt_fb_destroy_cairo_shadow_buffer(struct igt_fb *shadow,
					       void *ptr)
{
	munmap(ptr, shadow->size);
}

static uint8_t clamprgb(float val)
{
	return clamp((int)(val + 0.5f), 0, 255);
}

static void read_rgb(struct igt_vec4 *rgb, const uint8_t *rgb24)
{
	rgb->d[0] = rgb24[2];
	rgb->d[1] = rgb24[1];
	rgb->d[2] = rgb24[0];
	rgb->d[3] = 1.0f;
}

static void write_rgb(uint8_t *rgb24, const struct igt_vec4 *rgb)
{
	rgb24[2] = clamprgb(rgb->d[0]);
	rgb24[1] = clamprgb(rgb->d[1]);
	rgb24[0] = clamprgb(rgb->d[2]);
}

struct fb_convert_buf {
	void			*ptr;
	struct igt_fb		*fb;
	bool                     slow_reads;
};

struct fb_convert {
	struct fb_convert_buf	dst;
	struct fb_convert_buf	src;
};

static void *convert_src_get(const struct fb_convert *cvt)
{
	void *buf;

	if (!cvt->src.slow_reads)
		return cvt->src.ptr;

	/*
	 * Reading from the BO is awfully slow because of lack of read caching,
	 * it's faster to copy the whole BO to a temporary buffer and convert
	 * from there.
	 */
	buf = malloc(cvt->src.fb->size);
	if (!buf)
		return cvt->src.ptr;

	igt_memcpy_from_wc(buf, cvt->src.ptr, cvt->src.fb->size);

	return buf;
}

static void convert_src_put(const struct fb_convert *cvt,
			    void *src_buf)
{
	if (src_buf != cvt->src.ptr)
		free(src_buf);
}

struct yuv_parameters {
	unsigned	y_inc;
	unsigned	uv_inc;
	unsigned	y_stride;
	unsigned	uv_stride;
	unsigned	y_offset;
	unsigned	u_offset;
	unsigned	v_offset;
};

static void get_yuv_parameters(struct igt_fb *fb, struct yuv_parameters *params)
{
	igt_assert(igt_format_is_yuv(fb->drm_format));

	switch (fb->drm_format) {
	case DRM_FORMAT_NV12:
	case DRM_FORMAT_NV16:
	case DRM_FORMAT_NV21:
	case DRM_FORMAT_NV61:
	case DRM_FORMAT_P010:
	case DRM_FORMAT_P012:
	case DRM_FORMAT_P016:
		params->y_inc = 1;
		params->uv_inc = 2;
		break;

	case DRM_FORMAT_YUV420:
	case DRM_FORMAT_YUV422:
	case DRM_FORMAT_YVU420:
	case DRM_FORMAT_YVU422:
		params->y_inc = 1;
		params->uv_inc = 1;
		break;

	case DRM_FORMAT_YUYV:
	case DRM_FORMAT_YVYU:
	case DRM_FORMAT_UYVY:
	case DRM_FORMAT_VYUY:
		params->y_inc = 2;
		params->uv_inc = 4;
		break;

	case DRM_FORMAT_XYUV8888:
		params->y_inc = 4;
		params->uv_inc = 4;
		break;
	}

	switch (fb->drm_format) {
	case DRM_FORMAT_NV12:
	case DRM_FORMAT_NV16:
	case DRM_FORMAT_NV21:
	case DRM_FORMAT_NV61:
	case DRM_FORMAT_YUV420:
	case DRM_FORMAT_YUV422:
	case DRM_FORMAT_YVU420:
	case DRM_FORMAT_YVU422:
	case DRM_FORMAT_P010:
	case DRM_FORMAT_P012:
	case DRM_FORMAT_P016:
		params->y_stride = fb->strides[0];
		params->uv_stride = fb->strides[1];
		break;

	case DRM_FORMAT_YUYV:
	case DRM_FORMAT_YVYU:
	case DRM_FORMAT_UYVY:
	case DRM_FORMAT_VYUY:
	case DRM_FORMAT_XYUV8888:
		params->y_stride = fb->strides[0];
		params->uv_stride = fb->strides[0];
		break;
	}

	switch (fb->drm_format) {
	case DRM_FORMAT_NV12:
	case DRM_FORMAT_NV16:
		params->y_offset = fb->offsets[0];
		params->u_offset = fb->offsets[1];
		params->v_offset = fb->offsets[1] + 1;
		break;

	case DRM_FORMAT_NV21:
	case DRM_FORMAT_NV61:
		params->y_offset = fb->offsets[0];
		params->u_offset = fb->offsets[1] + 1;
		params->v_offset = fb->offsets[1];
		break;

	case DRM_FORMAT_YUV420:
	case DRM_FORMAT_YUV422:
		params->y_offset = fb->offsets[0];
		params->u_offset = fb->offsets[1];
		params->v_offset = fb->offsets[2];
		break;

	case DRM_FORMAT_YVU420:
	case DRM_FORMAT_YVU422:
		params->y_offset = fb->offsets[0];
		params->u_offset = fb->offsets[2];
		params->v_offset = fb->offsets[1];
	case DRM_FORMAT_P010:
	case DRM_FORMAT_P012:
	case DRM_FORMAT_P016:
		params->y_offset = fb->offsets[0];
		params->u_offset = fb->offsets[1];
		params->v_offset = fb->offsets[1] + 2;
		break;

	case DRM_FORMAT_YUYV:
		params->y_offset = fb->offsets[0];
		params->u_offset = fb->offsets[0] + 1;
		params->v_offset = fb->offsets[0] + 3;
		break;

	case DRM_FORMAT_YVYU:
		params->y_offset = fb->offsets[0];
		params->u_offset = fb->offsets[0] + 3;
		params->v_offset = fb->offsets[0] + 1;
		break;

	case DRM_FORMAT_UYVY:
		params->y_offset = fb->offsets[0] + 1;
		params->u_offset = fb->offsets[0];
		params->v_offset = fb->offsets[0] + 2;
		break;

	case DRM_FORMAT_VYUY:
		params->y_offset = fb->offsets[0] + 1;
		params->u_offset = fb->offsets[0] + 2;
		params->v_offset = fb->offsets[0];
		break;

	case DRM_FORMAT_XYUV8888:
		params->y_offset = fb->offsets[0] + 1;
		params->u_offset = fb->offsets[0] + 2;
		params->v_offset = fb->offsets[0] + 3;
		break;
	}
}

static void convert_yuv_to_rgb24(struct fb_convert *cvt)
{
	const struct format_desc_struct *src_fmt =
		lookup_drm_format(cvt->src.fb->drm_format);
	int i, j;
	uint8_t bpp = 4;
	uint8_t *y, *u, *v;
	uint8_t *rgb24 = cvt->dst.ptr;
	unsigned int rgb24_stride = cvt->dst.fb->strides[0];
	struct igt_mat4 m = igt_ycbcr_to_rgb_matrix(cvt->src.fb->drm_format,
						    cvt->dst.fb->drm_format,
						    cvt->src.fb->color_encoding,
						    cvt->src.fb->color_range);
	uint8_t *buf;
	struct yuv_parameters params = { };

	igt_assert(cvt->dst.fb->drm_format == DRM_FORMAT_XRGB8888 &&
		   igt_format_is_yuv(cvt->src.fb->drm_format));

	buf = convert_src_get(cvt);
	get_yuv_parameters(cvt->src.fb, &params);
	y = buf + params.y_offset;
	u = buf + params.u_offset;
	v = buf + params.v_offset;

	for (i = 0; i < cvt->dst.fb->height; i++) {
		const uint8_t *y_tmp = y;
		const uint8_t *u_tmp = u;
		const uint8_t *v_tmp = v;
		uint8_t *rgb_tmp = rgb24;

		for (j = 0; j < cvt->dst.fb->width; j++) {
			struct igt_vec4 rgb, yuv;

			yuv.d[0] = *y_tmp;
			yuv.d[1] = *u_tmp;
			yuv.d[2] = *v_tmp;
			yuv.d[3] = 1.0f;

			rgb = igt_matrix_transform(&m, &yuv);
			write_rgb(rgb_tmp, &rgb);

			rgb_tmp += bpp;
			y_tmp += params.y_inc;

			if ((src_fmt->hsub == 1) || (j % src_fmt->hsub)) {
				u_tmp += params.uv_inc;
				v_tmp += params.uv_inc;
			}
		}

		rgb24 += rgb24_stride;
		y += params.y_stride;

		if ((src_fmt->vsub == 1) || (i % src_fmt->vsub)) {
			u += params.uv_stride;
			v += params.uv_stride;
		}
	}

	convert_src_put(cvt, buf);
}

static void convert_rgb24_to_yuv(struct fb_convert *cvt)
{
	const struct format_desc_struct *dst_fmt =
		lookup_drm_format(cvt->dst.fb->drm_format);
	int i, j;
	uint8_t *y, *u, *v;
	const uint8_t *rgb24 = cvt->src.ptr;
	uint8_t bpp = 4;
	unsigned rgb24_stride = cvt->src.fb->strides[0];
	struct igt_mat4 m = igt_rgb_to_ycbcr_matrix(cvt->src.fb->drm_format,
						    cvt->dst.fb->drm_format,
						    cvt->dst.fb->color_encoding,
						    cvt->dst.fb->color_range);
	struct yuv_parameters params = { };

	igt_assert(cvt->src.fb->drm_format == DRM_FORMAT_XRGB8888 &&
		   igt_format_is_yuv(cvt->dst.fb->drm_format));

	get_yuv_parameters(cvt->dst.fb, &params);
	y = cvt->dst.ptr + params.y_offset;
	u = cvt->dst.ptr + params.u_offset;
	v = cvt->dst.ptr + params.v_offset;

	for (i = 0; i < cvt->dst.fb->height; i++) {
		const uint8_t *rgb_tmp = rgb24;
		uint8_t *y_tmp = y;
		uint8_t *u_tmp = u;
		uint8_t *v_tmp = v;

		for (j = 0; j < cvt->dst.fb->width; j++) {
			const uint8_t *pair_rgb24 = rgb_tmp;
			struct igt_vec4 pair_rgb, rgb;
			struct igt_vec4 pair_yuv, yuv;

			read_rgb(&rgb, rgb_tmp);
			yuv = igt_matrix_transform(&m, &rgb);

			rgb_tmp += bpp;

			*y_tmp = yuv.d[0];
			y_tmp += params.y_inc;

			if ((i % dst_fmt->vsub) || (j % dst_fmt->hsub))
				continue;

			/*
			 * We assume the MPEG2 chroma siting convention, where
			 * pixel center for Cb'Cr' is between the left top and
			 * bottom pixel in a 2x2 block, so take the average.
			 *
			 * Therefore, if we use subsampling, we only really care
			 * about two pixels all the time, either the two
			 * subsequent pixels horizontally, vertically, or the
			 * two corners in a 2x2 block.
			 *
			 * The only corner case is when we have an odd number of
			 * pixels, but this can be handled pretty easily by not
			 * incrementing the paired pixel pointer in the
			 * direction it's odd in.
			 */
			if (j != (cvt->dst.fb->width - 1))
				pair_rgb24 += (dst_fmt->hsub - 1) * bpp;

			if (i != (cvt->dst.fb->height - 1))
				pair_rgb24 += rgb24_stride * (dst_fmt->vsub - 1);

			read_rgb(&pair_rgb, pair_rgb24);
			pair_yuv = igt_matrix_transform(&m, &pair_rgb);

			*u_tmp = (yuv.d[1] + pair_yuv.d[1]) / 2.0f;
			*v_tmp = (yuv.d[2] + pair_yuv.d[2]) / 2.0f;

			u_tmp += params.uv_inc;
			v_tmp += params.uv_inc;
		}

		rgb24 += rgb24_stride;
		y += params.y_stride;

		if ((i % dst_fmt->vsub) == (dst_fmt->vsub - 1)) {
			u += params.uv_stride;
			v += params.uv_stride;
		}
	}
}

static void read_rgbf(struct igt_vec4 *rgb, const float *rgb24)
{
	rgb->d[0] = rgb24[0];
	rgb->d[1] = rgb24[1];
	rgb->d[2] = rgb24[2];
	rgb->d[3] = 1.0f;
}

static void write_rgbf(float *rgb24, const struct igt_vec4 *rgb)
{
	rgb24[0] = rgb->d[0];
	rgb24[1] = rgb->d[1];
	rgb24[2] = rgb->d[2];
}

static void convert_yuv16_to_float(struct fb_convert *cvt)
{
	const struct format_desc_struct *src_fmt =
		lookup_drm_format(cvt->src.fb->drm_format);
	int i, j;
	uint8_t fpp = 3;
	uint16_t *y, *u, *v;
	float *ptr = cvt->dst.ptr;
	unsigned int float_stride = cvt->dst.fb->strides[0] / sizeof(*ptr);
	struct igt_mat4 m = igt_ycbcr_to_rgb_matrix(cvt->src.fb->drm_format,
						    cvt->dst.fb->drm_format,
						    cvt->src.fb->color_encoding,
						    cvt->src.fb->color_range);
	uint16_t *buf;
	struct yuv_parameters params = { };

	igt_assert(cvt->dst.fb->drm_format == IGT_FORMAT_FLOAT &&
		   igt_format_is_yuv(cvt->src.fb->drm_format));

	buf = convert_src_get(cvt);
	get_yuv_parameters(cvt->src.fb, &params);
	igt_assert(!(params.y_offset % sizeof(*buf)) &&
		   !(params.u_offset % sizeof(*buf)) &&
		   !(params.v_offset % sizeof(*buf)));

	y = buf + params.y_offset / sizeof(*buf);
	u = buf + params.u_offset / sizeof(*buf);
	v = buf + params.v_offset / sizeof(*buf);

	for (i = 0; i < cvt->dst.fb->height; i++) {
		const uint16_t *y_tmp = y;
		const uint16_t *u_tmp = u;
		const uint16_t *v_tmp = v;
		float *rgb_tmp = ptr;

		for (j = 0; j < cvt->dst.fb->width; j++) {
			struct igt_vec4 rgb, yuv;

			yuv.d[0] = *y_tmp;
			yuv.d[1] = *u_tmp;
			yuv.d[2] = *v_tmp;
			yuv.d[3] = 1.0f;

			rgb = igt_matrix_transform(&m, &yuv);
			write_rgbf(rgb_tmp, &rgb);

			rgb_tmp += fpp;
			y_tmp += params.y_inc;

			if ((src_fmt->hsub == 1) || (j % src_fmt->hsub)) {
				u_tmp += params.uv_inc;
				v_tmp += params.uv_inc;
			}
		}

		ptr += float_stride;
		y += params.y_stride / sizeof(*y);

		if ((src_fmt->vsub == 1) || (i % src_fmt->vsub)) {
			u += params.uv_stride / sizeof(*u);
			v += params.uv_stride / sizeof(*v);
		}
	}

	convert_src_put(cvt, buf);
}

static void convert_float_to_yuv16(struct fb_convert *cvt)
{
	const struct format_desc_struct *dst_fmt =
		lookup_drm_format(cvt->dst.fb->drm_format);
	int i, j;
	uint16_t *y, *u, *v;
	const float *ptr = cvt->src.ptr;
	uint8_t fpp = 3;
	unsigned float_stride = cvt->src.fb->strides[0] / sizeof(*ptr);
	struct igt_mat4 m = igt_rgb_to_ycbcr_matrix(cvt->src.fb->drm_format,
						    cvt->dst.fb->drm_format,
						    cvt->dst.fb->color_encoding,
						    cvt->dst.fb->color_range);
	struct yuv_parameters params = { };

	igt_assert(cvt->src.fb->drm_format == IGT_FORMAT_FLOAT &&
		   igt_format_is_yuv(cvt->dst.fb->drm_format));

	get_yuv_parameters(cvt->dst.fb, &params);
	igt_assert(!(params.y_offset % sizeof(*y)) &&
		   !(params.u_offset % sizeof(*u)) &&
		   !(params.v_offset % sizeof(*v)));

	y = cvt->dst.ptr + params.y_offset;
	u = cvt->dst.ptr + params.u_offset;
	v = cvt->dst.ptr + params.v_offset;

	for (i = 0; i < cvt->dst.fb->height; i++) {
		const float *rgb_tmp = ptr;
		uint16_t *y_tmp = y;
		uint16_t *u_tmp = u;
		uint16_t *v_tmp = v;

		for (j = 0; j < cvt->dst.fb->width; j++) {
			const float *pair_float = rgb_tmp;
			struct igt_vec4 pair_rgb, rgb;
			struct igt_vec4 pair_yuv, yuv;

			read_rgbf(&rgb, rgb_tmp);
			yuv = igt_matrix_transform(&m, &rgb);

			rgb_tmp += fpp;

			*y_tmp = yuv.d[0];
			y_tmp += params.y_inc;

			if ((i % dst_fmt->vsub) || (j % dst_fmt->hsub))
				continue;

			/*
			 * We assume the MPEG2 chroma siting convention, where
			 * pixel center for Cb'Cr' is between the left top and
			 * bottom pixel in a 2x2 block, so take the average.
			 *
			 * Therefore, if we use subsampling, we only really care
			 * about two pixels all the time, either the two
			 * subsequent pixels horizontally, vertically, or the
			 * two corners in a 2x2 block.
			 *
			 * The only corner case is when we have an odd number of
			 * pixels, but this can be handled pretty easily by not
			 * incrementing the paired pixel pointer in the
			 * direction it's odd in.
			 */
			if (j != (cvt->dst.fb->width - 1))
				pair_float += (dst_fmt->hsub - 1) * fpp;

			if (i != (cvt->dst.fb->height - 1))
				pair_float += float_stride * (dst_fmt->vsub - 1);

			read_rgbf(&pair_rgb, pair_float);
			pair_yuv = igt_matrix_transform(&m, &pair_rgb);

			*u_tmp = (yuv.d[1] + pair_yuv.d[1]) / 2.0f;
			*v_tmp = (yuv.d[2] + pair_yuv.d[2]) / 2.0f;

			u_tmp += params.uv_inc;
			v_tmp += params.uv_inc;
		}

		ptr += float_stride;
		y += params.y_stride / sizeof(*y);

		if ((i % dst_fmt->vsub) == (dst_fmt->vsub - 1)) {
			u += params.uv_stride / sizeof(*u);
			v += params.uv_stride / sizeof(*v);
		}
	}
}

static void convert_pixman(struct fb_convert *cvt)
{
	pixman_format_code_t src_pixman = drm_format_to_pixman(cvt->src.fb->drm_format);
	pixman_format_code_t dst_pixman = drm_format_to_pixman(cvt->dst.fb->drm_format);
	pixman_image_t *dst_image, *src_image;
	void *src_ptr;

	igt_assert((src_pixman != PIXMAN_invalid) &&
		   (dst_pixman != PIXMAN_invalid));

	/* Pixman requires the stride to be aligned to 32 bits. */
	igt_assert((cvt->src.fb->strides[0] % sizeof(uint32_t)) == 0);
	igt_assert((cvt->dst.fb->strides[0] % sizeof(uint32_t)) == 0);

	src_ptr = convert_src_get(cvt);

	src_image = pixman_image_create_bits(src_pixman,
					     cvt->src.fb->width,
					     cvt->src.fb->height,
					     src_ptr,
					     cvt->src.fb->strides[0]);
	igt_assert(src_image);

	dst_image = pixman_image_create_bits(dst_pixman,
					     cvt->dst.fb->width,
					     cvt->dst.fb->height,
					     cvt->dst.ptr,
					     cvt->dst.fb->strides[0]);
	igt_assert(dst_image);

	pixman_image_composite(PIXMAN_OP_SRC, src_image, NULL, dst_image,
			       0, 0, 0, 0, 0, 0,
			       cvt->dst.fb->width, cvt->dst.fb->height);
	pixman_image_unref(dst_image);
	pixman_image_unref(src_image);

	convert_src_put(cvt, src_ptr);
}

static void fb_convert(struct fb_convert *cvt)
{
	if ((drm_format_to_pixman(cvt->src.fb->drm_format) != PIXMAN_invalid) &&
	    (drm_format_to_pixman(cvt->dst.fb->drm_format) != PIXMAN_invalid)) {
		convert_pixman(cvt);
		return;
	} else if (cvt->dst.fb->drm_format == DRM_FORMAT_XRGB8888) {
		switch (cvt->src.fb->drm_format) {
		case DRM_FORMAT_XYUV8888:
		case DRM_FORMAT_NV12:
		case DRM_FORMAT_NV16:
		case DRM_FORMAT_NV21:
		case DRM_FORMAT_NV61:
		case DRM_FORMAT_UYVY:
		case DRM_FORMAT_VYUY:
		case DRM_FORMAT_YUV420:
		case DRM_FORMAT_YUV422:
		case DRM_FORMAT_YUYV:
		case DRM_FORMAT_YVU420:
		case DRM_FORMAT_YVU422:
		case DRM_FORMAT_YVYU:
			convert_yuv_to_rgb24(cvt);
			return;
		}
	} else if (cvt->src.fb->drm_format == DRM_FORMAT_XRGB8888) {
		switch (cvt->dst.fb->drm_format) {
		case DRM_FORMAT_XYUV8888:
		case DRM_FORMAT_NV12:
		case DRM_FORMAT_NV16:
		case DRM_FORMAT_NV21:
		case DRM_FORMAT_NV61:
		case DRM_FORMAT_UYVY:
		case DRM_FORMAT_VYUY:
		case DRM_FORMAT_YUV420:
		case DRM_FORMAT_YUV422:
		case DRM_FORMAT_YUYV:
		case DRM_FORMAT_YVU420:
		case DRM_FORMAT_YVU422:
		case DRM_FORMAT_YVYU:
			convert_rgb24_to_yuv(cvt);
			return;
		}
	} else if (cvt->dst.fb->drm_format == IGT_FORMAT_FLOAT) {
		switch (cvt->src.fb->drm_format) {
		case DRM_FORMAT_P010:
		case DRM_FORMAT_P012:
		case DRM_FORMAT_P016:
			convert_yuv16_to_float(cvt);
			return;
		}
	} else if (cvt->src.fb->drm_format == IGT_FORMAT_FLOAT) {
		switch (cvt->dst.fb->drm_format) {
		case DRM_FORMAT_P010:
		case DRM_FORMAT_P012:
		case DRM_FORMAT_P016:
			convert_float_to_yuv16(cvt);
			return;
		}
	}

	igt_assert_f(false,
		     "Conversion not implemented (from format 0x%x to 0x%x)\n",
		     cvt->src.fb->drm_format, cvt->dst.fb->drm_format);
}

static void destroy_cairo_surface__convert(void *arg)
{
	struct fb_convert_blit_upload *blit = arg;
	struct igt_fb *fb = blit->base.fb;
	struct fb_convert cvt = {
		.dst	= {
			.ptr	= blit->base.linear.map,
			.fb	= &blit->base.linear.fb,
		},

		.src	= {
			.ptr	= blit->shadow_ptr,
			.fb	= &blit->shadow_fb,
		},
	};

	fb_convert(&cvt);
	igt_fb_destroy_cairo_shadow_buffer(&blit->shadow_fb, blit->shadow_ptr);

	if (blit->base.linear.fb.gem_handle)
		free_linear_mapping(&blit->base);
	else
		unmap_bo(fb, blit->base.linear.map);

	free(blit);

	fb->cairo_surface = NULL;
}

static void create_cairo_surface__convert(int fd, struct igt_fb *fb)
{
	struct fb_convert_blit_upload *blit = malloc(sizeof(*blit));
	struct fb_convert cvt = { };
	const struct format_desc_struct *f = lookup_drm_format(fb->drm_format);
	unsigned drm_format;
	cairo_format_t cairo_id;

	if (f->cairo_id != CAIRO_FORMAT_INVALID) {
		cairo_id = f->cairo_id;

		switch (f->cairo_id) {
		case CAIRO_FORMAT_RGB96F:
		case CAIRO_FORMAT_RGBA128F:
			drm_format = IGT_FORMAT_FLOAT;
			break;
		case CAIRO_FORMAT_RGB24:
			drm_format = DRM_FORMAT_XRGB8888;
			break;
		default:
			igt_assert_f(0, "Unsupported format %u", f->cairo_id);
		}
	} else if (PIXMAN_FORMAT_A(f->pixman_id)) {
		cairo_id = CAIRO_FORMAT_ARGB32;
		drm_format = DRM_FORMAT_ARGB8888;
	} else {
		cairo_id = CAIRO_FORMAT_RGB24;
		drm_format = DRM_FORMAT_XRGB8888;
	}

	igt_assert(blit);

	blit->base.fd = fd;
	blit->base.fb = fb;
	blit->shadow_ptr = igt_fb_create_cairo_shadow_buffer(fd, drm_format,
							     fb->width,
							     fb->height,
							     &blit->shadow_fb);
	igt_assert(blit->shadow_ptr);

	if (fb->tiling == LOCAL_I915_FORMAT_MOD_Y_TILED ||
	    fb->tiling == LOCAL_I915_FORMAT_MOD_Yf_TILED) {
		setup_linear_mapping(fd, fb, &blit->base.linear);
	} else {
		blit->base.linear.fb = *fb;
		blit->base.linear.fb.gem_handle = 0;
		blit->base.linear.map = map_bo(fd, fb);
		igt_assert(blit->base.linear.map);

		/* reading via gtt mmap is slow */
		cvt.src.slow_reads = is_i915_device(fd);
	}

	cvt.dst.ptr = blit->shadow_ptr;
	cvt.dst.fb = &blit->shadow_fb;
	cvt.src.ptr = blit->base.linear.map;
	cvt.src.fb = &blit->base.linear.fb;
	fb_convert(&cvt);

	fb->cairo_surface =
		cairo_image_surface_create_for_data(blit->shadow_ptr,
						    cairo_id,
						    fb->width, fb->height,
						    blit->shadow_fb.strides[0]);

	cairo_surface_set_user_data(fb->cairo_surface,
				    (cairo_user_data_key_t *)create_cairo_surface__convert,
				    blit, destroy_cairo_surface__convert);
}


/**
 * igt_fb_map_buffer:
 * @fd: open drm file descriptor
 * @fb: pointer to an #igt_fb structure
 *
 * This function will creating a new mapping of the buffer and return a pointer
 * to the content of the supplied framebuffer's plane. This mapping needs to be
 * deleted using igt_fb_unmap_buffer().
 *
 * Returns:
 * A pointer to a buffer with the contents of the framebuffer
 */
void *igt_fb_map_buffer(int fd, struct igt_fb *fb)
{
	return map_bo(fd, fb);
}

/**
 * igt_fb_unmap_buffer:
 * @fb: pointer to the backing igt_fb structure
 * @buffer: pointer to the buffer previously mappped
 *
 * This function will unmap a buffer mapped previously with
 * igt_fb_map_buffer().
 */
void igt_fb_unmap_buffer(struct igt_fb *fb, void *buffer)
{
	return unmap_bo(fb, buffer);
}

/**
 * igt_get_cairo_surface:
 * @fd: open drm file descriptor
 * @fb: pointer to an #igt_fb structure
 *
 * This function stores the contents of the supplied framebuffer's plane
 * into a cairo surface and returns it.
 *
 * Returns:
 * A pointer to a cairo surface with the contents of the framebuffer.
 */
cairo_surface_t *igt_get_cairo_surface(int fd, struct igt_fb *fb)
{
	const struct format_desc_struct *f = lookup_drm_format(fb->drm_format);

	if (fb->cairo_surface == NULL) {
		if (igt_format_is_yuv(fb->drm_format) ||
		    ((f->cairo_id == CAIRO_FORMAT_INVALID) &&
		     (f->pixman_id != PIXMAN_invalid)))
			create_cairo_surface__convert(fd, fb);
		else if (fb->tiling == LOCAL_I915_FORMAT_MOD_Y_TILED ||
		    fb->tiling == LOCAL_I915_FORMAT_MOD_Yf_TILED)
			create_cairo_surface__blit(fd, fb);
		else
			create_cairo_surface__gtt(fd, fb);

		if (f->cairo_id == CAIRO_FORMAT_RGB96F ||
		    f->cairo_id == CAIRO_FORMAT_RGBA128F) {
			cairo_status_t status = cairo_surface_status(fb->cairo_surface);

			igt_skip_on_f(status == CAIRO_STATUS_INVALID_FORMAT &&
				      cairo_version() < CAIRO_VERSION_ENCODE(1, 17, 2),
				      "Cairo version too old, need 1.17.2, have %s\n",
				      cairo_version_string());

			igt_skip_on_f(status == CAIRO_STATUS_NO_MEMORY &&
				      pixman_version() < PIXMAN_VERSION_ENCODE(0, 36, 0),
				      "Pixman version too old, need 0.36.0, have %s\n",
				      pixman_version_string());
		}
	}

	igt_assert(cairo_surface_status(fb->cairo_surface) == CAIRO_STATUS_SUCCESS);
	return fb->cairo_surface;
}

/**
 * igt_get_cairo_ctx:
 * @fd: open i915 drm file descriptor
 * @fb: pointer to an #igt_fb structure
 *
 * This initializes a cairo surface for @fb and then allocates a drawing context
 * for it. The return cairo drawing context should be released by calling
 * igt_put_cairo_ctx(). This also sets a default font for drawing text on
 * framebuffers.
 *
 * Returns:
 * The created cairo drawing context.
 */
cairo_t *igt_get_cairo_ctx(int fd, struct igt_fb *fb)
{
	cairo_surface_t *surface;
	cairo_t *cr;

	surface = igt_get_cairo_surface(fd, fb);
	cr = cairo_create(surface);
	cairo_surface_destroy(surface);
	igt_assert(cairo_status(cr) == CAIRO_STATUS_SUCCESS);

	cairo_select_font_face(cr, "Helvetica", CAIRO_FONT_SLANT_NORMAL,
			       CAIRO_FONT_WEIGHT_NORMAL);
	igt_assert(cairo_status(cr) == CAIRO_STATUS_SUCCESS);

	return cr;
}

/**
 * igt_put_cairo_ctx:
 * @fd: open i915 drm file descriptor
 * @fb: pointer to an #igt_fb structure
 * @cr: the cairo context returned by igt_get_cairo_ctx.
 *
 * This releases the cairo surface @cr returned by igt_get_cairo_ctx()
 * for @fb, and writes the changes out to the framebuffer if cairo doesn't
 * have native support for the format.
 */
void igt_put_cairo_ctx(int fd, struct igt_fb *fb, cairo_t *cr)
{
	cairo_status_t ret = cairo_status(cr);
	igt_assert_f(ret == CAIRO_STATUS_SUCCESS, "Cairo failed to draw with %s\n", cairo_status_to_string(ret));

	cairo_destroy(cr);
}

/**
 * igt_remove_fb:
 * @fd: open i915 drm file descriptor
 * @fb: pointer to an #igt_fb structure
 *
 * This function releases all resources allocated in igt_create_fb() for @fb.
 * Note that if this framebuffer is still in use on a primary plane the kernel
 * will disable the corresponding crtc.
 */
void igt_remove_fb(int fd, struct igt_fb *fb)
{
	if (!fb || !fb->fb_id)
		return;

	cairo_surface_destroy(fb->cairo_surface);
	do_or_die(drmModeRmFB(fd, fb->fb_id));
	if (fb->is_dumb)
		kmstest_dumb_destroy(fd, fb->gem_handle);
	else
		gem_close(fd, fb->gem_handle);
	fb->fb_id = 0;
}

/**
 * igt_fb_convert_with_stride:
 * @dst: pointer to the #igt_fb structure that will store the conversion result
 * @src: pointer to the #igt_fb structure that stores the frame we convert
 * @dst_fourcc: DRM format specifier to convert to
 * @dst_modifier: DRM format modifier to convert to
 * @dst_stride: Stride for the resulting framebuffer (0 for automatic stride)
 *
 * This will convert a given @src content to the @dst_fourcc format,
 * storing the result in the @dst fb, allocating the @dst fb
 * underlying buffer with a stride of @dst_stride stride.
 *
 * Once done with @dst, the caller will have to call igt_remove_fb()
 * on it to free the associated resources.
 *
 * Returns:
 * The kms id of the created framebuffer.
 */
unsigned int igt_fb_convert_with_stride(struct igt_fb *dst, struct igt_fb *src,
					uint32_t dst_fourcc,
					uint64_t dst_modifier,
					unsigned int dst_stride)
{
	struct fb_convert cvt = { };
	void *dst_ptr, *src_ptr;
	int fb_id;

	fb_id = igt_create_fb_with_bo_size(src->fd, src->width, src->height,
					   dst_fourcc,
					   LOCAL_DRM_FORMAT_MOD_NONE, dst, 0,
					   dst_stride);
	igt_assert(fb_id > 0);

	src_ptr = igt_fb_map_buffer(src->fd, src);
	igt_assert(src_ptr);

	dst_ptr = igt_fb_map_buffer(dst->fd, dst);
	igt_assert(dst_ptr);

	cvt.dst.ptr = dst_ptr;
	cvt.dst.fb = dst;
	cvt.src.ptr = src_ptr;
	cvt.src.fb = src;
	fb_convert(&cvt);

	igt_fb_unmap_buffer(dst, dst_ptr);
	igt_fb_unmap_buffer(src, src_ptr);

	igt_assert(dst_modifier == LOCAL_DRM_FORMAT_MOD_NONE);

	return fb_id;
}

/**
 * igt_fb_convert:
 * @dst: pointer to the #igt_fb structure that will store the conversion result
 * @src: pointer to the #igt_fb structure that stores the frame we convert
 * @dst_fourcc: DRM format specifier to convert to
 * @dst_modifier: DRM format modifier to convert to
 *
 * This will convert a given @src content to the @dst_fourcc format,
 * storing the result in the @dst fb, allocating the @dst fb
 * underlying buffer.
 *
 * Once done with @dst, the caller will have to call igt_remove_fb()
 * on it to free the associated resources.
 *
 * Returns:
 * The kms id of the created framebuffer.
 */
unsigned int igt_fb_convert(struct igt_fb *dst, struct igt_fb *src,
			    uint32_t dst_fourcc, uint64_t dst_modifier)
{
	return igt_fb_convert_with_stride(dst, src, dst_fourcc, dst_modifier,
					  0);
}

/**
 * igt_bpp_depth_to_drm_format:
 * @bpp: desired bits per pixel
 * @depth: desired depth
 *
 * Returns:
 * The rgb drm fourcc pixel format code corresponding to the given @bpp and
 * @depth values.  Fails hard if no match was found.
 */
uint32_t igt_bpp_depth_to_drm_format(int bpp, int depth)
{
	const struct format_desc_struct *f;

	for_each_format(f)
		if (f->plane_bpp[0] == bpp && f->depth == depth)
			return f->drm_id;


	igt_assert_f(0, "can't find drm format with bpp=%d, depth=%d\n", bpp,
		     depth);
}

/**
 * igt_drm_format_to_bpp:
 * @drm_format: drm fourcc pixel format code
 *
 * Returns:
 * The bits per pixel for the given drm fourcc pixel format code. Fails hard if
 * no match was found.
 */
uint32_t igt_drm_format_to_bpp(uint32_t drm_format)
{
	const struct format_desc_struct *f = lookup_drm_format(drm_format);

	igt_assert_f(f, "can't find a bpp format for %08x (%s)\n",
		     drm_format, igt_format_str(drm_format));

	return f->plane_bpp[0];
}

/**
 * igt_format_str:
 * @drm_format: drm fourcc pixel format code
 *
 * Returns:
 * Human-readable fourcc pixel format code for @drm_format or "invalid" no match
 * was found.
 */
const char *igt_format_str(uint32_t drm_format)
{
	const struct format_desc_struct *f = lookup_drm_format(drm_format);

	return f ? f->name : "invalid";
}

/**
 * igt_fb_supported_format:
 * @drm_format: drm fourcc to test.
 *
 * This functions returns whether @drm_format can be succesfully created by
 * igt_create_fb() and drawn to by igt_get_cairo_ctx().
 */
bool igt_fb_supported_format(uint32_t drm_format)
{
	const struct format_desc_struct *f;

	for_each_format(f)
		if (f->drm_id == drm_format)
			return (f->cairo_id != CAIRO_FORMAT_INVALID) ||
				(f->pixman_id != PIXMAN_invalid);

	return false;
}

/**
 * igt_format_is_yuv:
 * @drm_format: drm fourcc
 *
 * This functions returns whether @drm_format is YUV (as opposed to RGB).
 */
bool igt_format_is_yuv(uint32_t drm_format)
{
	switch (drm_format) {
	case DRM_FORMAT_NV12:
	case DRM_FORMAT_NV16:
	case DRM_FORMAT_NV21:
	case DRM_FORMAT_NV61:
	case DRM_FORMAT_YUV420:
	case DRM_FORMAT_YUV422:
	case DRM_FORMAT_YVU420:
	case DRM_FORMAT_YVU422:
	case DRM_FORMAT_P010:
	case DRM_FORMAT_P012:
	case DRM_FORMAT_P016:
	case DRM_FORMAT_YUYV:
	case DRM_FORMAT_YVYU:
	case DRM_FORMAT_UYVY:
	case DRM_FORMAT_VYUY:
	case DRM_FORMAT_XYUV8888:
		return true;
	default:
		return false;
	}
}

/**
 * igt_format_plane_bpp:
 * @drm_format: drm fourcc
 * @plane: format plane index
 *
 * This functions returns the number of bits per pixel for the given @plane
 * index of the @drm_format.
 */
int igt_format_plane_bpp(uint32_t drm_format, int plane)
{
	const struct format_desc_struct *format =
		lookup_drm_format(drm_format);

	return format->plane_bpp[plane];
}

/**
 * igt_format_array_fill:
 * @formats_array: a pointer to the formats array pointer to be allocated
 * @count: a pointer to the number of elements contained in the allocated array
 * @allow_yuv: a boolean indicating whether YUV formats should be included
 *
 * This functions allocates and fills a @formats_array that lists the DRM
 * formats current available.
 */
void igt_format_array_fill(uint32_t **formats_array, unsigned int *count,
			   bool allow_yuv)
{
	const struct format_desc_struct *format;
	unsigned int index = 0;

	*count = 0;

	for_each_format(format) {
		if (!allow_yuv && igt_format_is_yuv(format->drm_id))
			continue;

		(*count)++;
	}

	*formats_array = calloc(*count, sizeof(uint32_t));
	igt_assert(*formats_array);

	for_each_format(format) {
		if (!allow_yuv && igt_format_is_yuv(format->drm_id))
			continue;

		(*formats_array)[index++] = format->drm_id;
	}
}