File: PsychScreenGlue.c

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

    PLATFORMS:

        This is the Linux version.
        It contains all code shared across Linux backends and
        the code for the non-Wayland backend - specifically for
        the X11 backend and the GBM+DRM/KMS backend, although
        the GBM backend is just a shim which doesn't do anything
        but prevent the beast from crashing.

    AUTHORS:

        Mario Kleiner       mk      mario.kleiner.de@gmail.com

    HISTORY:

        2/20/06             mk      Wrote it. Derived from Windows version.

    DESCRIPTION:

        Functions in this file comprise an abstraction layer for probing and controlling screen state.

        Each C function which implements a particular Screen subcommand should be platform neutral.  For example, the source to SCREENPixelSizes()
        should be platform-neutral, despite that the calls in OS X and Linux to detect available pixel sizes are
        different.  The platform specificity is abstracted out in C files which end it "Glue", for example PsychScreenGlue, PsychWindowGlue,
        PsychWindowTextClue.

        In addition to glue functions for windows and screen there are functions which implement shared functionality between between Screen commands,
        such as ScreenTypes.c and WindowBank.c.

*/

#include "Screen.h"

/* These are needed for our GPU specific beamposition query implementation: */
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/mman.h>

// To use libpciaccess for GPU device detection and mmaping():
#include "pciaccess.h"
#define PCI_CLASS_DISPLAY    0x03

// Maximum number of slots in a gamma table to set/query: This should be plenty.
#define MAX_GAMMALUT_SIZE 16384

// Defined in PsychGraphicsHardwareHALSupport.c, but accessed and initialized here:
extern unsigned int crtcoff[kPsychMaxPossibleCrtcs];

// If non-zero entries, then we are or have been running on Mesa
// and mesaversion encodes major.minor.patchlevel:
extern int mesaversion[3];

// Event and error base for XRandR extension:
int xr_event, xr_error;
psych_bool has_xrandr_1_2 = FALSE;
psych_bool has_xrandr_1_3 = FALSE;
psych_bool has_xrandr_1_4 = FALSE;

/* Following structures are needed by our ATI/AMD/NVIDIA beamposition query implementation: */
/* Location and format of the relevant hardware registers of the ATI R500/R600 chips
 * was taken from the official register spec for that chips which was released to
 * the public by AMD/ATI end of 2007 and is available for download at XOrg.
 *
 * http://www.x.org/docs/AMD/
 *
 * Register spec's for DCE-4 hardware are from Linux kms driver and Alex Deucher.
 * This should work on any AVIVO or DCE4/5 display hardware chip, i.e., R300 and
 * later. It won't work on ancient pre-AVIVO hardware.
 */

#include "PsychGraphicsCardRegisterSpecs.h"
#include <endian.h>

// gfx_cntl_mem is mapped to the actual device's memory mapped control area.
// Not the address but what it points to is volatile.
struct pci_device *gpu = NULL;
unsigned char * volatile gfx_cntl_mem = NULL;
unsigned long gfx_length = 0;
unsigned long gfx_lowlimit = 0;
unsigned int  fDeviceType = 0;
unsigned int  fCardType = 0;
unsigned int  fPCIDeviceId = 0;
unsigned int  fNumDisplayHeads = 0;
psych_bool    amdgpuUsesDisplayCore = FALSE;

// Minimum allowed physical crtc id for assignment to X-Screens. Used
// for the (x-screen, output) -> physical crtc id mapping heuristic
// for multi-x-screen ZaphodHead display setups:
static int    minimum_crtcid = 0;

// Count of kernel drivers:
static int    numKernelDrivers = 0;

// Internal helper function prototype:
void PsychInitNonX11(void);

/* Mappings up to date for January 2019 (last update e-mail patch / commit 2018-12-21). Would need updates for any commit after January 2019 */

static psych_bool isDCE12(int screenId)
{
    psych_bool isDCE12 = false;
    (void) screenId;

    // VEGA is DCE12:

    // VEGA10: 0x6860 - 0x687F
    if ((fPCIDeviceId & 0xFFF0) == 0x6860) isDCE12 = true;
    if ((fPCIDeviceId & 0xFFF0) == 0x6870) isDCE12 = true;

    // VEGA12: 0x69A0 - 0x69AF
    if ((fPCIDeviceId & 0xFFF0) == 0x69A0) isDCE12 = true;

    // VEGA20: 0x66A0 - 0x66AF
    if ((fPCIDeviceId & 0xFFF0) == 0x66A0) isDCE12 = true;

    return(isDCE12);
}

static psych_bool isDCE112(int screenId)
{
    psych_bool isDCE112 = false;
    (void) screenId;

    // POLARIS10/11/12 are DCE11.2. So is, oddly, VEGAM:

    // POLARIS10: 0x67C0 - 0x67DF and 0x6FDF
    if ((fPCIDeviceId & 0xFFF0) == 0x67C0) isDCE112 = true;
    if ((fPCIDeviceId & 0xFFF0) == 0x67D0) isDCE112 = true;
    if ((fPCIDeviceId & 0xFFFF) == 0x6FDF) isDCE112 = true;

    // POLARIS11: 0x67E0 - 0x67FF
    if ((fPCIDeviceId & 0xFFF0) == 0x67E0) isDCE112 = true;
    if ((fPCIDeviceId & 0xFFF0) == 0x67F0) isDCE112 = true;

    // POLARIS12: 0x6980 - 0x699F
    if ((fPCIDeviceId & 0xFFF0) == 0x6980) isDCE112 = true;
    if ((fPCIDeviceId & 0xFFF0) == 0x6990) isDCE112 = true;

    // VEGAM: 0x6940 - 0x694F
    if ((fPCIDeviceId & 0xFFF0) == 0x6940) isDCE112 = true;

    return(isDCE112);
}

/* Is a given ATI/AMD GPU a DCE11 type ASIC, i.e., with the new display engine? */
static psych_bool isDCE11(int screenId)
{
    psych_bool isDCE11 = false;

    (void) screenId;

    // CARRIZO and STONEY are DCE11.0 -- This is part of the "Volcanic Islands" GPU family.

    // CARRIZO: 0x987x so far.
    if ((fPCIDeviceId & 0xFFF0) == 0x9870) isDCE11 = true;

    // STONEY: 0x98E4 so far.
    if ((fPCIDeviceId & 0xFFFF) == 0x98E4) isDCE11 = true;

    if (isDCE112(screenId)) isDCE11 = true;

    // DCE12 can be treated as DCE11 for our purpose, as only the DCE-12 ip offset
    // has changed, not the register locations inside the block. We correct for the
    // offset in the setup code via dce_ip_offset.
    if (isDCE12(screenId)) isDCE11 = true;

    return(isDCE11);
}

/* Is a given ATI/AMD GPU a DCE10 type ASIC, i.e., with the new display engine? */
static psych_bool isDCE10(int screenId)
{
    psych_bool isDCE10 = false;

    (void) screenId;

    // TONGA and FIJI are DCE10 -- This is part of the "Volcanic Islands" GPU family.

    // TONGA: 0x692x - 0x693x so far.
    if ((fPCIDeviceId & 0xFFF0) == 0x6920) isDCE10 = true;
    if ((fPCIDeviceId & 0xFFF0) == 0x6930) isDCE10 = true;

    // FIJI is 0x7300 or 0x730F: Other 0x73's are NAVI and later ie. unsupported DCN's.
    if ((fPCIDeviceId & 0xFFFF) == 0x7300) isDCE10 = true;
    if ((fPCIDeviceId & 0xFFFF) == 0x730F) isDCE10 = true;

    // All DCE11 are also DCE10, so far...
    if (isDCE11(screenId)) isDCE10 = true;

    return(isDCE10);
}

static psych_bool isDCE81(int screenId)
{
    psych_bool isDCE81 = false;
    (void) screenId;

    // KAVERI in 0x13xx range:
    if ((fPCIDeviceId & 0xFF00) == 0x1300) isDCE81 = true;

    return(isDCE81);
}

static psych_bool isDCE82(int screenId)
{
    psych_bool isDCE82 = false;
    (void) screenId;

    // BONAIRE in 0x664x - 0x665x range:
    if ((fPCIDeviceId & 0xFFF0) == 0x6640) isDCE82 = true;
    if ((fPCIDeviceId & 0xFFF0) == 0x6650) isDCE82 = true;

    return(isDCE82);
}

static psych_bool isDCE85(int screenId)
{
    psych_bool isDCE85 = false;
    (void) screenId;

    // HAWAII in 0x67Ax - 0x67Bx range:
    if ((fPCIDeviceId & 0xFFF0) == 0x67A0) isDCE85 = true;
    if ((fPCIDeviceId & 0xFFF0) == 0x67B0) isDCE85 = true;

    return(isDCE85);
}

/* Is a given ATI/AMD GPU a DCE8 type ASIC, i.e., with the new display engine? */
static psych_bool isDCE8(int screenId)
{
    psych_bool isDCE8 = false;

    (void) screenId;

    // Everything >= BONAIRE is DCE8 -- This is part of the "Sea Islands" GPU family.

    // KABINI in 0x983x range:
    if ((fPCIDeviceId & 0xFFF0) == 0x9830) isDCE8 = true;

    // MULLINS in 0x985x range:
    if ((fPCIDeviceId & 0xFFF0) == 0x9850) isDCE8 = true;

    if (isDCE81(screenId)) isDCE8 = true;
    if (isDCE82(screenId)) isDCE8 = true;
    if (isDCE85(screenId)) isDCE8 = true;

    // CAUTION: DCE 10 and higher are *not* DCE8 as well!
    // These new parts have a different register layout, so
    // need separate code!

    return(isDCE8);
}

/* Is a given ATI/AMD GPU a DCE6.4 type ASIC, i.e., with the new display engine? */
static psych_bool isDCE64(int screenId)
{
    psych_bool isDCE64 = false;

    (void) screenId;

    // Everything == OLAND is DCE6.4 -- This is part of the "Southern Islands" GPU family.

    // OLAND in 0x66xx range:
    if ((fPCIDeviceId & 0xFF00) == 0x6600) isDCE64 = true;

    return(isDCE64);
}

/* Is a given ATI/AMD GPU a DCE6.1 type ASIC, i.e., with the new display engine? */
static psych_bool isDCE61(int screenId)
{
    psych_bool isDCE61 = false;

    (void) screenId;

    // Everything >= ARUBA which is an IGP is DCE6.1 -- This is the "Trinity" GPU family.

    // ARUBA in 0x99xx range: This is the "Trinity" chip family.
    if ((fPCIDeviceId & 0xFF00) == 0x9900) isDCE61 = true;

    // KAVERI in 0x13xx range:
    if ((fPCIDeviceId & 0xFF00) == 0x1300) isDCE61 = true;

    return(isDCE61);
}

/* Is a given ATI/AMD GPU a DCE6 type ASIC, i.e., with the new display engine? */
static psych_bool isDCE6(int screenId)
{
    psych_bool isDCE6 = false;

    // Everything >= ARUBA is DCE6 -- This is the "Southern Islands" GPU family.
    // First real DCE-6.0 is TAHITI in 0x678x - 0x679x range:
    if ((fPCIDeviceId & 0xFFF0) == 0x6780) isDCE6 = true;
    if ((fPCIDeviceId & 0xFFF0) == 0x6790) isDCE6 = true;

    // Then PITCAIRN, VERDE in 0x6800 - 0x683x range:
    if ((fPCIDeviceId & 0xFFF0) == 0x6800) isDCE6 = true;
    if ((fPCIDeviceId & 0xFFF0) == 0x6810) isDCE6 = true;
    if ((fPCIDeviceId & 0xFFF0) == 0x6820) isDCE6 = true;
    if ((fPCIDeviceId & 0xFFF0) == 0x6830) isDCE6 = true;

    // And one outlier PITCAIRN:
    if ((fPCIDeviceId & 0xFFFF) == 0x684c) isDCE6 = true;

    // Then HAINAN in the 0x666x range:
    if ((fPCIDeviceId & 0xFFF0) == 0x6660) isDCE6 = true;

    // All DCE-6.1 engines are also DCE-6:
    if (isDCE61(screenId)) isDCE6 = true;

    // All DCE-6.4 engines are also DCE-6:
    if (isDCE64(screenId)) isDCE6 = true;

    // All DCE-8 engines are also DCE-6:
    if (isDCE8(screenId)) isDCE6 = true;

    return(isDCE6);
}

/* Is a given ATI/AMD GPU a DCE5 type ASIC, i.e., with the new display engine? */
static psych_bool isDCE5(int screenId)
{
    psych_bool isDCE5 = false;

    // Everything after BARTS is DCE5 -- This is the "Northern Islands" GPU family.
    // Barts, Turks, Caicos, Cayman, Antilles in 0x67xx range:
    if ((fPCIDeviceId & 0xFF00) == 0x6700) isDCE5 = true;

    // More Turks ids:
    if ((fPCIDeviceId & 0xFFF0) == 0x6840) isDCE5 = true;
    if ((fPCIDeviceId & 0xFFF0) == 0x6850) isDCE5 = true;

    // All DCE-6 engines are also DCE-5:
    if (isDCE6(screenId)) isDCE5 = true;

    return(isDCE5);
}

/* Is a given ATI/AMD GPU a DCE-4.1 type ASIC, i.e., with the new display engine? */
static psych_bool isDCE41(int screenId)
{
    psych_bool isDCE41 = false;

    (void) screenId;

    // Everything after PALM which is an IGP is DCE-4.1
    // Currently these are Palm, Sumo and Sumo2.
    // DCE-4.1 is a real subset of DCE-4, with all its
    // functionality, except it only has 2 crtcs instead of 6.

    // Palm in 0x980x range:
    if ((fPCIDeviceId & 0xFFF0) == 0x9800) isDCE41 = true;

    // Sumo/Sumo2 in 0x964x range:
    if ((fPCIDeviceId & 0xFFF0) == 0x9640) isDCE41 = true;

    return(isDCE41);
}

/* Is a given ATI/AMD GPU a DCE4 type ASIC, i.e., with the new display engine? */
static psych_bool isDCE4(int screenId)
{
    psych_bool isDCE4 = false;

    // Everything after CEDAR is DCE4. The Linux radeon kms driver defines
    // in radeon_family.h which chips are CEDAR or later, and the mapping to
    // these chip codes is done by matching against pci device id's in a
    // mapping table inside linux/include/drm/drm_pciids.h
    // Mapping of chip codes to DCE-generations is in drm/radeon/radeon.h
    // Maintaining a copy of that table is impractical for PTB, so we simply
    // check which range of PCI device id's is covered by the DCE-4 chips and
    // code up matching rules here. This should do for now...

    // Caiman, Cedar, Redwood, Juniper, Cypress, Hemlock in 0x6xxx range:
    if ((fPCIDeviceId & 0xF000) == 0x6000) isDCE4 = true;

    // All DCE-4.1 engines are also DCE-4, except for lower crtc count:
    if (isDCE41(screenId)) isDCE4 = true;

    // All DCE-5 engines are also DCE-4:
    if (isDCE5(screenId)) isDCE4 = true;

    return(isDCE4);
}

static psych_bool isDCE3(int screenId)
{
    psych_bool isDCE3 = false;

    (void) screenId;

    // RV620, RV635, RS780, RS880, RV770, RV710, RV730, RV740,
    // aka roughly HD4330 - HD5165, HD5xxV, and some HD4000 parts.

    if ((fPCIDeviceId & 0xFFF0) == 0x9440) isDCE3 = true;
    if ((fPCIDeviceId & 0xFFF0) == 0x9450) isDCE3 = true;
    if ((fPCIDeviceId & 0xFFF0) == 0x9460) isDCE3 = true;
    if ((fPCIDeviceId & 0xFFF0) == 0x9470) isDCE3 = true;
    if ((fPCIDeviceId & 0xFFF0) == 0x9480) isDCE3 = true;
    if ((fPCIDeviceId & 0xFFF0) == 0x9490) isDCE3 = true;
    if ((fPCIDeviceId & 0xFFF0) == 0x94A0) isDCE3 = true;
    if ((fPCIDeviceId & 0xFFF0) == 0x94B0) isDCE3 = true;

    if ((fPCIDeviceId & 0xFFF0) == 0x9540) isDCE3 = true;
    if ((fPCIDeviceId & 0xFFF0) == 0x9550) isDCE3 = true;
    if ((fPCIDeviceId & 0xFFF0) == 0x9590) isDCE3 = true;
    if ((fPCIDeviceId & 0xFFF0) == 0x95C0) isDCE3 = true;

    if ((fPCIDeviceId & 0xFFF0) == 0x9610) isDCE3 = true;

    if ((fPCIDeviceId & 0xFFF0) == 0x9710) isDCE3 = true;

    return(isDCE3);
}

// DCE1/2 aka AVIVO is the earliest display hardware we support with
// our low-level trickery. Older hw uses the legacy display engines
// and is not supported at all by our mmio code:
static psych_bool isDCE1(int screenId)
{
    psych_bool isDCE1 = false;

    (void) screenId;

    if ((fPCIDeviceId & 0xFF00) == 0x7100) isDCE1 = true;
    if ((fPCIDeviceId & 0xFF00) == 0x7200) isDCE1 = true;
    if ((fPCIDeviceId & 0xFF00) == 0x7900) isDCE1 = true;

    if ((fPCIDeviceId & 0xFF00) == 0x9400) isDCE1 = true;
    if ((fPCIDeviceId & 0xFF00) == 0x9500) isDCE1 = true;
    if ((fPCIDeviceId & 0xFFF0) == 0x9610) isDCE1 = true;
    if ((fPCIDeviceId & 0xFFF0) == 0x9610) isDCE1 = true;
    if ((fPCIDeviceId & 0xFFF0) == 0x9710) isDCE1 = true;

    return(isDCE1);
}

// Helper routine: Read a single 32 bit unsigned int hardware register at
// offset 'offset' and return its value:
static unsigned int ReadRegister(unsigned long offset)
{
    unsigned int value;

    // Safety check: Don't allow reads past devices MMIO range:
    // We don't return error codes and don't log the problem,
    // because we could be called from primary Interrupt path, so IOLog() is not
    // an option!
    if (gfx_cntl_mem == NULL || offset > gfx_length-4 || offset < gfx_lowlimit) {
        if (PsychPrefStateGet_Verbosity() > 0)
            printf("PTB-ERROR: In GPU ReadRegister(): MMIO not mapped or reg offset %p out of range [%p - %p]! Nop zero return!\n", offset, gfx_lowlimit, gfx_length-4);
        return(0);
    }

    // Read and return value:
    value = *(unsigned int * volatile)(gfx_cntl_mem + offset);

    // Enforce a full memory barrier: This is a gcc intrinsic:
    __sync_synchronize();

    // Radeon: Don't know endianity behaviour: Play save, stick to LE assumption for now:
    if (fDeviceType == kPsychRadeon) return(le32toh(value));

    // Read the register in native byte order: At least NVidia GPU's adapt their
    // endianity to match the host systems endianity, so no need for conversion:
    if (fDeviceType == kPsychGeForce)  return(value);
    if (fDeviceType == kPsychIntelIGP) return(value);

    // No-Op return:
    if (PsychPrefStateGet_Verbosity() > 0) printf("PTB-ERROR: In GPU ReadRegister(): UNKNOWN fDeviceType of GPU! NO OPERATION!\n");
    return(0);
}

// Helper routine: Write a single 32 bit unsigned int hardware register at
// offset 'offset':
static void WriteRegister(unsigned long offset, unsigned int value)
{
    // Safety check: Don't allow reads past devices MMIO range:
    // We don't return error codes and don't log the problem,
    // because we could be called from primary Interrupt path, so IOLog() is not
    // an option!
    if (gfx_cntl_mem == NULL || offset > gfx_length-4 || offset < gfx_lowlimit) {
        if (PsychPrefStateGet_Verbosity() > 0)
            printf("PTB-ERROR: In GPU WriteRegister(): MMIO not mapped or reg offset %p out of range [%p - %p]! Nop zero return!\n", offset, gfx_lowlimit, gfx_length-4);
        return;
    }

    // Write the register in native byte order: At least NVidia GPU's adapt their
    // endianity to match the host systems endianity, so no need for conversion:
    if (fDeviceType == kPsychGeForce)  value = value;
    if (fDeviceType == kPsychIntelIGP) value = value;

    // Radeon: Don't know endianity behaviour: Play save, stick to LE assumption for now:
    if (fDeviceType == kPsychRadeon) value = htole32(value);

    *(unsigned int* volatile)(gfx_cntl_mem + offset) = value;

    // Enforce a full memory barrier: This is a gcc intrinsic:
    __sync_synchronize();
}

void PsychScreenUnmapDeviceMemory(void)
{
    // Any mapped?
    if (gfx_cntl_mem) {
        // Unmap:
        pci_device_unmap_range(gpu, (void*) gfx_cntl_mem, gfx_length);
        gfx_cntl_mem = NULL;
        gfx_length = 0;
        gpu = NULL;
        numKernelDrivers = 0;
        amdgpuUsesDisplayCore = FALSE;
    }

    // Shutdown PCI access library, release all resources:
    pci_system_cleanup();

    return;
}

// Helper routine: Check if a supported GPU is installed, and mmap() its MMIO register
// control block into our address space for direct register access:
psych_bool PsychScreenMapRadeonCntlMemory(void)
{
    struct pci_device_iterator *iter;
    struct pci_device *dev;
    struct pci_mem_region *region = NULL;
    int ret = 0;
    int screenId = 0;
    int currentgpuidx = 0, targetgpuidx = -1;
    psych_bool suppress_disclaimer = FALSE;

    // A bit of a hack for now: Allow user to select which gpu in a multi-gpu
    // system should be used for low-level mmio based features. If the environment
    // variable PSYCH_USE_GPUIDX is set to a number, it will try to use that GPU:
    // TODO: Replace this by true multi-gpu support and - far in the future? -
    // automatic mapping of screens to gpu's:
    if (getenv("PSYCH_USE_GPUIDX")) {
        targetgpuidx = atoi(getenv("PSYCH_USE_GPUIDX"));
        if (PsychPrefStateGet_Verbosity() > 2) printf("PTB-INFO: Will try to use GPU number %i for low-level access during this session.\n", targetgpuidx);
    }

    // Safe-guard:
    if (gfx_cntl_mem || gpu) {
        if (PsychPrefStateGet_Verbosity() > 1) printf("PTB-WARNING: Redundant call to PsychScreenMapRadeonCntlMemory()! Ignored for now. This should not happen!\n");
        return(TRUE);
    }

    // Start with default setting: No low-level access possible.
    amdgpuUsesDisplayCore = FALSE;
    gfx_cntl_mem = NULL;
    gfx_length = 0;
    gpu = NULL;

    // On ARM architecture system? If so, we assume it is a SoC without PCI bus, ergo no low-level PCI MMIO mapping/access:
    #if defined(__arm__) || defined(__thumb__) || defined(__aarch64__)
        if (PsychPrefStateGet_Verbosity() > 3) printf("PTB-INFO: Not using any low-level access to GPU, as this is an ARM SoC.\n");
        return(FALSE);
    #endif

    // Initialize libpciaccess:
    ret = pci_system_init();
    if (ret) {
        if (PsychPrefStateGet_Verbosity() > 1) printf("PTB-WARNING: Could not establish low-level access to GPU for screenId %i - Could not initialize PCI system.\n", screenId);
        return(FALSE);
    }

    // Enumerate them:
    iter = pci_id_match_iterator_create(NULL);
    while ((dev = pci_device_next(iter)) != NULL) {
        if (PsychPrefStateGet_Verbosity() > 4) {
            printf("PTB-DEBUG: Checking PCI device [%s %s] with class x%08x ...\n", pci_device_get_vendor_name(dev), pci_device_get_device_name(dev), dev->device_class);
        }

        // "Upgrade" pre PCI 2.0 class device to PCI 2.0 class equivalent
        // to simplify matching:
        if (dev->device_class == 0x00000101) dev->device_class = 0x00030000;

        // GPU aka display device class?
        if ((dev->device_class & 0x00ff0000) == (PCI_CLASS_DISPLAY << 16)) {
            // dev is our current candidate gpu. Matching vendor?
            if (dev->vendor_id == PCI_VENDOR_ID_NVIDIA || dev->vendor_id == PCI_VENDOR_ID_ATI || dev->vendor_id == PCI_VENDOR_ID_AMD || dev->vendor_id == PCI_VENDOR_ID_INTEL) {
                // Yes. This is our baby from NVidia or ATI/AMD or Intel:

                // From the land of bad hacks: Keep track early if we enumerated an Intel GPU, because
                // some KDE-specific hacks for override_redirect handling in window setup need to know
                // about running on an Intel IGP, even if we don't actually mmap() the gpu, and the hacks
                // need to know about this before we have an easy to probe OpenGL context online:
                if ((dev->vendor_id == PCI_VENDOR_ID_INTEL) && pci_device_is_boot_vga(dev)) fDeviceType = kPsychIntelIGP;

                // Get PCI device id early for dual-gpu PRIME handling:
                if (pci_device_is_boot_vga(dev)) fPCIDeviceId = dev->device_id;

                // Skip intel gpu's, unless the PSYCH_ALLOW_DANGEROUS env variable is set:
                // Intel IGP's have a design quirk which can cause machine hard lockup if multiple
                // regs are accessed simultaneously! As we can't serialize our MMIO reads with the
                // kms-driver, using our MMIO code on Intel is unsafe. Horrible crashes are reported
                // against Haswell on the freedesktop bug tracker for this issue.
                if ((dev->vendor_id == PCI_VENDOR_ID_INTEL) && !getenv("PSYCH_ALLOW_DANGEROUS")) {
                    if (PsychPrefStateGet_Verbosity() > 3) printf("PTB-INFO: Skipping detected Intel GPU for safety reasons. setenv('PSYCH_ALLOW_DANGEROUS', '1') to override.\n");
                    continue;
                }

                // Select the targetgpuidx'th detected gpu. If none is explicitely selected, use
                // the boot_vga gpu, which is the one and only gpu in a single gpu system, and the
                // active display gpu in a hybrid graphics laptop.
                //
                // TODO: Replace this hack by true multi-gpu support and - far in the future? -
                // automatic mapping of screens to gpu's:
                if (((targetgpuidx >= 0) && (currentgpuidx >= targetgpuidx)) || ((targetgpuidx < 0) && pci_device_is_boot_vga(dev))) {
                    if ((PsychPrefStateGet_Verbosity() > 2) && (targetgpuidx >= 0)) printf("PTB-INFO: Choosing GPU number %i for low-level access during this session.\n", currentgpuidx);

                    // Assign as gpu:
                    gpu = dev;
                    break;
                }

                currentgpuidx++;
            }
        }
    }

    // Enumeration finished - Release iterator:
    pci_iterator_destroy(iter);

    // Found matching GPU?
    if (gpu) {
        // Yes!
        if (PsychPrefStateGet_Verbosity() > 3) {
            printf("PTB-INFO: %s - %s GPU found. Trying to establish low-level access...\n", pci_device_get_vendor_name(gpu), pci_device_get_device_name(gpu));
            fflush(NULL);
        }

        // Need to zero-out errno to work around a bug in shipping libpciaccess.so versions prior June 2011 which would cause
        // pci_device_probe(gpu) to report failure even on success at every invocation after the 1st invocation.
        // See <http://cgit.freedesktop.org/xorg/lib/libpciaccess/commit/src/linux_sysfs.c?id=f9159b97834ba4b4e42a07953a33866e7ac90dbd>
        errno = 0;

        // Pull in remaining info about gpu:
        ret = pci_device_probe(gpu);
        if (ret) {
            if (PsychPrefStateGet_Verbosity() > 1) {
                printf("PTB-INFO: Could not probe properties of GPU for screenId %i [%s]\n", screenId, strerror(ret));
                printf("PTB-INFO: Beamposition timestamping and other special features disabled.\n");
                fflush(NULL);
            }

            gpu = NULL;

            // Cleanup:
            pci_system_cleanup();

            return(FALSE);
        }

        // Store PCI device id:
        fPCIDeviceId = gpu->device_id;

        // Find out which BAR to use for mapping MMIO registers. Depends on GPU vendor:
        if (gpu->vendor_id == PCI_VENDOR_ID_NVIDIA) {
            // BAR 0 is MMIO:
            region = &gpu->regions[0];
            fDeviceType = kPsychGeForce;
            fNumDisplayHeads = 2;
        }

        if (gpu->vendor_id == PCI_VENDOR_ID_ATI || gpu->vendor_id == PCI_VENDOR_ID_AMD) {
            // On Radeons we distinguish between Avivo / DCE-1/2 (10), DCE-3 (30), or DCE-4 style (40) or DCE-5 (50) or DCE-6 (60), DCE-8 (80), DCE-10 (100), DCE-11 (110), DCE-12 (120).
            // A values of 0 is assigned for pre DCE-1/AVIVO hardware, which we don't support at all for MMIO mapping tricks:
            fCardType = isDCE12(screenId) ? 120 : isDCE11(screenId) ? 110 : isDCE10(screenId) ? 100 : isDCE8(screenId) ? 80 : (isDCE6(screenId) ? 60 : (isDCE5(screenId) ? 50 : (isDCE4(screenId) ? 40 :
                        (isDCE3(screenId) ? 30 : isDCE1(screenId) ? 10 : 0))));

            fDeviceType = kPsychRadeon;
            fNumDisplayHeads = 2;

            // Supported DCE1+ ?
            if (fCardType > 0) {
                // BAR 2 is MMIO on old AMD gpus, BAR 5 is MMIO on DCE-8/10/11/... "Sea Islands" gpus and later models:
                region = &gpu->regions[(isDCE8(screenId) || isDCE10(screenId)) ? 5 : 2];
            }
            else {
                region = NULL;
                suppress_disclaimer = TRUE;
                if (PsychPrefStateGet_Verbosity() > 3)
                    printf("PTB-INFO: Unsupported AMD gpu for low-level access tricks, either it is a new DCN gpu, or unknown to us [pciid = 0x%x].\n", fPCIDeviceId);
            }
        }

        if (gpu->vendor_id == PCI_VENDOR_ID_INTEL) {
            // On non GEN-2 hardware, BAR 0 is MMIO:
            region = &gpu->regions[0];
            fCardType = 0;

            // On GEN-2 hardware, BAR 1 is MMIO: Detect known IGP's of GEN-2.
            if ((fPCIDeviceId == 0x3577) || (fPCIDeviceId == 0x2562) || (fPCIDeviceId == 0x3582) || (fPCIDeviceId == 0x358e) || (fPCIDeviceId == 0x2572)) {
                region = &gpu->regions[1];
                fCardType = 2;
            }

            fDeviceType = kPsychIntelIGP;

            // GEN-7+ (IvyBridge and later) and maybe GEN-6 (SandyBridge) has 3 display
            // heads, older IGP's have 2. Let's be optimistic and assume 3, to safe us
            // from lots of new detection code:
            fNumDisplayHeads = 3;
        }

        if (region) {
            // Try to MMAP MMIO registers with write access, assign their base address to gfx_cntl_mem on success:
            if (PsychPrefStateGet_Verbosity() > 4) {
                printf("PTB-DEBUG: Mapping GPU BAR address %p ...\n", region->base_addr);
                printf("PTB-DEBUG: Mapping %p bytes...\n", region->size);
                fflush(NULL);
            }

            // Read only is fine for anything but AMD, as we don't benefit from write access on other vendors gpus:
            // Note: MMIO access doesn't work anymore on Intel igp's since quite a while - at least Linux 4.4+.
            ret = pci_device_map_range(gpu, region->base_addr, region->size, (fDeviceType == kPsychRadeon) ? PCI_DEV_MAP_FLAG_WRITABLE : 0, (void**) &gfx_cntl_mem);
        }
        else {
            // Unsupported GPU type:
            gfx_cntl_mem = NULL;
            ret = 0;
        }

        if (ret || (NULL == gfx_cntl_mem)) {
            if (!suppress_disclaimer && (PsychPrefStateGet_Verbosity() > 1)) {
                printf("PTB-INFO: Failed to map GPU low-level control registers for screenId %i [%s].\n", screenId, strerror(ret));
                printf("PTB-INFO: Beamposition timestamping on NVidia and AMD gpu's, and other special functions on AMD gpu's, disabled.\n");
                if (fDeviceType != kPsychRadeon || fCardType > 0) {
                    printf("PTB-INFO: You need to run the setup script PsychLinuxConfiguration once, followed by a reboot, for this to work.\n");
                    printf("PTB-INFO: Additionally, on machines with EFI firmware, EFI secure boot must be disabled, or kernel lockdown lifted.\n");
                }
                printf("PTB-INFO: If you are using the open-source graphics drivers, then this usually doesn't matter for typical use.\n");
            }

            // Failed:
            gpu = NULL;

            // Cleanup:
            pci_system_cleanup();

            return(FALSE);
        }

        // Success! Identify GPU:
        gfx_length = region->size;

        // Lowest allowable MMIO register offset for given GPU:
        gfx_lowlimit = 0;

        if (fDeviceType == kPsychGeForce) {
            fCardType = PsychGetNVidiaGPUType(NULL);

            // GPU powered down and therefore offline? Signalled by special return code 0xffffffff.
            if (fCardType == 0xffffffff) {
                // Yes. This can happen in Optimus setups or other hybrid graphics setups.
                // Bail out of this GPU and cleanup:
                PsychScreenUnmapDeviceMemory();

                if (PsychPrefStateGet_Verbosity() > 2) printf("PTB-INFO: This NVidia GPU is powered down, probably in a Optimus setup. Skipping its use for beamposition timestamping.\n");

                // We are done.
                return(FALSE);
            }

            // NV-E0 "Kepler" and later have 4 display heads:
            if ((fCardType == 0x0) || (fCardType >= 0xe0)) fNumDisplayHeads = 4;

            if (PsychPrefStateGet_Verbosity() > 2) {
                printf("PTB-INFO: Connected to NVidia %s GPU of NV-%03x family with %i display heads.\n", pci_device_get_device_name(gpu), fCardType, fNumDisplayHeads);
                fflush(NULL);
            }
        }

        if (fDeviceType == kPsychRadeon) {
            // Setup for DCE-4/5/6/8:
            if (isDCE4(screenId) || isDCE5(screenId) || isDCE6(screenId) || isDCE8(screenId)) {
                gfx_lowlimit = 0;

                // Offset of crtc blocks of evergreen gpu's for each of the six possible crtc's:
                crtcoff[0] = EVERGREEN_CRTC0_REGISTER_OFFSET;
                crtcoff[1] = EVERGREEN_CRTC1_REGISTER_OFFSET;
                crtcoff[2] = EVERGREEN_CRTC2_REGISTER_OFFSET;
                crtcoff[3] = EVERGREEN_CRTC3_REGISTER_OFFSET;
                crtcoff[4] = EVERGREEN_CRTC4_REGISTER_OFFSET;
                crtcoff[5] = EVERGREEN_CRTC5_REGISTER_OFFSET;

                // Also, DCE-4 and DCE-5 and DCE-6, but not DCE-4.1 or DCE-6.4 (which have only 2) or DCE-6.1 (4 heads), supports up to six display heads:
                if (!isDCE41(screenId) && !isDCE61(screenId) && !isDCE64(screenId)) fNumDisplayHeads = 6;

                // DCE 8.2/8.5 have 6 display heads:
                if (isDCE82(screenId) || isDCE85(screenId)) fNumDisplayHeads = 6;

                // DCE-6.1 "Trinity" chip family supports 4 display heads:
                if (!isDCE41(screenId) && isDCE61(screenId)) fNumDisplayHeads = 4;

                // DCE-8.1 "Kaveri" supports 4 display heads:
                if (isDCE81(screenId)) fNumDisplayHeads = 4;
            }

            // Setup for DCE-10/11/12:
            if (isDCE10(screenId) || isDCE11(screenId) || isDCE12(screenId)) {
                unsigned int dce_ip_offset;

                // DCE-10/11/12 of the "Volcanic Islands" gpu family uses (mostly) the same register specs,
                // but the offsets for the different CRTC blocks are different wrt. to pre DCE-10. Therefore
                // need to initialize the offsets differently. Additionally, starting with DCE-12, the base
                // address of the DCE IP block inside the MMIO range has changed, compared to older DCE versions.
                // We use an additive offset dce_ip_offset to correct for the shift in IP block position.
                gfx_lowlimit = 0;

                // DCE-12.0 or later display engine?
                if (isDCE12(screenId)) {
                    // From the kernel file drivers/gpu/drm/amd/include/vega10_ip_offset.h, #define of
                    // DCE_BASE, DCE_BASE.instance[0].segment[reg##_BASE_IDX] with segment index 2 for
                    // registers we care about,ie. DCE_BASE.instance[0].segment[2] = 0x000034C0;
                    // (Reference: https://elixir.bootlin.com/linux/v5.0-rc4/source/drivers/gpu/drm/amd/include/vega10_ip_offset.h#L48)
                    //
                    // The base address of the DCE IP block has shifted in DCE-12 vs. older DCE's. Was implicitly
                    // 4-Bytes * 0x00002013, is now 4-Bytes * 0x000034C0:
                    dce_ip_offset = 0x000034C0 * 4;

                    // Offset of crtc blocks of Vega DCE-12 gpu's for each of the possible crtc's:
                    crtcoff[0] = DCE12_CRTC0_REGISTER_OFFSET + dce_ip_offset;
                    crtcoff[1] = DCE12_CRTC1_REGISTER_OFFSET + dce_ip_offset;
                    crtcoff[2] = DCE12_CRTC2_REGISTER_OFFSET + dce_ip_offset;
                    crtcoff[3] = DCE12_CRTC3_REGISTER_OFFSET + dce_ip_offset;
                    crtcoff[4] = DCE12_CRTC4_REGISTER_OFFSET + dce_ip_offset;
                    crtcoff[5] = DCE12_CRTC5_REGISTER_OFFSET + dce_ip_offset;

                    // Note that there is nothing preventing different DCE-12.x generations from having
                    // different DCE IP offsets, so dce_ip_offset would need to be defined by sub-gen!
                    // It just happens that so far we got lucky and as of February 2019, all DCE-12 ip
                    // of DCE12.0 and DCE12.1 seems to have the same offset.
                    // However, new Raven gpu's have a substantially redesigned display engine, called
                    // DCN, with potentially very different register layout and programming / operation /
                    // capabilites, requiring a big code rewrite in our support code. I think this won't
                    // happen, so DCE-12 might be the end of the road for our custom hacks.
                }
                else {
                    // Older than DCE-12. Implicit offset is 0x00002013 * 4 Bytes, but as we encode a delta to
                    // the implicit offset of pre DCE-12 in dce_ip_offset, the delta of < DCE-12 to itself is
                    // obviously 0x0:
                    dce_ip_offset = 0x0;

                    // Offset of crtc blocks of Volcanic Islands DCE-10/11 gpu's for each of the possible crtc's:
                    crtcoff[0] = DCE10_CRTC0_REGISTER_OFFSET + dce_ip_offset;
                    crtcoff[1] = DCE10_CRTC1_REGISTER_OFFSET + dce_ip_offset;
                    crtcoff[2] = DCE10_CRTC2_REGISTER_OFFSET + dce_ip_offset;
                    crtcoff[3] = DCE10_CRTC3_REGISTER_OFFSET + dce_ip_offset;
                    crtcoff[4] = DCE10_CRTC4_REGISTER_OFFSET + dce_ip_offset;
                    crtcoff[5] = DCE10_CRTC5_REGISTER_OFFSET + dce_ip_offset;
                    crtcoff[6] = DCE10_CRTC6_REGISTER_OFFSET + dce_ip_offset;
                }

                // DCE-10 has 6 display controllers:
                if (isDCE10(screenId)) fNumDisplayHeads = 6;

                // DCE-11.0 has 3 display controllers:
                if (isDCE11(screenId)) fNumDisplayHeads = 3;

                // DCE-11.2 has 6 display controllers:
                if (isDCE112(screenId)) fNumDisplayHeads = 6;

                // DCE-12 has 6 display controllers:
                if (isDCE12(screenId)) fNumDisplayHeads = 6;
            }

            if (PsychPrefStateGet_Verbosity() > 2) {
                printf("PTB-INFO: Connected to %s %s GPU with DCE-%.1f display engine [%i heads].\n", pci_device_get_vendor_name(gpu), pci_device_get_device_name(gpu), (float) fCardType / 10, fNumDisplayHeads);
                fflush(NULL);
            }
        }

        if (fDeviceType == kPsychIntelIGP) {
            if (PsychPrefStateGet_Verbosity() > 2) {
                printf("PTB-INFO: Connected to Intel %s GPU%s.\n", pci_device_get_device_name(gpu), (fCardType == 2) ? " of GEN-2 type" : "");
                fflush(NULL);
            }
        }

        // Perform auto-detection of screen to head mappings: This will no-op if users script
        // has already manually specified mappings via Screen('Preference','ScreenToHead', ...):
        // Also skip on Wayland and Waffle atm., as we need fast control of gamma tables for
        // auto-detection, which we currently don't have on Wayland and Waffle.
        #if !defined(PTB_USE_WAYLAND) && !defined(PTB_USE_WAFFLE)
        PsychAutoDetectScreenToHeadMappings(fNumDisplayHeads);
        #endif

        // Ready to rock!
    } else {
        // No candidate.
        if (PsychPrefStateGet_Verbosity() > 3) printf("PTB-INFO: No low-level controllable GPU on screenId %i. Beamposition timestamping and other special functions disabled.\n", screenId);
        fflush(NULL);

        // Cleanup:
        pci_system_cleanup();
    }

    // Keep track if something is mapped:
    if (gfx_cntl_mem) numKernelDrivers++;

    // Return final success or failure status:
    return((gfx_cntl_mem) ? TRUE : FALSE);
}

/*
 * Return identifying information about GPU for a given screen screenNumber:
 *
 * Returns TRUE on success, and the actual info in int variables, FALSE if info
 * not available:
 * Input: screenNumber of the screen for which to query GPU.
 *
 * Output: All optional - NULL == Don't return info.
 *
 * gpuMaintype = Basically what vendor.
 * gpuMinortype = Vendor specific id meaningful to us to define a certain class or generation of hardware.
 * pciDeviceId = The PCI device id.
 * numDisplayHeads = Maximum number of crtc's.
 *
 */
psych_bool PsychGetGPUSpecs(int screenNumber, int* gpuMaintype, int* gpuMinortype, int* pciDeviceId, int* numDisplayHeads)
{
  // Provide the basic device type, ie., unknown, intel, amd, ...
  if (gpuMaintype) *gpuMaintype = fDeviceType;
  if (pciDeviceId) *pciDeviceId = fPCIDeviceId;

  // Remaining info is only available for mapped gpu's:
  if (!PsychOSIsKernelDriverAvailable(screenNumber)) return(FALSE);

  if (gpuMinortype) *gpuMinortype = fCardType;
  if (numDisplayHeads) *numDisplayHeads = fNumDisplayHeads;

  return(TRUE);
}

// These are shared with display backend specific code, e.g., PsychScreenGlueWayland:
PsychScreenSettingsType     displayOriginalCGSettings[kPsychMaxPossibleDisplays];            //these track the original video state before the Psychtoolbox changed it.
psych_bool                  displayOriginalCGSettingsValid[kPsychMaxPossibleDisplays];
psych_bool                  displayCursorHidden[kPsychMaxPossibleDisplays];
CGDisplayCount              numDisplays;

// displayCGIDs stores the X11 Display* handles to the display connections of each PTB logical screen:
CGDirectDisplayID           displayCGIDs[kPsychMaxPossibleDisplays];

// Only used in this file:
static psych_bool           displayBeampositionHealthy[kPsychMaxPossibleDisplays];
static psych_bool           displayLockSettingsFlags[kPsychMaxPossibleDisplays];
// displayX11Screens stores the mapping of PTB screenNumber's to corresponding X11 screen numbers:
static int                  displayX11Screens[kPsychMaxPossibleDisplays];
static XRRScreenResources*  displayX11ScreenResources[kPsychMaxPossibleDisplays];
static Atom                 displayX11ScreenCompositionAtom[kPsychMaxPossibleDisplays];
static psych_bool           displayX11ScreenUsesModesettingDDX[kPsychMaxPossibleDisplays];

// XInput-2 extension data per display:
static int                  xi_opcode = 0, xi_event = 0, xi_error = 0;
static int                  xinput_ndevices[kPsychMaxPossibleDisplays];
static XIDeviceInfo*        xinput_info[kPsychMaxPossibleDisplays];

// File local functions:
void PsychLockScreenSettings(int screenNumber);
void PsychUnlockScreenSettings(int screenNumber);
psych_bool PsychCheckScreenSettingsLock(int screenNumber);
void InitPsychtoolboxKernelDriverInterface(void);

// X11 has a different - and much more powerful and flexible - concept of displays than OS-X or Windows:
// One can have multiple X11 connections to different logical displays. A logical display corresponds
// to a specific X-Server. This X-Server could run on the same machine as Matlab+PTB or on a different
// machine connected via network somewhere in the building or the world. A single machine can even run
// multiple X-Servers. Each display itself can consist of multiple screens. Each screen represents
// a single physical display device. E.g., a dual-head gfx-adaptor could be driven by a single X-Server and have
// two screens for each physical output. A single X-Server could also drive multiple different gfx-cards
// and therefore have many screens. A Linux render-cluster could consist of multiple independent machines,
// each with multiple screens aka gfx heads connected to each machine (aka X11 display).
//
// By default, PTB just connects to the same display as the one that Matlab is running on and tries to
// detect and enumerate all physical screens connected to that display. The default display is set either
// via Matlab command option "-display" or via the Shell environment variable $DISPLAY. Typically, it
// is simply $DISPLAY=:0.0, which means the local gfx-adaptor attached to the machine the user is logged into.
//
// If a user wants to make use of other displays than the one Matlab is running on, (s)he can set the
// environment variable $PSYCHTOOLBOX_DISPLAYS to a list of all requested displays. PTB will then try
// to connect to each of the listed displays, enumerate all attached screens and build its list of
// available screens as a merge of all screens of all displays.
// E.g., export PSYCHTOOLBOX_DISPLAYS=":0.0,kiwi.kyb.local:0.0,coriander.kyb.local:0.0" would enumerate
// all screens of all gfx-adaptors on the local machine ":0.0", and the network connected machines
// "kiwi.kyb.local" and "coriander.kyb.local".
//
// Possible applications: Multi-display setups on Linux, possibly across machines, e.g., render-clusters
// Weird experiments with special setups. Show stimulus on display 1, query mouse or keyboard from
// different machine...

static int x11_errorval = 0;
static int x11_errorbase = 0;
static int (*x11_olderrorhandler)(Display*, XErrorEvent*);

//file local functions
void InitCGDisplayIDList(void);

/* Lock graphics access
 *
 * This is mostly to protect access to XLib functions (and also GLX functions, as they
 * are using XLib/X11 as transport), but could also be used to protect access to other
 * backend libraries for display configuration and stimulus onset control.
 *
 * We use this as we don't want to rely on XLib's builtin locking and thread-safety.
 * Why? Because XLib's multi-threading protection must be initialized at application
 * startup time *before any other XLib calls* via a call to XInitThreads(), and we
 * do not have any control if or when that XInitThreads() call happens, so it is better
 * to not rely on Octave, Matlab or other future hosting environments doing the right
 * thing and implement our own locking around potentially racy XLib calls.
 *
 * XLib itself is reentrant, but concurrent access by multiple threads to the same xdisplay
 * connection handle, and thereby to the same x-windows connection queue is not safe.
 * We use one shared xdisplay handle for all onscreen windows and screens, across all of
 * Screen's threads (main thread and async flipper/frame-sequential stereo threads). We
 * need to use one shared handle because otherwise OpenGL context resource sharing and the
 * OML_sync_control timing and timestamping functions won't work properly. Therefore we
 * must lock-protect all calls by all threads to XLib. N.b. PsychHID uses its own private
 * xdisplay handle for its KbQueue thread, but that handle is really only used exclusively
 * by one thread, so no need to worry about locking that one.
 *
 * For now we only maintain a global lock and extend this into finer-grained locking if
 * neccessary. Using XCB would be another option, but that would be a huge rewrite with
 * rather sparse documentation available...
 */
psych_mutex displayLock;
double tLockDisplay;

void PsychLockDisplay(void)
{
    PsychLockMutex(&displayLock);

    if (PsychPrefStateGet_Verbosity() > 15) {
        printf("PTB-DEBUG: PsychLockDisplay(): Display locked!\n");
        fflush(NULL);
        PsychGetAdjustedPrecisionTimerSeconds(&tLockDisplay);
    }
}

void PsychUnlockDisplay(void)
{
    if (PsychPrefStateGet_Verbosity() > 15) {
        double tUnlockDisplay;
        PsychGetAdjustedPrecisionTimerSeconds(&tUnlockDisplay);
        printf("PTB-DEBUG: PsychUnlockDisplay(): Display unlocked! Lock hold time was %f msecs.\n", 1000 * (tUnlockDisplay - tLockDisplay));
        fflush(NULL);
    }

    PsychUnlockMutex(&displayLock);
}

int PsychGetXScreenIdForScreen(int screenNumber)
{
    if ((screenNumber >= numDisplays) || (screenNumber < 0)) PsychErrorExit(PsychError_invalidScumber);
    return(displayX11Screens[screenNumber]);
}

void PsychGetCGDisplayIDFromScreenNumber(CGDirectDisplayID *displayID, int screenNumber)
{
    if ((screenNumber >= numDisplays) || (screenNumber < 0)) PsychErrorExit(PsychError_invalidScumber);
    *displayID=displayCGIDs[screenNumber];
}

/*  About locking display settings:
 *
 *    SCREENOpenWindow and SCREENOpenOffscreenWindow  set the lock when opening  windows and
 *    SCREENCloseWindow unsets upon the close of the last of a screen's windows. PsychSetVideoSettings checks for a lock
 *    before changing the settings.  Anything (SCREENOpenWindow or SCREENResolutions) which attemps to change
 *    the display settings should report that attempts to change a dipslay's settings are not allowed when its windows are open.
 *
 *    PsychSetVideoSettings() may be called by either SCREENOpenWindow or by Resolutions().  If called by Resolutions it both sets the video settings
 *    and caches the video settings so that subsequent calls to OpenWindow can use the cached mode regardless of whether interceding calls to OpenWindow
 *    have changed the display settings or reverted to the virgin display settings by closing.  SCREENOpenWindow should thus invoke the cached mode
 *    settings if they have been specified and not current actual display settings.
 *
 */
void PsychLockScreenSettings(int screenNumber)
{
    displayLockSettingsFlags[screenNumber]=TRUE;
}

void PsychUnlockScreenSettings(int screenNumber)
{
    displayLockSettingsFlags[screenNumber]=FALSE;
}

psych_bool PsychCheckScreenSettingsLock(int screenNumber)
{
    return(displayLockSettingsFlags[screenNumber]);
}

/* Because capture and lock will always be used in conjuction, capture calls lock, and SCREENOpenWindow must only call Capture and Release */
void PsychCaptureScreen(int screenNumber)
{
    if(screenNumber>=numDisplays) PsychErrorExit(PsychError_invalidScumber);
    PsychLockScreenSettings(screenNumber);
}

/*
 *    PsychReleaseScreen()
 */
void PsychReleaseScreen(int screenNumber)
{
    if(screenNumber>=numDisplays) PsychErrorExit(PsychError_invalidScumber);
    PsychUnlockScreenSettings(screenNumber);
}

psych_bool PsychIsScreenCaptured(int screenNumber)
{
    return(PsychCheckScreenSettingsLock(screenNumber));
}

//Read display parameters.
/*
 *    PsychGetNumDisplays()
 *    Get the number of video displays connected to the system.
 */
int PsychGetNumDisplays(void)
{
    return((int) numDisplays);
}

//Initialization functions
void InitializePsychDisplayGlue(void)
{
    static psych_bool firstTime = TRUE;
    int i;

    //init the display settings flags.
    for(i = 0; i < kPsychMaxPossibleDisplays; i++) {
        displayLockSettingsFlags[i]=FALSE;
        displayOriginalCGSettingsValid[i]=FALSE;
        displayCursorHidden[i]=FALSE;
        displayBeampositionHealthy[i]=TRUE;
        displayX11ScreenResources[i] = NULL;
        displayX11ScreenCompositionAtom[i] = None;
        displayX11ScreenUsesModesettingDDX[i] = FALSE;
        xinput_ndevices[i]=0;
        xinput_info[i]=NULL;
    }

    has_xrandr_1_2 = FALSE;
    has_xrandr_1_3 = FALSE;
    has_xrandr_1_4 = FALSE;

    // Set Mesa version to undefined:
    mesaversion[0] = mesaversion[1] = mesaversion[2] = 0;

    // Initialize our mutex for locking of display function access, e.g., XLib/GLX calls:
    PsychInitMutex(&displayLock);

    if (firstTime) {
        firstTime = FALSE;

        #ifndef PTB_USE_WAYLAND
        // If the X11 windowing system is used in this session, then we must initialize XLib for
        // multithreading-safe operations / access on first call if ...
        // - Usercode explicitely requests this via environment variable PSYCH_XINITTHREADS,
        // - Or if our host process hasn't done proper setup itself and it is safe for us to do it.
        // We can only do this if PsychOSNeedXInitThreads() deems it needed and safe, as XInitThreads()
        // must be called as very first XLib function after process startup or bad things may happen!
        // Testing shows that Matlab always calls XInitThreads() itself properly, and octave as well,
        // if called as "octave" and not "octave-cli". "octave-cli --no-window-system allows us to
        // work around this, but octave-cli is seldomly (ever?) used for use with Psychtoolbox.
        // In practice this is mostly to work around unsuitable Python runtimes/host applications
        // atm., should Screen() get ported to Python:
        if ((getenv("DISPLAY") || getenv("PSYCHTOOLBOX_DISPLAYS")) && PsychOSNeedXInitThreads(PsychPrefStateGet_Verbosity()))
            XInitThreads();
        #endif
    }

    //init the list of Core Graphics display IDs.
    InitCGDisplayIDList();

    // Attach to kernel-level Psychtoolbox graphics card interface driver if possible
    // *and* allowed by settings, setup all relevant mappings:
    InitPsychtoolboxKernelDriverInterface();
}

int PsychGetScreenDepthValue(int screenNumber)
{
    PsychDepthType    depthStruct;

    PsychInitDepthStruct(&depthStruct);
    PsychGetScreenDepth(screenNumber, &depthStruct);
    return(PsychGetValueFromDepthStruct(0,&depthStruct));
}

/*
 *    PsychGetScreenSettings()
 *
 *    Fills a structure describing the screen settings such as x, y, depth, frequency, etc.
 *
 *    Consider inverting the calling sequence so that this function is at the bottom of call hierarchy.
 */
void PsychGetScreenSettings(int screenNumber, PsychScreenSettingsType *settings)
{
    settings->screenNumber=screenNumber;
    PsychGetScreenRect(screenNumber, settings->rect);
    PsychInitDepthStruct(&(settings->depth));
    PsychGetScreenDepth(screenNumber, &(settings->depth));
    settings->mode=PsychGetColorModeFromDepthStruct(&(settings->depth));
    settings->nominalFrameRate= (int) (PsychGetNominalFramerate(screenNumber) + 0.5);
    //settings->dacbits=PsychGetDacBits(screenNumber);
}

PsychColorModeType PsychGetScreenMode(int screenNumber)
{
    PsychDepthType depth;

    PsychInitDepthStruct(&depth);
    PsychGetScreenDepth(screenNumber, &depth);
    return(PsychGetColorModeFromDepthStruct(&depth));
}

// TODO: Hack to keep running under Wayland:
XIDeviceInfo* PsychGetInputDevicesForScreen(int screenNumber, int* nDevices)
{
    if(screenNumber >= numDisplays) PsychErrorExit(PsychError_invalidScumber);
    if (nDevices) *nDevices = xinput_ndevices[screenNumber];
    return(xinput_info[screenNumber]);
}

// X-Screen primary gpu driver is modesetting ddx?
psych_bool PsychOSX11ScreenUsesModesettingDDX(int screenId)
{
    return(displayX11ScreenUsesModesettingDDX[screenId]);
}

// Wayland native builds do have their own screen glue for the X11 specific bits:
#ifndef PTB_USE_WAYLAND

psych_bool PsychGetCGModeFromVideoSetting(CFDictionaryRef *cgMode, PsychScreenSettingsType *setting);

/*
 *    PsychCheckVideoSettings()
 *
 *    Check all available video display modes for the specified screen number and return true if the
 *    settings are valid and false otherwise.
 */
psych_bool PsychCheckVideoSettings(PsychScreenSettingsType *setting)
{
    CFDictionaryRef cgMode;
    return(PsychGetCGModeFromVideoSetting(&cgMode, setting));
}

// Init XInput extension: Called under display lock protection:
static void InitXInputExtensionForDisplay(CGDirectDisplayID dpy, int idx)
{
    int major, minor;
    int rc;

    // XInputExtension supported? If so do basic init:
    if (!XQueryExtension(dpy, "XInputExtension", &xi_opcode, &xi_event, &xi_error)) {
        if (PsychPrefStateGet_Verbosity() > 1) printf("PTB-WARNING: XINPUT1/2 extension unsupported. Will only be able to handle one mouse and mouse cursor.\n");
        goto out;
    }

    // XInput V 2.0 or later supported?
    major = 2;
    minor = 0;
    rc = XIQueryVersion(dpy, &major, &minor);
    if (rc == BadRequest) {
        printf("PTB-WARNING: No XInput-2 support. Server supports version %d.%d only.\n", major, minor);
        printf("PTB-WARNING: XINPUT1/2 extension unsupported. Will only be able to handle one mouse and mouse cursor.\n");
        goto out;
    } else if (rc != Success) {
        printf("PTB-ERROR: Internal error during XInput-2 extension init sequence! This is a bug in Xlib!\n");
        printf("PTB-WARNING: XINPUT1/2 extension unsupported. Will only be able to handle one mouse and mouse cursor.\n");
        goto out;
    }

    // printf("PsychHID: INFO: XI2 supported. Server provides version %d.%d.\n", major, minor);

    // Enumerate all XI2 input devices for this x-display:
    xinput_info[idx] = XIQueryDevice(dpy, XIAllDevices, &xinput_ndevices[idx]);

    out:
    return;
}

// ProcessRandREvents: Must be called called under display lock protection!
static void ProcessRandREvents(int screenNumber)
{
    XEvent evt;

    if (!has_xrandr_1_2) return;

    // Check for screen config change events and dispatch them:
    while (XCheckTypedWindowEvent(displayCGIDs[screenNumber], RootWindow(displayCGIDs[screenNumber], displayX11Screens[screenNumber]), xr_event + RRScreenChangeNotify, &evt)) {
        // Screen changed: Dispatch new configuration to X-Lib:
        XRRUpdateConfiguration(&evt);
    }
}

// GetRandRScreenConfig: Must be called called under display lock protection!
static void GetRandRScreenConfig(CGDirectDisplayID dpy, int idx)
{
    int major, minor;
    int o, isPrimary, crtcid, crtccount;
    int primaryOutput = -1, primaryCRTC = -1, primaryCRTCIdx = -1;
    int crtcs[100] = { 0 };
    XRRProviderResources *providerResources;

    // Preinit to "undefined":
    displayX11ScreenResources[idx] = NULL;

    // XRandR extension supported? If so do basic init:
    if (!XRRQueryExtension(dpy, &xr_event, &xr_error) ||
        !XRRQueryVersion(dpy, &major, &minor)) {
        if (PsychPrefStateGet_Verbosity() > 1) printf("PTB-WARNING: XRandR extension unsupported. Display infos and configuration functions will be very limited!\n");
        return;
    }

    // Detect version of XRandR:
    if (major > 1 || (major == 1 && minor >= 2)) has_xrandr_1_2 = TRUE;
    if (major > 1 || (major == 1 && minor >= 3)) has_xrandr_1_3 = TRUE;
    if (major > 1 || (major == 1 && minor >= 4)) has_xrandr_1_4 = TRUE;

    // Select screen configuration notify events to get delivered to us:
    Window root = RootWindow(dpy, displayX11Screens[idx]);
    XRRSelectInput(dpy, root, RRScreenChangeNotifyMask);

    if (!has_xrandr_1_3) {
        if (PsychPrefStateGet_Verbosity() > 1)
            printf("PTB-WARNING: XRandR version 1.3 unsupported! Could not query useful info for x-screen %i on display %s. Infos and configuration will be very limited.\n",
                   displayX11Screens[idx], DisplayString(dpy));
        return;
    }

    // Fetch current screen configuration info for this screen and display:
    XRRScreenResources* res = XRRGetScreenResourcesCurrent(dpy, root);
    displayX11ScreenResources[idx] = res;
    if (NULL == res) {
        if (PsychPrefStateGet_Verbosity() > 1)
            printf("PTB-WARNING: Could not query configuration of x-screen %i on display %s. Display infos and configuration will be very limited.\n",
                   displayX11Screens[idx], DisplayString(dpy));
        return;
    }

    // Total number of assigned crtc's for this screen:
    crtccount = 0;

    // Iterate over all outputs for this screen:
    for (o = 0; o < res->noutput; o++) {
        XRROutputInfo *output_info = XRRGetOutputInfo(dpy, res, res->outputs[o]);
        if (!output_info) {
            if (PsychPrefStateGet_Verbosity() > 1) printf("PTB-WARNING: Could not get output info for %i'th output of screen %i [display %s]!\n", o, displayX11Screens[idx], DisplayString(dpy));
            continue;
        }

        // Get info about this output:
        if (has_xrandr_1_3 && (XRRGetOutputPrimary(dpy, root) > 0)) {
            isPrimary = (XRRGetOutputPrimary(dpy, root) == res->outputs[o]) ? 1 : 0;
        }
        else {
            isPrimary = -1;
        }

        for (crtcid = 0; crtcid < res->ncrtc; crtcid++) {
            if (res->crtcs[crtcid] == output_info->crtc) break;
        }
        if (crtcid == res->ncrtc) crtcid = -1;

        // Store crtc for this output:
        crtcs[o] = crtcid;

        if (PsychPrefStateGet_Verbosity() > 3) {
            printf("PTB-INFO: Display '%s' : X-Screen %i : Output %i [%s]: %s : ", DisplayString(dpy), displayX11Screens[idx], o, (const char*) output_info->name, (isPrimary > -1) ? ((isPrimary == 1) ? "Primary output" : "Secondary output") : "Unknown output priority");
            printf("%s : CRTC %i [XID %i]\n", (output_info->connection == RR_Connected) ? "Connected" : "Offline", crtcid, (int) output_info->crtc);
        }

        if ((isPrimary > 0) && (crtcid >= 0)) {
            primaryOutput = o;
            primaryCRTC = crtcid;
        }

        // Is this output - and its crtc - really enabled for this screen?
        if (crtcid >=0) {
            // Yes: Add its crtcid to the list of crtc's for this screen:
            PsychSetScreenToHead(idx, crtcid, crtccount);
            PsychSetScreenToCrtcId(idx, minimum_crtcid, crtccount);

            // Increment id of next allocated crtc scanout engine on GPU:
            // We assume they are allocated in the order of activated outputs,
            // e.g., first output of first X-Screen -> crtc 0, 2nd output of first
            // X-Screen -> crtc 1, first output of 2nd X-Screen -> crtc 2 etc.
            //
            // This is as heuristic as previous approach, but it should continue
            // work as well or as bad as previous one, except it should fix the
            // problem reported in forum message #14200 for AMD Catalyst driver.
            // It should work for bog-standard ZaphodHead setups. It will work in
            // any case on single-display setups or multi-display setups where a single
            // X-Screen spans multiple display outputs aka multiple crtcs.
            //
            // The working assumption is that the user of a ZaphodHead config assigned the different
            // GPU outputs, and thereby their associated physical crtc's, in an ascending order to
            // X-Screens. This is a reasonable assumption, but in no way guaranteed by the system.
            // Therefore this heuristic can go wrong on non-standard ZaphodHead Multi-X-Screen setups.
            // In such cases the user can always use the Screen('Preference', 'ScreenToHead', ...);
            // command or the PSYCHTOOLBOX_PIPEMAPPINGS environment variable to override the wrong
            // mapping, although it would be a pita for complex setups.
            minimum_crtcid++;

            // Increment running count of active outputs (displays) attached to
            // the currently processed X-Screend idx:
            crtccount++;
        }

        // Release info for this output:
        XRRFreeOutputInfo(output_info);
    }

    // Found a defined primary output?
    if (primaryOutput == -1) {
        // Could not find primary output -- none defined. Use first connected
        // output as primary output:
        for (o = 0; o < res->noutput; o++) {
            XRROutputInfo *output_info = XRRGetOutputInfo(dpy, res, res->outputs[o]);
            if (output_info && (output_info->connection == RR_Connected) && (crtcs[o] >= 0)) {
                primaryOutput = o;
                primaryCRTC = crtcs[o];
                XRRFreeOutputInfo(output_info);
                break;
            }

            if (output_info) XRRFreeOutputInfo(output_info);
        }

        // Still undefined? Use first output as primary output:
        if (primaryOutput == -1) {
            primaryOutput = 0;
            primaryCRTC = (crtcs[0] >= 0) ? crtcs[0] : 0;
        }
    }

    // Assign primary crtc of primary output - index 0 - as default display head for this screen:
    // We swap the contents of slot 0 - the primary crtc slot - and whatever slot currently
    // contains the crtcid of our primaryCRTC. This way we shuffle the primary crtc into the
    // 1st slot (zero):
    for (o = 0; o < crtccount; o++) {
        if (PsychScreenToHead(idx, o) == primaryCRTC) {
            PsychSetScreenToHead(idx, PsychScreenToHead(idx, 0), o);
            primaryCRTCIdx = PsychScreenToCrtcId(idx, o);
            PsychSetScreenToCrtcId(idx, PsychScreenToCrtcId(idx, 0), o);
        }
    }

    PsychSetScreenToHead(idx, primaryCRTC, 0);
    PsychSetScreenToCrtcId(idx, primaryCRTCIdx, 0);

    // Check the name of the primary RandR provider for this X-Screen, to find out
    // if it is the modesetting-ddx:
    if (has_xrandr_1_4) {
        providerResources = XRRGetProviderResources(dpy, root);
        if (providerResources->nproviders > 0) {
            XRRProviderInfo *info = XRRGetProviderInfo(dpy, res, providerResources->providers[0]);
            if (!strcmp(info->name, "modesetting"))
                displayX11ScreenUsesModesettingDDX[idx] = TRUE;
        }

        XRRFreeProviderResources(providerResources);
    }

    if (PsychPrefStateGet_Verbosity() > 3) {
        printf("PTB-INFO: Display '%s' : X-Screen %i : Assigning primary output as %i with RandR-CRTC %i and GPU-CRTC %i. Modesetting-ddx=%i.\n",
               DisplayString(dpy), displayX11Screens[idx], primaryOutput, primaryCRTC, primaryCRTCIdx, displayX11ScreenUsesModesettingDDX[idx]);
    }

    return;
}

// Linux only: Retrieve modeline and crtc_info for a specific output on a specific screen:
// Caution: If crtc is non-NULL and receives a valid XRRCrtcInfo*, then this pointer must
//          be released by the caller via XRRFreeCrtcInfo(crtc), or resources will leak!
// Must be called under display lock protection!
XRRModeInfo* PsychOSGetModeLine(int screenId, int outputIdx, XRRCrtcInfo **crtc)
{
    int m;
    XRRModeInfo *mode = NULL;
    XRRCrtcInfo *crtc_info = NULL;

    // Query info about video modeline and crtc of output 'outputIdx':
    XRRScreenResources *res = displayX11ScreenResources[screenId];
    if (res && has_xrandr_1_2 && (PsychScreenToHead(screenId, outputIdx) >= 0)) {
        crtc_info = XRRGetCrtcInfo(displayCGIDs[screenId], res, res->crtcs[PsychScreenToHead(screenId, outputIdx)]);

        for (m = 0; (m < res->nmode) && crtc_info; m++) {
            if (res->modes[m].id == crtc_info->mode) {
                mode = &res->modes[m];
                break;
            }
        }
    }

    // Optionally return crtc_info in *crtc:
    if (crtc) {
        // Return crtc_info, if any - NULL otherwise:
        *crtc = crtc_info;
    }
    else {
        // crtc_info not required by caller. We release it:
        if (crtc_info) XRRFreeCrtcInfo(crtc_info);
    }

    return(mode);
}

const char* PsychOSGetOutputProps(int screenId, int outputIdx, psych_bool returnDisabledOutputs, unsigned long *mm_width, unsigned long *mm_height, unsigned long *rrOutputPrimary)
{
    static char outputName[100];
    int o;
    XRROutputInfo *output_info = NULL;
    RRCrtc crtc;
    XRRScreenResources *res = displayX11ScreenResources[screenId];

    // No RandR 1.3 -> No such info:
    if (res == NULL) {
        sprintf(outputName, "Unknown");
        if (mm_width) *mm_width = 0;
        if (mm_height) *mm_height = 0;
        if (rrOutputPrimary) *rrOutputPrimary = 0;
        return(&outputName[0]);
    }

    crtc = res->crtcs[PsychScreenToHead(screenId, outputIdx)];

    // Find output associated with the crtc for this outputIdx on this screen:
    PsychLockDisplay();
    for (o = 0; o < res->noutput; o++) {
        output_info = XRRGetOutputInfo(displayCGIDs[screenId], res, res->outputs[o]);

        if (returnDisabledOutputs) {
            // Special case, return all outputs, even inactive or disconnected ones,
            // just select the 'outputIdx' output:
            if (o == outputIdx)
                break;
        }
        else {
            // Standard case - Only connected and active outputs with proper crtc assigned:
            if (output_info->crtc == crtc)
                break;
        }

        XRRFreeOutputInfo(output_info);
    }
    PsychUnlockDisplay();

    // Got it?
    if (o == res->noutput) PsychErrorExitMsg(PsychError_user, "Invalid output index provided! No such output for this screen!");

    // Store output name to return:
    sprintf(outputName, "%s", output_info->name);

    // And width / height in mm:
    if (mm_width) *mm_width = output_info->mm_width;
    if (mm_height) *mm_height = output_info->mm_height;
    if (rrOutputPrimary) *rrOutputPrimary = (unsigned long) res->outputs[o];

    XRRFreeOutputInfo(output_info);

    // Return output name:
    return(&outputName[0]);
}

void InitCGDisplayIDList(void)
{
    int i, j, k, count, scrnid;
    char* ptbdisplays = NULL;
    char displayname[1000];
    CGDirectDisplayID x11_dpy = NULL;
    char* ptbpipelines = NULL;

    // NULL-out array of displays:
    for(i=0;i<kPsychMaxPossibleDisplays;i++) displayCGIDs[i]=NULL;

    // Preinit screen to head mappings to identity default:
    PsychInitScreenToHeadMappings(0);

    // Initial count of screens is zero:
    numDisplays = 0;

    // Initial minimum allowed crtc id is zero:
    minimum_crtcid = 0;

    // Multiple X11 display specifier strings provided in the environment variable
    // $PSYCHTOOLBOX_DISPLAYS? If so, we connect to all of them and enumerate all
    // available screens on them.
    ptbdisplays = getenv("PSYCHTOOLBOX_DISPLAYS");
    if (ptbdisplays) {
        // Displays explicitely specified. Parse the string and connect to all of them:
        j=0;
        for (i = 0; i <= (int) strlen(ptbdisplays) && j < 1000; i++) {
            // Accepted separators are ',', '"', white-space and end of string...
            if (ptbdisplays[i]==',' || ptbdisplays[i]=='"' || ptbdisplays[i]==' ' || i == (int) strlen(ptbdisplays)) {
                // Separator or end of string detected. Try to connect to display:
                displayname[j]=0;
                if (PsychPrefStateGet_Verbosity() > 2) printf("PTB-INFO: Trying to connect to X-Display %s ...", displayname);

                x11_dpy = XOpenDisplay(displayname);
                if (x11_dpy == NULL) {
                    // Failed.
                    if (PsychPrefStateGet_Verbosity() > 1) printf(" ...Failed! Skipping this display...\n");
                }
                else {
                    // Query number of available screens on this X11 display:
                    count=ScreenCount(x11_dpy);
                    scrnid=0;

                    // Set the screenNumber --> X11 display mappings up:
                    for (k=numDisplays; (k<numDisplays + count) && (k<kPsychMaxPossibleDisplays); k++) {
                        if (k == numDisplays) {
                            // 1st entry for this x-display: Init XInput2 extension for it:
                            InitXInputExtensionForDisplay(x11_dpy, numDisplays);
                        } else {
                            // Successive entry. Copy info from 1st entry:
                            xinput_info[k] = xinput_info[numDisplays];
                            xinput_ndevices[k] = xinput_ndevices[numDisplays];
                        }

                        // Mapping of logical screenNumber to X11 Display:
                        displayCGIDs[k]= x11_dpy;
                        // Mapping of logical screenNumber to X11 screenNumber for X11 Display:
                        displayX11Screens[k]=scrnid++;

                        // Get all relevant screen config info and cache it internally:
                        GetRandRScreenConfig(x11_dpy, k);
                    }

                    if (PsychPrefStateGet_Verbosity() > 2)
                        printf(" ...success! Added %i new physical display screens of %s as PTB screens %i to %i.\n", scrnid, displayname, numDisplays, k-1);

                    // Update total count:
                    numDisplays = k;
                }

                // Reset idx:
                j=0;
            }
            else {
                // Add character to display name:
                displayname[j++]=ptbdisplays[i];
            }
        }

        // At least one screen enumerated?
        if (numDisplays < 1) {
            // We're screwed :(
            PsychErrorExitMsg(PsychError_system, "FATAL ERROR: Couldn't open any X11 display connection to any X-Server!!!");
        }
    }
    else {
        // User didn't setup env-variable with any special displays. We just use
        // the default $DISPLAY or -display of Matlab:
        x11_dpy = XOpenDisplay(NULL);
        if (x11_dpy == NULL) {
            #ifndef PTB_USE_WAFFLE
                // We're screwed :(
                PsychErrorExitMsg(PsychError_system, "FATAL ERROR: Couldn't open default X11 display connection to X-Server!!!");
            #endif

            // No X-Display available, but we are configured with waffle support, so
            // probably user wants to use a non-X11 based display backend.
            if (PsychPrefStateGet_Verbosity() > 2) printf("PTB-INFO: Could not open any X11/X-Windows system based display connection. Trying other display backends.\n");
            PsychInitNonX11();
            return;
        }

        // Query number of available screens on this X11 display:
        count=ScreenCount(x11_dpy);

        InitXInputExtensionForDisplay(x11_dpy, 0);

        // Set the screenNumber --> X11 display mappings up:
        for (i=0; i<count && i<kPsychMaxPossibleDisplays; i++) {
            displayCGIDs[i]= x11_dpy;
            displayX11Screens[i]=i;
            xinput_info[i] = xinput_info[0];
            xinput_ndevices[i] = xinput_ndevices[0];

            // Get all relevant screen config info and cache it internally:
            GetRandRScreenConfig(x11_dpy, i);
        }
        numDisplays=i;
    }

    if ((numDisplays > 1) && (PsychPrefStateGet_Verbosity() > 3)) printf("PTB-INFO: A total of %i X-Windows display screens is available for use.\n", numDisplays);

    // Initialize screenId -> GPU headId mapping to identity mappings,
    // unless already setup by XRandR setup code:
    if (!has_xrandr_1_2) PsychInitScreenToHeadMappings(numDisplays);

    // Mark screen+output mappings as not yet overriden by user. We used PsychScreenToCrtcId() above which
    // set that flag, but we only want this flag set if triggered by true override from usercode by use of
    // Screen('Preference', 'ScreenToHead', screenId, ...):
    PsychResetCrtcIdUserOverride();

    // Did user provide an override for the screenid --> pipeline mapping? Need to reapply it as it
    // may have gotten clobbered by GetRandRScreenConfig() above:
    ptbpipelines = getenv("PSYCHTOOLBOX_PIPEMAPPINGS");
    if (ptbpipelines) {
        // The default is "012...", ie screen 0 = pipe 0, 1 = pipe 1, 2 =pipe 2, n = pipe n
        for (i = 0; (i < (int) strlen(ptbpipelines)) && (i < kPsychMaxPossibleDisplays); i++) {
            PsychSetScreenToCrtcId(i, (((ptbpipelines[i] - 0x30) >=0) && ((ptbpipelines[i] - 0x30) < 10)) ? (ptbpipelines[i] - 0x30) : -1, 0);
        }
    }

    // Prepare atoms for "Desktop composition active?" queries:
    // Each atom corresponds to one X-Screen. It is selection-owned by the
    // desktop compositor for that screen, if a compositor is actually active.
    // It is not owned by anybody if desktop composition is off or suspended for
    // that screen, so checking if such an atom has an owner allows to check if
    // the corresponding x-screen is subject to desktop composition atm.
    for (i = 0; i < numDisplays; i++) {
        CGDirectDisplayID dpy;
        char cmatomname[100];

        // Retrieve and cache an atom for this screen on this display:
        PsychGetCGDisplayIDFromScreenNumber(&dpy, i);
        sprintf(cmatomname, "_NET_WM_CM_S%d", PsychGetXScreenIdForScreen(i));
        displayX11ScreenCompositionAtom[i] = XInternAtom(dpy, cmatomname, False);
    }

    return;
}

void PsychInitNonX11(void)
{
    int i;

    // Set the screenNumber --> X11 display mappings up:
    for (i=0; i < kPsychMaxPossibleDisplays; i++) {
        displayCGIDs[i] = NULL;
        displayX11Screens[i] = i;
        xinput_info[i] = NULL;
        xinput_ndevices[i] = 0;
    }

    // Just make something up;
    numDisplays = 1;

    return;
}

void PsychCleanupDisplayGlue(void)
{
    CGDirectDisplayID dpy, last_dpy;
    int i;

    // Make sure the mmio mapping is shut down:
    PsychOSShutdownPsychtoolboxKernelDriverInterface();

    PsychLockDisplay();

    last_dpy = NULL;
    // Go trough full screen list:
    for (i=0; i < PsychGetNumDisplays(); i++) {
        // Get display-ptr for this screen:
        PsychGetCGDisplayIDFromScreenNumber(&dpy, i);

        // No X11 display associated with this screen? Skip it.
        if (!dpy) continue;

        // Did we close this connection already (dpy==last_dpy)?
        if (dpy != last_dpy) {
            // Nope. Keep track of it...
            last_dpy=dpy;
            // ...and close display connection to X-Server:
            if ((PsychGetNumDisplays() > 1) && (mesaversion[0] > 0)) {
                // This is a multi-x-screen (probably ZaphodHead style) setup, we are using the
                // OSS Mesa OpenGL library, and Mesa has been already initialized by us for the
                // session which is just about to end. Current Mesa versions have a bug in both
                // the nouveau and radeon winsys drivers which would cause a crash if we'd close
                // the X connection here and later Screen() gets reloaded again within the same
                // Octave/Matlab session. By avoiding to close the connection here we can avoid
                // this crash bug, at the minor expense of leaking a bit of memory and X resources.
                //
                // The bug has been already fixed by myself upstream for nouveau and radeon,
                // so we just use this workaround on Mesa versions known to contain the bug.
                // These would be current stable Mesa 10.6.1 and earlier stable versions, but
                // backports of these fixes are already available in Mesa 10.5.9 and expected
                // for Mesa 10.6.2+.
                if ((mesaversion[0] > 10) ||
                    ((mesaversion[0] == 10) && (mesaversion[1] >= 7)) ||
                    ((mesaversion[0] == 10) && (mesaversion[1] == 6) && (mesaversion[2] >= 2)) ||
                    ((mesaversion[0] == 10) && (mesaversion[1] == 5) && (mesaversion[2] >= 9))) {
                    // This Mesa version is safe to close the connection:
                    XCloseDisplay(dpy);
                }
                else {
                    if (PsychPrefStateGet_Verbosity() > 3)
                        printf("PTB-INFO: Skipping XCloseDisplay(screen %i) on multi-x-screen setup, as workaround for buggy Mesa version %i.%i.%i.\n",
                               i, mesaversion[0], mesaversion[1], mesaversion[2]);
                }
            }
            else {
                // Always close display connection on single x-screen setups, or if we aren't
                // running under Mesa OpenGL, or if we haven't initialized our Mesa instance
                // yet, as closing the connection is then safe in any case:
                XCloseDisplay(dpy);
            }

            // Release actual xinput info list for this x11 display connection:
            if (xinput_info[i]) {
                XIFreeDeviceInfo(xinput_info[i]);
            }
        }

        // NULL-Out xinput extension data:
        xinput_info[i] = NULL;
        xinput_ndevices[i] = 0;

        // Release per-screen RandR info structures:
        if (displayX11ScreenResources[i]) XRRFreeScreenResources(displayX11ScreenResources[i]);
        displayX11ScreenResources[i] = NULL;
    }

    PsychUnlockDisplay();

    // Destroy the display lock mutex, now that we're done with it for this Screen() session instance:
    PsychDestroyMutex(&displayLock);

    // All connections should be closed now. We can't NULL-out the display list, but
    // Matlab will flush the Screen - Mexfile anyway...
    return;
}

void PsychGetScreenDepths(int screenNumber, PsychDepthType *depths)
{
    int* x11_depths = NULL;
    int  i, count = 0;

    if(screenNumber>=numDisplays || screenNumber < 0) PsychErrorExitMsg(PsychError_internal, "screenNumber is out of range"); //also checked within SCREENPixelSizes

    // Update XLib's view of this screens configuration:
    PsychLockDisplay();
    ProcessRandREvents(screenNumber);

    if (displayCGIDs[screenNumber]) {
        x11_depths = XListDepths(displayCGIDs[screenNumber], PsychGetXScreenIdForScreen(screenNumber), &count);
    }

    PsychUnlockDisplay();

    if (x11_depths && depths && count > 0) {
        // Query successful: Add all values to depth struct:
        for(i=0; i<count; i++) PsychAddValueToDepthStruct(x11_depths[i], depths);
        XFree(x11_depths);
    }
    else {
        // Query failed: Assume at least 32 bits is available.
        if (PsychPrefStateGet_Verbosity() > 1) printf("PTB-WARNING: Couldn't query available display depths values! Returning a made up list...\n");
        fflush(NULL);
        PsychAddValueToDepthStruct(32, depths);
        PsychAddValueToDepthStruct(24, depths);
        PsychAddValueToDepthStruct(16, depths);
    }
}

double PsychOSVRefreshFromMode(XRRModeInfo *mode)
{
    double dot_clock = (double) mode->dotClock / 1000.0;
    double vrefresh;

    // Sanity check:
    if ((dot_clock <= 0) || (mode->hTotal < 1) || (mode->vTotal < 1)) return(0);

    vrefresh = (((dot_clock * 1000.0) / mode->hTotal) * 1000.0) / mode->vTotal;

    // Divide vrefresh by 1000 to get real Hz - value:
    vrefresh = vrefresh / 1000.0;

    // Doublescan mode? If so, divide vrefresh by 2:
    if (mode->modeFlags & RR_DoubleScan) vrefresh /= 2.0;

    // Interlaced mode? If so, multiply vrefresh by 2:
    if (mode->modeFlags & RR_Interlace) vrefresh *= 2.0;

    return(vrefresh);
}

/*   PsychGetAllSupportedScreenSettings()
 *
 *     Queries the display system for a list of all supported display modes, ie. all valid combinations
 *     of resolution, pixeldepth and refresh rate. Allocates temporary arrays for storage of this list
 *     and returns it to the calling routine. This function is basically only used by Screen('Resolutions').
 */
int PsychGetAllSupportedScreenSettings(int screenNumber, int outputId, long** widths, long** heights, long** hz, long** bpp)
{
    int i, j, o, nsizes, nrates, numPossibleModes;
    XRROutputInfo *output_info = NULL;

    if(screenNumber >= numDisplays || screenNumber < 0) PsychErrorExit(PsychError_invalidScumber);

    // Only supported with RandR 1.2 or later:
    if (!has_xrandr_1_2) return(0);

    if (outputId < 0) {
        PsychLockDisplay();

        // Iterate over all screen sizes and count number of size x refresh rate combos:
        numPossibleModes = 0;
        XRRScreenSize *scs = XRRSizes(displayCGIDs[screenNumber], PsychGetXScreenIdForScreen(screenNumber), &nsizes);
        for (i = 0; i < nsizes; i++) {
            XRRRates(displayCGIDs[screenNumber], PsychGetXScreenIdForScreen(screenNumber), i, &nrates);
            numPossibleModes += nrates;
        }

        PsychUnlockDisplay();

        // Allocate output arrays: These will get auto-released at exit from Screen():
        *widths  = (long*) PsychMallocTemp(numPossibleModes * sizeof(long));
        *heights = (long*) PsychMallocTemp(numPossibleModes * sizeof(long));
        *hz      = (long*) PsychMallocTemp(numPossibleModes * sizeof(long));
        *bpp     = (long*) PsychMallocTemp(numPossibleModes * sizeof(long));

        // Reiterate and fill all slots:
        numPossibleModes = 0;
        for (i = 0; i < nsizes; i++) {
            PsychLockDisplay();
            short* rates = XRRRates(displayCGIDs[screenNumber], PsychGetXScreenIdForScreen(screenNumber), i, &nrates);
            PsychUnlockDisplay();
            for (j = 0; j < nrates; j++) {
                (*widths)[numPossibleModes]  = (long) scs[i].width;
                (*heights)[numPossibleModes] = (long) scs[i].height;
                (*hz)[numPossibleModes]      = (long) rates[j];
                (*bpp)[numPossibleModes]     = (long) PsychGetScreenDepthValue(screenNumber);
                numPossibleModes++;
            }
        }

        // Done:
        return(numPossibleModes);
    }

    // Find crtc for given outputid and screen:
    XRRScreenResources *res = displayX11ScreenResources[screenNumber];
    if (outputId >= kPsychMaxPossibleCrtcs) PsychErrorExitMsg(PsychError_user, "Invalid output index provided! No such output for this screen!");

    outputId = PsychScreenToHead(screenNumber, outputId);
    if (outputId >= res->ncrtc || outputId < 0) PsychErrorExitMsg(PsychError_user, "Invalid output index provided! No such output for this screen!");

    RRCrtc crtc = res->crtcs[outputId];

    // Find output associated with the crtc for this outputId:
    PsychLockDisplay();
    for (o = 0; o < res->noutput; o++) {
        output_info = XRRGetOutputInfo(displayCGIDs[screenNumber], res, res->outputs[o]);
        if (output_info->crtc == crtc) break;
        XRRFreeOutputInfo(output_info);
    }
    PsychUnlockDisplay();

    // Got it?
    if (o == res->noutput) PsychErrorExitMsg(PsychError_user, "Invalid output index provided! No such output for this screen!");

    // Got it: output_info contains a list of all modes (XID's) supported by this
    // display output / crtc combo: Iterate over all of them and return them.
    numPossibleModes = output_info->nmode;

    // Allocate output arrays: These will get auto-released at exit from Screen():
    *widths  = (long*) PsychMallocTemp(numPossibleModes * sizeof(long));
    *heights = (long*) PsychMallocTemp(numPossibleModes * sizeof(long));
    *hz      = (long*) PsychMallocTemp(numPossibleModes * sizeof(long));
    *bpp     = (long*) PsychMallocTemp(numPossibleModes * sizeof(long));

    for (i = 0; i < numPossibleModes; i++) {
        // Fetch modeline for i'th mode:
        for (j = 0; j < res->nmode; j++) {
            if (res->modes[j].id == output_info->modes[i]) break;
        }

        (*widths)[i] = (long) res->modes[j].width;
        (*heights)[i] = (long) res->modes[j].height;
        (*hz)[i] = (long) (PsychOSVRefreshFromMode(&res->modes[j]) + 0.5);
        (*bpp)[i] = (long) 32;
    }

    // Free output info:
    XRRFreeOutputInfo(output_info);

    // Done:
    return(numPossibleModes);
}

/*
 * PsychGetCGModeFromVideoSettings()
 */
psych_bool PsychGetCGModeFromVideoSetting(CFDictionaryRef *cgMode, PsychScreenSettingsType *setting)
{
    int i, j, nsizes = 0, nrates = 0;

    // No op on system without RandR:
    if (!has_xrandr_1_2) {
        // Dummy assignment:
        *cgMode = -1;

        // Also cannot restore display settings at Window / Screen / Runtime close time, so disable it:
        displayOriginalCGSettingsValid[setting->screenNumber] = FALSE;

        // Some info for the reader:
        if (PsychPrefStateGet_Verbosity() > 3) printf("PTB-INFO: Getting or setting display video modes unsupported on this graphics driver due to lack of RandR v1.2 support.\n");

        // Return success in good faith that its ok.
        return(TRUE);
    }

    // Extract parameters from setting struct:
    CGDirectDisplayID dpy = displayCGIDs[setting->screenNumber];
    int width  = (int) PsychGetWidthFromRect(setting->rect);
    int height = (int) PsychGetHeightFromRect(setting->rect);
    int fps    = (int) (setting->nominalFrameRate + 0.5);

    if (PsychPrefStateGet_Verbosity() > 3) printf("PTB-INFO: Trying to validate/find closest video mode for requested spec: width = %i x height = %i, rate %i Hz.\n", width, height, fps);

    // Find matching mode:
    int size_index = -1;

    PsychLockDisplay();

    XRRScreenSize *scs = XRRSizes(dpy, PsychGetXScreenIdForScreen(setting->screenNumber), &nsizes);
    for (i = 0; (i < nsizes) && (size_index == -1); i++) {
        if (PsychPrefStateGet_Verbosity() > 4)
            printf("PTB-INFO: Testing against mode of resolution w x h = %i x %i with refresh rates: ", scs[i].width, scs[i].height);

        if ((width == scs[i].width) && (height == scs[i].height)) {
            short *rates = XRRRates(dpy, PsychGetXScreenIdForScreen(setting->screenNumber), i, &nrates);
            for (j = 0; j < nrates; j++) {
                if (PsychPrefStateGet_Verbosity() > 4)
                    printf("%i ", (int) rates[j]);

                if (rates[j] == (short) fps) {
                    // Our requested size x fps combo is supported:
                    size_index = i;
                    if (PsychPrefStateGet_Verbosity() > 3)
                        printf("\nPTB-INFO: Got it! Mode id %i.\n", size_index);

                    break;
                }
            }
        }
        if (PsychPrefStateGet_Verbosity() > 4) printf("\n");
    }

    PsychUnlockDisplay();

    if ((nsizes == 0) && (PsychPrefStateGet_Verbosity() > 1))
        printf("PTB-WARNING: Getting or setting display video modes unsupported on this graphics driver despite advertised RandR v1.2 support.\n");

    // Found valid settings?
    if (size_index == -1) {
        if (PsychPrefStateGet_Verbosity() > 3) printf("PTB-INFO: No matching video mode found.\n");
        return(FALSE);
    }

    *cgMode = size_index;
    return(TRUE);
}

/*
    PsychGetScreenDepth()

    The caller must allocate and initialize the depth struct.
*/
void PsychGetScreenDepth(int screenNumber, PsychDepthType *depth)
{
    if (screenNumber>=numDisplays || screenNumber < 0) PsychErrorExitMsg(PsychError_internal, "screenNumber is out of range"); //also checked within SCREENPixelSizes

    // Update XLib's view of this screens configuration:
    PsychLockDisplay();
    ProcessRandREvents(screenNumber);

    if (displayCGIDs[screenNumber]) {
        PsychAddValueToDepthStruct(DefaultDepth(displayCGIDs[screenNumber], PsychGetXScreenIdForScreen(screenNumber)), depth);
    }
    else {
        PsychAddValueToDepthStruct(32, depth);
    }

    PsychUnlockDisplay();
}

// We build with VidModeExtension support unless forcefully disabled at compile time via a -DNO_VIDMODEEXTS
#ifndef NO_VIDMODEEXTS
#define USE_VIDMODEEXTS 1
#endif

#ifdef USE_VIDMODEEXTS
// Functions for setup and query of hw gamma CLUTS and for monitor refresh rate query:
#include <X11/extensions/xf86vmode.h>
#else
#define XF86VidModeNumberErrors 0
#endif

float PsychGetNominalFramerate(int screenNumber)
{
    if (PsychPrefStateGet_ConserveVRAM() & kPsychIgnoreNominalFramerate) return(0);

    if(screenNumber >= numDisplays || screenNumber < 0)
        PsychErrorExitMsg(PsychError_internal, "screenNumber passed to PsychGetNominalFramerate() is out of range");

    // No-Op on non-X11:
    if (!displayCGIDs[screenNumber]) return(0);

#ifdef USE_VIDMODEEXTS

    // Information returned by the XF86VidModeExtension:
    XF86VidModeModeLine mode_line;  // The mode line of the current video mode.
    int dot_clock;                  // The RAMDAC / TDMS pixel clock frequency.

    // We start with a default vrefresh of zero, which means "couldn't query refresh from OS":
    float vrefresh = 0;

    // First we try to get modeline of primary crtc from RandR:
    PsychLockDisplay();
    XRRModeInfo *mode = PsychOSGetModeLine(screenNumber, 0, NULL);
    PsychUnlockDisplay();

    // Modeline with plausible values returned by RandR?
    if (mode && (mode->hTotal >= mode->width) && (mode->vTotal >= mode->height)) {
        if (PsychPrefStateGet_Verbosity() > 4) {
            printf ("RandR: %s (0x%x) %6.1fMHz\n",
                    mode->name, (int)mode->id,
                    (double)mode->dotClock / 1000000.0);
            printf ("        h: width  %4d start %4d end %4d total %4d skew %4d\n",
                    mode->width, mode->hSyncStart, mode->hSyncEnd,
                    mode->hTotal, mode->hSkew);
            printf ("        v: height %4d start %4d end %4d total %4d\n",
                    mode->height, mode->vSyncStart, mode->vSyncEnd, mode->vTotal);
        }

        dot_clock = (int) ((double) mode->dotClock / 1000.0);
        mode_line.htotal = mode->hTotal;
        mode_line.vtotal = mode->vTotal;
        mode_line.flags = 0;
        mode_line.flags |= (mode->modeFlags & RR_DoubleScan) ? 0x0020 : 0x0;
        mode_line.flags |= (mode->modeFlags & RR_Interlace) ? 0x0010 : 0x0;
    }
    else {
        // No modeline from RandR or invalid modeline. Retry with vidmode extensions:
        if (PsychPrefStateGet_Verbosity() > 5) printf("PTB-DEBUG: PsychGetNominalFramerate: No mode or invalid mode from RandR. Using XF86VidModeExt fallback path...\n");

        PsychLockDisplay();
        if (!XF86VidModeSetClientVersion(displayCGIDs[screenNumber])) {
            // Failed to use VidMode-Extension. We just return a vrefresh of zero.
            if (PsychPrefStateGet_Verbosity() > 5) printf("PTB-DEBUG: PsychGetNominalFramerate: XF86VidModeExt fallback path failed in init.\n");
            PsychUnlockDisplay();
            return(0);
        }

        if (!XF86VidModeGetModeLine(displayCGIDs[screenNumber], PsychGetXScreenIdForScreen(screenNumber), &dot_clock, &mode_line)) {
            // Failed to use VidMode-Extension. We just return a vrefresh of zero.
            if (PsychPrefStateGet_Verbosity() > 5) printf("PTB-DEBUG: PsychGetNominalFramerate: XF86VidModeExt fallback path failed in modeline query.\n");
            PsychUnlockDisplay();
            return(0);
        }

        PsychUnlockDisplay();
    }

    // More child-protection: (utterly needed!)
    if ((dot_clock <= 0) || (mode_line.htotal < 1) || (mode_line.vtotal < 1)) {
        if (PsychPrefStateGet_Verbosity() > 5) printf("PTB-DEBUG: PsychGetNominalFramerate: Invalid modeline retrieved from RandR/VidModeExt. Giving up!\n");
        return(0);
    }

    // Query vertical refresh rate. If it fails we default to the last known good value...
    // Vertical refresh rate is: RAMDAC pixel clock / width of a scanline in clockcylces /
    // number of scanlines per videoframe.
    vrefresh = (((dot_clock * 1000) / mode_line.htotal) * 1000) / mode_line.vtotal;

    // Divide vrefresh by 1000 to get real Hz - value:
    vrefresh = vrefresh / 1000.0f;

    // Definitions from xserver's hw/xfree86/common/xf86str.h
    // V_INTERLACE    = 0x0010,
    // V_DBLSCAN    = 0x0020,

    // Doublescan mode? If so, divide vrefresh by 2:
    if (mode_line.flags & 0x0020) vrefresh /= 2;

    // Interlaced mode? If so, multiply vrefresh by 2:
    if (mode_line.flags & 0x0010) vrefresh *= 2;

    // Done.
    return(vrefresh);
#else
    return(0);
#endif
}

// Error callback handler for X11 errors:
static int x11VidModeErrorHandler(Display* dis, XErrorEvent* err)
{
    (void) dis;

    // If x11_errorbase not yet setup, simply return and ignore this error:
    if (x11_errorbase == 0) return(0);

    // Setup: Check if its an XVidMode-Error - the only one we do handle.
    if (((err->error_code >=x11_errorbase) && (err->error_code < x11_errorbase + XF86VidModeNumberErrors)) ||
        (err->error_code == BadValue)) {
        // We caused some error. Set error flag:
        x11_errorval = 1;
    }

    // Done.
    return(0);
}

float PsychSetNominalFramerate(int screenNumber, float requestedHz)
{
#ifdef USE_VIDMODEEXTS
    // Information returned by/sent to the XF86VidModeExtension:
    XF86VidModeModeLine mode_line;  // The mode line of the current video mode.
    int dot_clock;                  // The RAMDAC / TDMS pixel clock frequency.
    int event_base;

    // We start with a default vrefresh of zero, which means "couldn't query refresh from OS":
    float vrefresh = 0;

    if(screenNumber>=numDisplays || screenNumber < 0)
        PsychErrorExitMsg(PsychError_internal, "screenNumber is out of range");

    // Not available on non-X11:
    if (!displayCGIDs[screenNumber]) return(0);

    PsychLockDisplay();

    if (!XF86VidModeSetClientVersion(displayCGIDs[screenNumber])) {
        // Failed to use VidMode-Extension. We just return a vrefresh of zero.
        PsychUnlockDisplay();
        return(0);
    }

    if (!XF86VidModeQueryExtension(displayCGIDs[screenNumber], &event_base, &x11_errorbase)) {
        // Failed to use VidMode-Extension. We just return a vrefresh of zero.
        PsychUnlockDisplay();
        return(0);
    }

    // Attach our error callback handler and reset error-state:
    x11_errorval = 0;
    x11_olderrorhandler = XSetErrorHandler(x11VidModeErrorHandler);

    // Step 1: Query current dotclock and modeline:
    if (!XF86VidModeGetModeLine(displayCGIDs[screenNumber], PsychGetXScreenIdForScreen(screenNumber), &dot_clock, &mode_line)) {
        // Restore default error handler:
        XSetErrorHandler(x11_olderrorhandler);
        PsychUnlockDisplay();

        PsychErrorExitMsg(PsychError_internal, "Failed to query video dotclock and modeline!");
    }

    // Step 2: Calculate updated modeline:
    if (requestedHz > 10) {
        // Step 2-a: Given current dot-clock and modeline and requested vrefresh, compute
        // modeline for closest possible match:
        requestedHz*=1000.0f;
        vrefresh = (((dot_clock * 1000) / mode_line.htotal) * 1000) / requestedHz;

        // Assign it to closest modeline setting:
        mode_line.vtotal = (int)(vrefresh + 0.5f);
    }
    else {
        // Step 2-b: Delta mode. requestedHz represents a direct integral offset
        // to add or subtract from current modeline setting:
        mode_line.vtotal+=(int) requestedHz;
    }

    // Step 3: Try to set new modeline:
    if (!XF86VidModeModModeLine(displayCGIDs[screenNumber], PsychGetXScreenIdForScreen(screenNumber), &mode_line)) {
        // Restore default error handler:
        XSetErrorHandler(x11_olderrorhandler);
        PsychUnlockDisplay();

        // Invalid modeline? Signal this:
        return(-1);
    }

    // We synchronize and wait for X-Request completion. If the modeline was invalid,
    // this will trigger an invocation of our errorhandler, which in turn will
    // set the x11_errorval to a non-zero value:
    XSync(displayCGIDs[screenNumber], FALSE);

    // Restore default error handler:
    XSetErrorHandler(x11_olderrorhandler);

    PsychUnlockDisplay();

    // Check for error:
    if (x11_errorval) {
        // Failed to set new mode! Must be invalid. We return -1 to signal this:
        return(-1);
    }

    // No error...

    // Step 4: Query new settings and return them:
    vrefresh = PsychGetNominalFramerate(screenNumber);

    // Done.
    return(vrefresh);
#else
    return(0);
#endif
}

/* Returns the physical display size as reported by X11: */
void PsychGetDisplaySize(int screenNumber, int *width, int *height)
{
    if(screenNumber>=numDisplays || screenNumber < 0)
        PsychErrorExitMsg(PsychError_internal, "screenNumber passed to PsychGetDisplaySize() is out of range");

    // Not available on non-X11:
    if (!displayCGIDs[screenNumber]) { *width = 0; *height = 0; return; }

    // Update XLib's view of this screens configuration:
    PsychLockDisplay();
    ProcessRandREvents(screenNumber);

    *width = (int) XDisplayWidthMM(displayCGIDs[screenNumber], PsychGetXScreenIdForScreen(screenNumber));
    *height = (int) XDisplayHeightMM(displayCGIDs[screenNumber], PsychGetXScreenIdForScreen(screenNumber));

    PsychUnlockDisplay();
}

void PsychGetScreenPixelSize(int screenNumber, long *width, long *height)
{
    // For now points == pixels, so just a dumb wrapper, as long as we
    // don't have special "Retina Display" / HiDPI handling in place on X11:
    PsychGetScreenSize(screenNumber, width, height);
}

void PsychGetScreenSize(int screenNumber, long *width, long *height)
{
    if(screenNumber>=numDisplays || screenNumber < 0) PsychErrorExitMsg(PsychError_internal, "screenNumber passed to PsychGetScreenDepths() is out of range");

    // Not available on non-X11: MK TODO FIXME - How to get real values?
    if (!displayCGIDs[screenNumber]) { *width = 1680; *height = 1050; return; }

    // Update XLib's view of this screens configuration:
    PsychLockDisplay();
    ProcessRandREvents(screenNumber);

    *width=XDisplayWidth(displayCGIDs[screenNumber], PsychGetXScreenIdForScreen(screenNumber));
    *height=XDisplayHeight(displayCGIDs[screenNumber], PsychGetXScreenIdForScreen(screenNumber));

    PsychUnlockDisplay();
}

void PsychGetGlobalScreenRect(int screenNumber, double *rect)
{
    // Create an empty rect:
    PsychMakeRect(rect, 0, 0, 1, 1);
    // Fill it with meaning by PsychGetScreenRect():
    PsychGetScreenRect(screenNumber, rect);
}

void PsychGetScreenRect(int screenNumber, double *rect)
{
    long width, height;

    PsychGetScreenSize(screenNumber, &width, &height);
    rect[kPsychLeft]=0;
    rect[kPsychTop]=0;
    rect[kPsychRight]=(int)width;
    rect[kPsychBottom]=(int)height;
}

/*
    This is a place holder for a function which uncovers the number of dacbits.

    For now we just use 0 to avoid false precision.
*/
int PsychGetDacBitsFromDisplay(int screenNumber)
{
    (void) screenNumber;

    return(0);
}

//Set display parameters

/* Linux only: PsychOSSetOutputConfig()
 * Set a video mode and other settings for a specific crtc of a specific output 'outputId'
 * for a specific screen 'screenNumber'.
 *
 * Returns true on success, false on failure.
 */
int PsychOSSetOutputConfig(int screenNumber, int outputId, int newWidth, int newHeight, int newHz, int newX, int newY)
{
    int modeid, maxw, maxh, output, widthMM, heightMM;
    XRRCrtcInfo *crtc_info = NULL, *crtc_info2;
    CGDirectDisplayID dpy = displayCGIDs[screenNumber];
    XRRScreenResources *res = displayX11ScreenResources[screenNumber];

    // Need this later:
    PsychGetDisplaySize(screenNumber, &widthMM, &heightMM);

    if (res && has_xrandr_1_2 && (PsychScreenToHead(screenNumber, outputId) >= 0)) {
        PsychLockDisplay();
        crtc_info = XRRGetCrtcInfo(dpy, res, res->crtcs[PsychScreenToHead(screenNumber, outputId)]);
        PsychUnlockDisplay();
    }
    else {
        // Failed!
        return(FALSE);
    }

    // Disable auto-restore of screen settings - It would end badly...
    displayOriginalCGSettingsValid[screenNumber] = FALSE;

    // Find matching mode:
    for (modeid = 0; modeid < res->nmode; modeid++) {
        if (((int) res->modes[modeid].width == newWidth) && ((int) res->modes[modeid].height == newHeight) &&
            (newHz == (int)(PsychOSVRefreshFromMode(&res->modes[modeid]) + 0.5))) {
            break;
        }
    }

    PsychLockDisplay();

    // Matching mode found for modesetting?
    if (modeid < res->nmode) {

        // Assign default panning:
        if (newX < 0) newX = crtc_info->x;
        if (newY < 0) newY = crtc_info->y;

        // Iterate over all outputs and compute the new screen bounding box:
        maxw = maxh = 0;
        for (output = 0; (PsychScreenToHead(screenNumber, output) >= 0) && (output < kPsychMaxPossibleCrtcs); output++) {
            if (output == outputId) continue;

            crtc_info2 = XRRGetCrtcInfo(dpy, res, res->crtcs[PsychScreenToHead(screenNumber, output)]);
            if (crtc_info2->x + (int) crtc_info2->width > maxw) maxw = crtc_info2->x + (int) crtc_info2->width;
            if (crtc_info2->y + (int) crtc_info2->height > maxh) maxh = crtc_info2->y + (int) crtc_info2->height;
            XRRFreeCrtcInfo(crtc_info2);
        }

        // Incorporate our soon reconfigured crtc:
        if (newX + newWidth  > maxw) maxw = newX + newWidth;
        if (newY + newHeight > maxh) maxh = newY + newHeight;

        // [0, 0, maxw, maxh] is the new bounding rectangle of the scanned out framebuffer. Set screen size accordingly:

        // Prevent clients from getting confused by our config sequence:
        // XGrabServer(dpy);

        // Disable target crtc:
        if (PsychPrefStateGet_Verbosity() > 4) printf("PTB-INFO: Disabling crtc %i.\n", outputId);
        XRRSetCrtcConfig(dpy, res, res->crtcs[PsychScreenToHead(screenNumber, outputId)], crtc_info->timestamp,
                                    0, 0, None, RR_Rotate_0, NULL, 0);

        // Resize screen: MK Don't! Skip this for now, use PsychSetScreenSettings() aka Screen('Resolution') to resize
        // the screen without changing the crtc / output settings. More flexible...
        // if (PsychPrefStateGet_Verbosity() > 4) printf("PTB-INFO: Resizing screen %i to %i x %i pixels.\n", screenNumber, maxw, maxh);
        // XRRSetScreenSize(dpy, RootWindow(dpy, PsychGetXScreenIdForScreen(screenNumber)), maxw, maxh, widthMM, heightMM);

        // Switch mode of target crtc and reenable it:
        if (PsychPrefStateGet_Verbosity() > 4) printf("PTB-INFO: Enabling crtc %i.\n", outputId);

        crtc_info2 = XRRGetCrtcInfo(dpy, res, res->crtcs[PsychScreenToHead(screenNumber, outputId)]);
        XRRSetCrtcConfig(dpy, res, res->crtcs[PsychScreenToHead(screenNumber, outputId)], crtc_info2->timestamp,
                                newX, newY, res->modes[modeid].id, crtc_info->rotation,
                                crtc_info->outputs, crtc_info->noutput);
        XRRFreeCrtcInfo(crtc_info);
        XRRFreeCrtcInfo(crtc_info2);

        // XUngrabServer(dpy);

    } else {
        // No such matching mode for given specs. Output disable requested?
        if (newWidth == 0 && newHeight == 0 && newHz == 0) {
            // Disable output, ie. target crtc:
            if (PsychPrefStateGet_Verbosity() > 4)
                printf("PTB-INFO: Disabling crtc %i.\n", outputId);

            XRRSetCrtcConfig(dpy, res, res->crtcs[PsychScreenToHead(screenNumber, outputId)], crtc_info->timestamp,
                            0, 0, None, RR_Rotate_0, NULL, 0);
            XRRFreeCrtcInfo(crtc_info);
        }
        else {
            XRRFreeCrtcInfo(crtc_info);

            PsychUnlockDisplay();

            return(FALSE);
        }
    }

    // Make sure the screen change gets noticed by XLib:
    ProcessRandREvents(screenNumber);

    PsychUnlockDisplay();

    return(TRUE);
}

/*
    PsychSetScreenSettings()

    Accept a PsychScreenSettingsType structure holding a video mode and set the display mode accordingly.

    If we can not change the display settings because of a lock (set by open window or close window) then return false.

    SCREENOpenWindow should capture the display before it sets the video mode.  If it doesn't, then PsychSetVideoSettings will
    detect that and exit with an error.  SCREENClose should uncapture the display.

    The duties of SCREENOpenWindow are:
    -Lock the screen which serves the purpose of preventing changes in video setting with open Windows.
    -Capture the display which gives the application synchronous control of display parameters.

    TO DO: for 8-bit palletized mode there is probably more work to do.

*/

psych_bool PsychSetScreenSettings(psych_bool cacheSettings, PsychScreenSettingsType *settings)
{
    CFDictionaryRef cgMode;
    psych_bool      isValid, isCaptured;
    Rotation        rotation;
    short           rate;
    Time            cfg_timestamp;
    CGDirectDisplayID dpy;

    (void) cacheSettings;

    if (settings->screenNumber >= numDisplays || settings->screenNumber < 0) PsychErrorExitMsg(PsychError_internal, "screenNumber passed to PsychSetScreenSettings() is out of range");
    dpy = displayCGIDs[settings->screenNumber];

    // Not available on non-X11:
    if (!dpy) return(false);

    //Check for a lock which means onscreen or offscreen windows tied to this screen are currently open.
    // MK Disabled: if(PsychCheckScreenSettingsLock(settings->screenNumber)) return(false);  //calling function should issue an error for attempt to change display settings while windows were open.

    //Check to make sure that this display is captured, which OpenWindow should have done.  If it has not been done, then exit with an error.
    isCaptured=PsychIsScreenCaptured(settings->screenNumber);
    if(!isCaptured) PsychErrorExitMsg(PsychError_internal, "Attempt to change video settings without capturing the display");

    // Store the original display mode if this is the first time we have called this function.  The psychtoolbox will disregard changes in
    // the screen state made through the control panel after the Psychtoolbox was launched. That is, OpenWindow will by default continue to
    // open windows with finder settings which were in place at the first call of OpenWindow.  That's not intuitive, but not much of a problem
    // either.
    if(!displayOriginalCGSettingsValid[settings->screenNumber]) {
        PsychGetScreenSettings(settings->screenNumber, &displayOriginalCGSettings[settings->screenNumber]);
        displayOriginalCGSettingsValid[settings->screenNumber] = TRUE;
    }

    // Multi-Display configuration?
    if (PsychScreenToHead(settings->screenNumber, 1) != -1) {
        // Yes: At least two display heads attached. We can't use the XRRSetScreenConfigAndRate() method,
        // it is only suitable for single-display setups. In this case, we only set the screen size, aka
        // framebuffer size. User scripts can use the 'ConfigureDisplay' function to setup the crtc's:

        // Also cannot restore display settings at Window / Screen / Runtime close time, so disable it:
        displayOriginalCGSettingsValid[settings->screenNumber] = FALSE;

        // Resize screen:
        int widthMM, heightMM;
        PsychGetDisplaySize(settings->screenNumber, &widthMM, &heightMM);
        int width  = (int) PsychGetWidthFromRect(settings->rect);
        int height = (int) PsychGetHeightFromRect(settings->rect);

        if (PsychPrefStateGet_Verbosity() > 4) printf("PTB-INFO: Resizing screen %i to %i x %i pixels.\n", settings->screenNumber, width, height);

        PsychLockDisplay();

        XRRSetScreenSize(dpy, RootWindow(dpy, PsychGetXScreenIdForScreen(settings->screenNumber)), width, height, widthMM, heightMM);

        // Make sure the screen change gets noticed by XLib:
        ProcessRandREvents(settings->screenNumber);

        PsychUnlockDisplay();

        // Done.
        return(true);
    }

    // Single display configuration, go ahead:

    //Find core graphics video settings which correspond to settings as specified withing by an abstracted psychsettings structure.
    isValid = PsychGetCGModeFromVideoSetting(&cgMode, settings);
    if (!isValid || (int) cgMode < 0) {
        // This is an internal error because the caller is expected to check first.
        PsychErrorExitMsg(PsychError_user, "Attempt to set invalid video settings or function unsupported with this graphics-driver.");
    }

    // Change the display mode.
    PsychLockDisplay();
    XRRScreenConfiguration *sc = XRRGetScreenInfo(dpy, RootWindow(dpy, PsychGetXScreenIdForScreen(settings->screenNumber)));

    // Extract parameters from settings struct:
    rate = (short) (settings->nominalFrameRate + 0.5);

    // Fetch current rotation, so we can (re)apply it -- We don't support changing rotation yet:
    XRRConfigCurrentConfiguration(sc, &rotation);

    // Fetch config timestamp so we can prove to the server we're trustworthy:
    Time timestamp = XRRConfigTimes(sc, &cfg_timestamp);

    // Apply new configuration - combo of old rotation with new size (encoded in cgMode) and refresh rate:
    Status rc = XRRSetScreenConfigAndRate(dpy, sc, RootWindow(dpy, PsychGetXScreenIdForScreen(settings->screenNumber)), cgMode, rotation, rate, timestamp);

    // Cleanup:
    XRRFreeScreenConfigInfo(sc);

    // Make sure the screen change gets noticed by XLib:
    ProcessRandREvents(settings->screenNumber);

    PsychUnlockDisplay();

    // Done:
    return((rc != BadValue) ? true : false);
}

/*
    PsychRestoreVideoSettings()

    Restores video settings to the state set by the finder.  Returns TRUE if the settings can be restored or false if they
    can not be restored because a lock is in effect, which would mean that there are still open windows.

*/
psych_bool PsychRestoreScreenSettings(int screenNumber)
{
    CFDictionaryRef             cgMode;
    psych_bool                  isValid, isCaptured;
    Rotation                    rotation;
    short                       rate;
    Time                        cfg_timestamp;
    CGDirectDisplayID           dpy;
    PsychScreenSettingsType     *settings;

    if(screenNumber >= numDisplays || screenNumber < 0)
        PsychErrorExitMsg(PsychError_internal, "screenNumber passed to PsychGetScreenDepths() is out of range"); //also checked within SCREENPixelSizes

    //Check to make sure that the original graphics settings were cached.  If not, it means that the settings were never changed, so we can just
    //return true.
    if(!displayOriginalCGSettingsValid[screenNumber]) return(true);

    //Check to make sure that this display is captured, which OpenWindow should have done.  If it has not been done, then exit with an error.
    isCaptured=PsychIsScreenCaptured(screenNumber);
    if(!isCaptured) PsychErrorExitMsg(PsychError_internal, "Attempt to change video settings without capturing the display");

    // Retrieve original screen settings which we should restore for this screen:
    settings = &displayOriginalCGSettings[screenNumber];

    // Invalidate settings - we want a fresh game after restoring the resolution:
    displayOriginalCGSettingsValid[screenNumber] = FALSE;

    //Find core graphics video settings which correspond to settings as specified withing by an abstracted psychsettings structure.
    isValid = PsychGetCGModeFromVideoSetting(&cgMode, settings);
    if (!isValid || (int) cgMode < 0){
        // This is an internal error because the caller is expected to check first.
        PsychErrorExitMsg(PsychError_user, "Attempt to restore invalid video settings or function unsupported with this graphics-driver.");
    }

    //Change the display mode.
    dpy = displayCGIDs[settings->screenNumber];

    PsychLockDisplay();

    XRRScreenConfiguration *sc = XRRGetScreenInfo(dpy, RootWindow(dpy, PsychGetXScreenIdForScreen(settings->screenNumber)));

    // Extract parameters from settings struct:
    rate = (short) (settings->nominalFrameRate + 0.5);

    // Fetch current rotation, so we can (re)apply it -- We don't support changing rotation yet:
    XRRConfigCurrentConfiguration (sc, &rotation);

    // Fetch config timestamp so we can prove to the server we're trustworthy:
    Time timestamp = XRRConfigTimes(sc, &cfg_timestamp);

    // Apply new configuration - combo of old rotation with new size (encoded in cgMode) and refresh rate:
    Status rc = XRRSetScreenConfigAndRate(dpy, sc, RootWindow(dpy, PsychGetXScreenIdForScreen(settings->screenNumber)), cgMode, rotation, rate, timestamp);

    // Cleanup:
    XRRFreeScreenConfigInfo(sc);

    // Make sure the screen change gets noticed by XLib:
    ProcessRandREvents(settings->screenNumber);

    PsychUnlockDisplay();

    // Done:
    return ((rc != BadValue) ? true : false);
}

void PsychOSDefineX11Cursor(int screenNumber, int deviceId, Cursor cursor)
{
    PsychWindowRecordType **windowRecordArray;
    int i, numWindows;

    // Not available on non-X11:
    if (!displayCGIDs[screenNumber]) return;

    // Iterate over all open onscreen windows associated with this screenNumber and
    // apply new X11 cursor definition to each of them:
    PsychCreateVolatileWindowRecordPointerList(&numWindows, &windowRecordArray);

    PsychLockDisplay();
    for(i = 0; i < numWindows; i++) {
        if (PsychIsOnscreenWindow(windowRecordArray[i]) && (windowRecordArray[i]->screenNumber == screenNumber) &&
            windowRecordArray[i]->targetSpecific.xwindowHandle) {
            // Candidate.
            if (deviceId >= 0) {
                // XInput extension for per-device settings:
                XIDefineCursor(displayCGIDs[screenNumber], deviceId, windowRecordArray[i]->targetSpecific.xwindowHandle, cursor);
            }
            else {
                // Old-School global settings:
                XDefineCursor(displayCGIDs[screenNumber], windowRecordArray[i]->targetSpecific.xwindowHandle, cursor);
            }
        }
    }
    PsychUnlockDisplay();
    PsychDestroyVolatileWindowRecordPointerList(windowRecordArray);

    return;
}

void PsychHideCursor(int screenNumber, int deviceIdx)
{
    // Static "Cursor" object which defines a completely transparent - and therefore invisible
    // X11 cursor for the mouse-pointer.
    static Cursor nullCursor = -1;

    // Check for valid screenNumber:
    if((screenNumber >= numDisplays) || (screenNumber < 0)) PsychErrorExitMsg(PsychError_internal, "screenNumber passed to PsychHideCursor() is out of range"); //also checked within SCREENPixelSizes

    // Not available on non-X11:
    if (!displayCGIDs[screenNumber]) return;

    // Cursor already hidden on screen? If so, nothing to do:
    if ((deviceIdx < 0) && displayCursorHidden[screenNumber]) return;

    // nullCursor already ready?
    if( nullCursor == (Cursor) -1 ) {
        // Create one:
        Pixmap cursormask;
        XGCValues xgc;
        GC gc;
        XColor dummycolour;

        PsychLockDisplay();

        cursormask = XCreatePixmap(displayCGIDs[screenNumber], RootWindow(displayCGIDs[screenNumber], PsychGetXScreenIdForScreen(screenNumber)), 1, 1, 1/*depth*/);
        xgc.function = GXclear;
        gc = XCreateGC(displayCGIDs[screenNumber], cursormask, GCFunction, &xgc );
        XFillRectangle(displayCGIDs[screenNumber], cursormask, gc, 0, 0, 1, 1 );
        dummycolour.pixel = 0;
        dummycolour.red   = 0;
        dummycolour.flags = 04;
        nullCursor = XCreatePixmapCursor(displayCGIDs[screenNumber], cursormask, cursormask, &dummycolour, &dummycolour, 0, 0 );
        XFreePixmap(displayCGIDs[screenNumber], cursormask );
        XFreeGC(displayCGIDs[screenNumber], gc );

        PsychUnlockDisplay();
    }

    if (deviceIdx < 0) {
        // Attach nullCursor to our onscreen window:
        PsychOSDefineX11Cursor(screenNumber, deviceIdx, nullCursor);
        PsychLockDisplay();
        XFlush(displayCGIDs[screenNumber]);
        PsychUnlockDisplay();
        displayCursorHidden[screenNumber]=TRUE;
    } else {
        // XInput cursor: Master pointers only.
        int nDevices;
        XIDeviceInfo* indevs = PsychGetInputDevicesForScreen(screenNumber, &nDevices);

        // Sanity check:
        if (NULL == indevs) PsychErrorExitMsg(PsychError_user, "Sorry, your system does not support individual mouse pointers.");
        if (deviceIdx >= nDevices) PsychErrorExitMsg(PsychError_user, "Invalid 'mouseIndex' provided. No such cursor pointer.");
        if (indevs[deviceIdx].use != XIMasterPointer) PsychErrorExitMsg(PsychError_user, "Invalid 'mouseIndex' provided. No such master cursor pointer.");

        // Attach nullCursor to our onscreen window:
        PsychOSDefineX11Cursor(screenNumber, indevs[deviceIdx].deviceid, nullCursor);
        PsychLockDisplay();
        XFlush(displayCGIDs[screenNumber]);
        PsychUnlockDisplay();
    }

    return;
}

void PsychShowCursor(int screenNumber, int deviceIdx)
{
    Cursor arrowCursor;

    // Check for valid screenNumber:
    if(screenNumber >= numDisplays || screenNumber < 0) PsychErrorExitMsg(PsychError_internal, "screenNumber passed to PsychHideCursor() is out of range"); //also checked within SCREENPixelSizes

    // Not available on non-X11:
    if (!displayCGIDs[screenNumber]) return;

    if (deviceIdx < 0) {
        // Cursor not hidden on screen? If so, nothing to do:
        if(!displayCursorHidden[screenNumber]) return;

        // Reset to standard Arrow-Type cursor, which is a visible one.
        PsychLockDisplay();
        arrowCursor = XCreateFontCursor(displayCGIDs[screenNumber], 2);
        PsychUnlockDisplay();

        PsychOSDefineX11Cursor(screenNumber, deviceIdx, arrowCursor);

        PsychLockDisplay();
        XFlush(displayCGIDs[screenNumber]);
        PsychUnlockDisplay();

        displayCursorHidden[screenNumber]=FALSE;
    } else {
        // XInput cursor: Master pointers only.
        int nDevices;
        XIDeviceInfo* indevs = PsychGetInputDevicesForScreen(screenNumber, &nDevices);

        // Sanity check:
        if (NULL == indevs) PsychErrorExitMsg(PsychError_user, "Sorry, your system does not support individual mouse pointers.");
        if (deviceIdx >= nDevices) PsychErrorExitMsg(PsychError_user, "Invalid 'mouseIndex' provided. No such cursor pointer.");
        if (indevs[deviceIdx].use != XIMasterPointer) PsychErrorExitMsg(PsychError_user, "Invalid 'mouseIndex' provided. No such master cursor pointer.");

        // Reset to standard Arrow-Type cursor, which is a visible one.
        PsychLockDisplay();
        arrowCursor = XCreateFontCursor(displayCGIDs[screenNumber], 2);
        PsychUnlockDisplay();

        PsychOSDefineX11Cursor(screenNumber, indevs[deviceIdx].deviceid, arrowCursor);

        PsychLockDisplay();
        XFlush(displayCGIDs[screenNumber]);
        PsychUnlockDisplay();
    }
}

void PsychPositionCursor(int screenNumber, int x, int y, int deviceIdx)
{
    // Not available on non-X11:
    if (!displayCGIDs[screenNumber]) return;

    // Reposition the mouse cursor:
    if (deviceIdx < 0) {
        // Core protocol cursor:
        PsychLockDisplay();
        if (XWarpPointer(displayCGIDs[screenNumber], None, RootWindow(displayCGIDs[screenNumber], PsychGetXScreenIdForScreen(screenNumber)), 0, 0, 0, 0, x, y)==BadWindow) {
            PsychUnlockDisplay();
            PsychErrorExitMsg(PsychError_internal, "Couldn't position the mouse cursor! (XWarpPointer() failed).");
        }
    } else {
        // XInput cursor: Master pointers only.
        int nDevices;
        XIDeviceInfo* indevs = PsychGetInputDevicesForScreen(screenNumber, &nDevices);

        // Sanity check:
        if (NULL == indevs) PsychErrorExitMsg(PsychError_user, "Sorry, your system does not support individual mouse pointers.");
        if (deviceIdx >= nDevices) PsychErrorExitMsg(PsychError_user, "Invalid 'mouseIndex' provided. No such cursor pointer.");
        if (indevs[deviceIdx].use != XIMasterPointer) PsychErrorExitMsg(PsychError_user, "Invalid 'mouseIndex' provided. No such master cursor pointer.");

        PsychLockDisplay();
        if (XIWarpPointer(displayCGIDs[screenNumber], indevs[deviceIdx].deviceid, None, RootWindow(displayCGIDs[screenNumber], PsychGetXScreenIdForScreen(screenNumber)), 0, 0, 0, 0, x, y)) {
            PsychUnlockDisplay();
            PsychErrorExitMsg(PsychError_internal, "Couldn't position the mouse cursor! (XIWarpPointer() failed).");
        }
    }

    XFlush(displayCGIDs[screenNumber]);
    PsychUnlockDisplay();
}

/*
    PsychReadNormalizedGammaTable()
*/
void PsychReadNormalizedGammaTable(int screenNumber, int outputId, int *numEntries, float **redTable, float **greenTable, float **blueTable)
{
    CGDirectDisplayID cgDisplayID;
    static float localRed[MAX_GAMMALUT_SIZE], localGreen[MAX_GAMMALUT_SIZE], localBlue[MAX_GAMMALUT_SIZE];

    // The X-Windows hardware LUT has 3 tables for R,G,B.
    // Each entry is a 16-bit word with the n most significant bits used for an n-bit DAC or display encoder:
    psych_uint16    RTable[MAX_GAMMALUT_SIZE];
    psych_uint16    GTable[MAX_GAMMALUT_SIZE];
    psych_uint16    BTable[MAX_GAMMALUT_SIZE];
    int i, n;

    // Initial assumption: Failed.
    n = 0;

    // Not available on non-X11:
    if (!displayCGIDs[screenNumber]) { *numEntries = 0; return; }

    // Query OS for gamma table:
    PsychGetCGDisplayIDFromScreenNumber(&cgDisplayID, screenNumber);

    if (has_xrandr_1_2) {
        // Use RandR V 1.2 for per-crtc query:
        XRRScreenResources *res = displayX11ScreenResources[screenNumber];

        if (outputId >= kPsychMaxPossibleCrtcs) PsychErrorExitMsg(PsychError_user, "Invalid output index provided! No such output for this screen!");
        outputId = PsychScreenToHead(screenNumber, ((outputId < 0) ? 0 : outputId));
        if (outputId >= res->ncrtc || outputId < 0) PsychErrorExitMsg(PsychError_user, "Invalid output index provided! No such output for this screen!");

        RRCrtc crtc = res->crtcs[outputId];
        PsychLockDisplay();
        XRRCrtcGamma *lut = XRRGetCrtcGamma(cgDisplayID, crtc);
        PsychUnlockDisplay();

        n = (lut) ? lut->size : 0;

        if (PsychPrefStateGet_Verbosity() > 5) printf("PTB-DEBUG: PsychReadNormalizedGammaTable: Provided RandR HW-LUT size is n=%i.\n", n);

        // Gamma lut query successfull?
        if (n > 0) {
            if ((n > MAX_GAMMALUT_SIZE) && (PsychPrefStateGet_Verbosity() > 1)) {
                printf("PTB-WARNING: ReadNormalizedGammatable: Hardware gamma table size of %i slots exceeds our maximum of %i slots. Clamping returned size to %i slots. Returned LUT's may be wrong!\n", n, MAX_GAMMALUT_SIZE, MAX_GAMMALUT_SIZE);
            }

            // Clamp for safety:
            n = (n <= MAX_GAMMALUT_SIZE) ? n : MAX_GAMMALUT_SIZE;

            // Convert tables: Map 16-bit values into 0-1 normalized floats:
            for (i = 0; i < n; i++) localRed[i]   = ((float) lut->red[i]) / 65535.0f;
            for (i = 0; i < n; i++) localGreen[i] = ((float) lut->green[i]) / 65535.0f;
            for (i = 0; i < n; i++) localBlue[i]  = ((float) lut->blue[i]) / 65535.0f;
        }

        if (lut) XRRFreeGamma(lut);
    }

    // Do we need the fallback path with XVidmodeExtension on systems which don't support RandR-1.2?
    // This applies to, e.g., the NVidia binary blob in the year 2011 (Sadly, not a joke):
    if (n <= 0) {
        // Use old-fashioned VidmodeExt path: No control over which output is queried on multi-display setups,
        // except in a ZaphodHead configuration where each display corresponds to a separate x-screen:
        #ifdef USE_VIDMODEEXTS
            // Query size of to-be-returned gamma table:
            PsychLockDisplay();
            XF86VidModeGetGammaRampSize(cgDisplayID, PsychGetXScreenIdForScreen(screenNumber), &n);
            PsychUnlockDisplay();

            if (PsychPrefStateGet_Verbosity() > 5) printf("PTB-DEBUG: PsychReadNormalizedGammaTable: Provided XF86VidMode HW-LUT size is n=%i.\n", n);

            // Make sure we stay within our limits:
            if (n > MAX_GAMMALUT_SIZE) {
                printf("PTB-ERROR: ReadNormalizedGammatable: Hardware gamma table size of %i slots exceeds our maximum of %i slots! Gamma table query failed!\n", n, MAX_GAMMALUT_SIZE);
                PsychErrorExitMsg(PsychError_user, "Gamma table query failed due to size mismatch. Please report this on the Psychtoolbox forum.");
            }

            // Make sure this works at all:
            if (n <= 0) PsychErrorExitMsg(PsychError_user, "Gamma table query failed while trying XF86VidModeExtension fallback path.");

            // Retrieve gamma table with n slots:
            PsychLockDisplay();
            XF86VidModeGetGammaRamp(cgDisplayID, PsychGetXScreenIdForScreen(screenNumber), n, (unsigned short*) RTable, (unsigned short*) GTable, (unsigned short*) BTable);
            PsychUnlockDisplay();
        #else
            PsychErrorExitMsg(PsychError_user, "Sorry, this graphics card and driver does not support gamma table queries!");
        #endif

        // Convert tables: Map 16-bit values into 0-1 normalized floats:
        for (i = 0; i < n; i++) localRed[i]   = ((float) RTable[i]) / 65535.0f;
        for (i = 0; i < n; i++) localGreen[i] = ((float) GTable[i]) / 65535.0f;
        for (i = 0; i < n; i++) localBlue[i]  = ((float) BTable[i]) / 65535.0f;
    }

    // Assign output lut's:
    *redTable=localRed; *greenTable=localGreen; *blueTable=localBlue;

    // Assign size of LUT's::
    *numEntries = n;

    return;
}

/* Copy provided input LUT into target output LUT. If input is smaller than target LUT, but
 * fits nicely because output size is an integral multiple of input, then oversample input
 * to create proper output. If size doesn't match or output is smaller than input, abort
 * with error.
 *
 * Rationale: LUT's of standard GPUs are 256 slots, LUT's of high-end GPU's can be bigger
 *            powers-of-two sizes, e.g., 512, 1024, 2048, 4096 for some NVidia QuadroFX
 *            parts. For reasons of backwards compatibility we always want to be able to
 *            accept a good'ol 256 slots input LUT, even if the GPU expects something bigger.
 *            -> This simple oversampling via replication allows us to do that without obvious
 *               bad consequences for precision.
 *
 */
static void ConvertLUTToHwLUT(int nOut, psych_uint16* Rout, psych_uint16* Gout, psych_uint16* Bout, int nIn, float *redTable, float *greenTable, float *blueTable)
{
    int i, s;

    // Can't handle too big input tables for GPU:
    if (nOut < nIn) {
        printf("PTB-ERROR: Provided gamma table has %i slots, but graphics card accepts at most %i slots!\n", nIn, nOut);
        PsychErrorExitMsg(PsychError_user, "Provided gamma table has too many slots!");
    }

    // Can't handle tables which don't fit:
    if ((nOut % nIn) != 0) {
        printf("PTB-ERROR: Provided gamma table has %i slots, but graphics card expects %i slots.\n", nIn, nOut);
        printf("PTB-ERROR: Unfortunately, graphics card LUT size is not a integral multiple of provided gamma table size.\n");
        printf("PTB-ERROR: I can not handle this case, as it could cause ugly distortions in the displayed color range.\n");
        PsychErrorExitMsg(PsychError_user, "Provided gamma table has wrong number of slots!");
    }

    // Compute oversampling factor:
    s = nOut / nIn;
    if (PsychPrefStateGet_Verbosity() > 5) {
        printf("PTB-DEBUG: PsychLoadNormalizedGammaTable: LUT size nIn %i <= nOut %i --> Oversample %i times.\n", nIn, nOut, s);
    }

    // Copy and oversample: Each slot in red/green/blueTable is replicated
    // into s consecutive slots of R/G/Bout:
    for (i = 0; i < nOut; i++) {
        Rout[i] = (psych_uint16) (redTable[i/s]   * 65535.0f + 0.5f);
        Gout[i] = (psych_uint16) (greenTable[i/s] * 65535.0f + 0.5f);
        Bout[i] = (psych_uint16) (blueTable[i/s]  * 65535.0f + 0.5f);
    }
}

unsigned int PsychLoadNormalizedGammaTable(int screenNumber, int outputId, int numEntries, float *redTable, float *greenTable, float *blueTable)
{
    CGDirectDisplayID cgDisplayID;
    int i, j, n;
    RRCrtc crtc;

    static psych_uint16    RTable[MAX_GAMMALUT_SIZE];
    static psych_uint16    GTable[MAX_GAMMALUT_SIZE];
    static psych_uint16    BTable[MAX_GAMMALUT_SIZE];

    // The X-Windows hardware LUT has 3 tables for R,G,B.
    // Each entry is a 16-bit word with the n most significant bits used for an n-bit DAC or display encoder.

    // Set new gammaTable:
    PsychGetCGDisplayIDFromScreenNumber(&cgDisplayID, screenNumber);

    // Initial assumption: Failure.
    n = 0;

    // Not available on non-X11:
    if (!displayCGIDs[screenNumber]) return(0);

    if (has_xrandr_1_2) {
        // Use RandR V 1.2 for per-crtc setup:

        // Setup of all crtc's with this gamma table requested?
        if (outputId < 0) {
            // Yes: Iterate over all outputs, set via recursive call:
            j = 1;
            for (i = 0; (j > 0) && (i < kPsychMaxPossibleCrtcs) && (PsychScreenToHead(screenNumber, i) > -1); i++) {
                j = PsychLoadNormalizedGammaTable(screenNumber, i, numEntries, redTable, greenTable, blueTable);
            }

            // Done trying to set all crtc's. Return status:
            return((unsigned int) j);
        }

        // No, or recursive self-call: Load a specific crtc for output 'outputId':
        XRRScreenResources *res = displayX11ScreenResources[screenNumber];

        if (outputId >= kPsychMaxPossibleCrtcs) PsychErrorExitMsg(PsychError_user, "Invalid output index provided! No such output for this screen!");
        outputId = PsychScreenToHead(screenNumber, outputId);
        if (outputId >= res->ncrtc || outputId < 0) PsychErrorExitMsg(PsychError_user, "Invalid output index provided! No such output for this screen!");

        crtc = res->crtcs[outputId];

        // Get required size of gamma table:
        PsychLockDisplay();
        n = XRRGetCrtcGammaSize(cgDisplayID, crtc);
        PsychUnlockDisplay();
        if (PsychPrefStateGet_Verbosity() > 5) printf("PTB-DEBUG: PsychLoadNormalizedGammaTable: Required RandR HW-LUT size is n=%i.\n", n);
    }

    // RandR 1.2 supported and has ability to set LUT's?
    if (has_xrandr_1_2 && (n > 0)) {
        // Allocate table of appropriate size:
        XRRCrtcGamma *lut = XRRAllocGamma(n);
        n = lut->size;

        // Convert tables: Map 16-bit values into 0-1 normalized floats:
        ConvertLUTToHwLUT(n, lut->red, lut->green, lut->blue, numEntries, redTable, greenTable, blueTable);

        // Assign to crtc:
        PsychLockDisplay();
        XRRSetCrtcGamma(cgDisplayID, crtc, lut);
        PsychUnlockDisplay();

        // Release lut:
        XRRFreeGamma(lut);
    }

    // RandR unsupported or failed?
    if (n <= 0) {
        // Use old-fashioned VidmodeExt fallback-path: No control over which output is setup on multi-display setups,
        // except in a ZaphodHead configuration where each display corresponds to a separate x-screen:
        if (PsychPrefStateGet_Verbosity() > 5) printf("PTB-DEBUG: PsychLoadNormalizedGammaTable: Using XF86VidModeExt fallback path...\n");

        #ifdef USE_VIDMODEEXTS
            // Query size of to-be-set hw-gamma table:
            PsychLockDisplay();
            XF86VidModeGetGammaRampSize(cgDisplayID, PsychGetXScreenIdForScreen(screenNumber), &n);
            PsychUnlockDisplay();
            if (PsychPrefStateGet_Verbosity() > 5) printf("PTB-DEBUG: PsychLoadNormalizedGammaTable: Required HW-LUT size is n=%i.\n", n);

            // Make sure we stay within our limits:
            if (n > MAX_GAMMALUT_SIZE) {
                printf("PTB-ERROR: LoadNormalizedGammatable: Hardware gamma table size of %i slots exceeds our maximum of %i slots! Gamma table setup failed!\n", n, MAX_GAMMALUT_SIZE);
                PsychErrorExitMsg(PsychError_user, "Gamma table setup failed due to size mismatch. Please report this on the Psychtoolbox forum.");
            }

            // Make sure this works at all:
            if (n <= 0) PsychErrorExitMsg(PsychError_user, "Gamma table setup failed while trying XF86VidModeExtension fallback path.");

            // Convert input table to X11 specific gammaTable:
            ConvertLUTToHwLUT(n, RTable, GTable, BTable, numEntries, redTable, greenTable, blueTable);

            // Assign to X-Screen:
            PsychLockDisplay();
            XF86VidModeSetGammaRamp(cgDisplayID, PsychGetXScreenIdForScreen(screenNumber), n, (unsigned short*) RTable, (unsigned short*) GTable, (unsigned short*) BTable);
            PsychUnlockDisplay();
        #else
            PsychErrorExitMsg(PsychError_user, "Sorry, this graphics card and driver does not support gamma table setup!");
        #endif
    }

    PsychLockDisplay();
    XFlush(cgDisplayID);
    PsychUnlockDisplay();

    // Return "success":
    return(1);
}

// Return true (non-zero) if a desktop compositor is likely active on screen 'screenNumber':
int PsychOSIsDWMEnabled(int screenNumber)
{
    int rc;
    CGDirectDisplayID dpy;
    PsychGetCGDisplayIDFromScreenNumber(&dpy, screenNumber);

    // Not available on non-X11: Assume no desktop compositor active.
    if (!dpy) return(0);

    // According to ICCCM spec, a compositing window manager who does composition on a
    // specific X-Screen must aquire "selection ownership" of the atom specified in our
    // displayX11ScreenCompositionAtom[screenNumber] for the given screenNumber. Therefore,
    // if the atom corresponding to 'screenNumber' does have a XGetSelectionOwner (!= None),
    // then that owner is the compositor, ergo desktop composition for that screenNumber is
    // active. Ref: http://standards.freedesktop.org/wm-spec/wm-spec-latest.html#id2579173
    //
    PsychLockDisplay();
    rc = (XGetSelectionOwner(dpy, displayX11ScreenCompositionAtom[screenNumber]) != None) ? 1 : 0;
    PsychUnlockDisplay();

    return(rc);
}

// !PTB_USE_WAYLAND
#endif

// PsychGetDisplayBeamPosition() contains the implementation of display beamposition queries.
// It requires both, a cgDisplayID handle, and a logical screenNumber and uses one of both for
// deciding which display pipe to query, whatever of both is more efficient or suitable for the
// host platform -- This is ugly, but neccessary, because the mapping with only one of these
// specifiers would be either ambigous (wrong results!) or usage would be inefficient and slow
// (bad for such a time critical low level call!). On some systems it may even ignore the arguments,
// because it's not capable of querying different pipes - ie., it will always query a hard-coded pipe.
//
int PsychGetDisplayBeamPosition(CGDirectDisplayID cgDisplayId, int screenNumber)
{
    // Beamposition queries aren't supported by the X11 graphics system.
    // However, for gfx-hardware where we have reliable register specs, we
    // can do it ourselves, bypassing the X server.

    // On systems that we can't handle, we return -1 as an indicator
    // to high-level routines that we don't know the rasterbeam position.
    double tdeadline, tnow;
    int vblbias, vbltotal;
    int beampos = -1;

    (void) cgDisplayId;

    // Get beamposition from low-level driver code:
    if (PsychOSIsKernelDriverAvailable(screenNumber) && displayBeampositionHealthy[screenNumber]) {
        // Is application of the beamposition workaround requested by high-level code?
        // Or is this a NVidia GPU? In the latter case we always use the workaround,
        // because many NVidia GPU's (especially pre NV-50 hardware) need this in many
        // setups. It helps if needed, and doesn't hurt if not needed - burns at most
        // 25 insignificant microseconds of time. However, we do not apply this workaround
        // automatically on NVidia Kepler or later gpu's, because it would interfere with
        // our G-Sync support:
        if ((PsychPrefStateGet_ConserveVRAM() & kPsychUseBeampositionQueryWorkaround) ||
-           ((fDeviceType == kPsychGeForce) && (fCardType != 0x0) && (fCardType < 0x0E0))) {
            // Yes: Avoid queries that return zero -- If query result is zero, retry
            // until it becomes non-zero: Some hardware may needs this to resolve...
            // We use a timeout of 100 msecs though to prevent hangs if we try to
            // query a disabled crtc's scanout position or similar bad things happen...
            PsychGetPrecisionTimerSeconds(&tdeadline);
            tdeadline += 0.1;
            while (0 == (beampos = PsychOSKDGetBeamposition(screenNumber))) {
                PsychGetPrecisionTimerSeconds(&tnow);
                if (tnow > tdeadline) {
                    // Trouble: Hanging here for more than 100 msecs?
                    // This display head is dead. Output a info to the user
                    // and disable it for further beamposition queries.
                    displayBeampositionHealthy[screenNumber] = FALSE;
                    beampos = -1;

                    if (PsychPrefStateGet_Verbosity() > 1) {
                        printf("PTB-WARNING: Hang in beamposition query detected! Seems my mapping of screen numbers to GPU's and display outputs is wrong?\n");
                        printf("PTB-WARNING: In a single GPU system you can resolve this by plugging in your monitors in a different order, changing the\n");
                        printf("PTB-WARNING: display arrangement in the control panel, or using the Screen('Preference', 'ScreenToHead', ...);\n");
                        printf("PTB-WARNING: command at the top of your scripts to set the mapping manually. See 'help DisplayOutputMappings' for more info.\n");
                        printf("PTB-WARNING: \n");
                        printf("PTB-WARNING: I am not yet able to handle multi-GPU systems reliably at all. If you have such a system it may work if\n");
                        printf("PTB-WARNING: you plug your monitor(s) into one of the other GPU's output connectors, trying different combinations.\n");
                        printf("PTB-WARNING: Or you simply live without high precision stimulus onset timestamping for now. Or you use the free and open-source\n");
                        printf("PTB-WARNING: graphics drivers (intel, radeon, or nouveau) instead of the proprietary Catalyst or NVidia binary drivers.\n");
                        printf("PTB-WARNING: I've disabled high precision timestamping for this screen for the remainder of the session.\n\n");
                        fflush(NULL);
                    }

                    break;
                }
            }
        } else {
            // Read final beampos:
            beampos = PsychOSKDGetBeamposition(screenNumber);
        }
    }

    // Return failure, if indicated:
    if (beampos == -1) return(-1);

    // Apply corrective offsets if any (i.e., if non-zero):
    // Note: In case of Radeon's, these are zero, because the code above already has applied proper corrections.
    PsychGetBeamposCorrection(screenNumber, &vblbias, &vbltotal);
    beampos = beampos - vblbias;
    if (beampos < 0) beampos = vbltotal + beampos;

    // Return our result or non-result:
    return(beampos);
}

// Try to attach to kernel level ptb support driver and setup everything, if it works:
void InitPsychtoolboxKernelDriverInterface(void)
{
    // This is currently a no-op on Linux, as most low-level stuff is done via mmapped() MMIO access...
    return;
}

// Try to detach to kernel level ptb support driver and tear down everything:
void PsychOSShutdownPsychtoolboxKernelDriverInterface(void)
{
    if (numKernelDrivers > 0) {
        // Make sure we're really detached from any MMIO memory before we shutdown:
        PsychScreenUnmapDeviceMemory();
    }

    // Ok, whatever happened, we're detached (for good or bad):
    numKernelDrivers = 0;

    return;
}

psych_bool PsychOSIsKernelDriverAvailable(int screenId)
{
    (void) screenId;

    // Currently our "kernel driver" is available if MMIO mem could be mapped:
    // A real driver would indicate its presence via numKernelDrivers > 0 (see init/teardown code just above this routine):
    return((gfx_cntl_mem) ? TRUE : FALSE);
}

int PsychOSCheckKDAvailable(int screenId, unsigned int * status)
{
    // This doesn't make much sense on Linux yet. 'connect' should be something like a handle
    // to a kernel driver connection, e.g., the filedescriptor fd of the devicefile for ioctl()s
    // but we don't have such a thing yet.  Could be also a pointer to a little struct with all
    // relevant info...
    // Currently we do a dummy assignment...
    int connect = PsychScreenToCrtcId(screenId, 0);

    if ((numKernelDrivers<=0) && (gfx_cntl_mem == NULL)) {
        if (status) *status = ENODEV;
        return(0);
    }

    if (connect < 0) {
        if (status) *status = ENODEV;
        if (PsychPrefStateGet_Verbosity() > 6) printf("PTB-DEBUGINFO: Could not access kernel driver connection for screenId %i - No such connection.\n", screenId);
        return(0);
    }

    if (status) *status = 0;

    // Force this to '1', so the truth value is non-zero aka TRUE.
    connect = 1;
    return(connect);
}

unsigned int PsychOSKDReadRegister(int screenId, unsigned int offset, unsigned int* status)
{
    // Check availability of connection:
    int connect;
    if (!(connect = PsychOSCheckKDAvailable(screenId, status))) {
        if (status) *status = ENODEV;
        return(0xffffffff);
    }

    if (status) *status = 0;

    // Return readback register value:
    return(ReadRegister(offset));
}

unsigned int PsychOSKDWriteRegister(int screenId, unsigned int offset, unsigned int value, unsigned int* status)
{
    // Check availability of connection:
    int connect;
    if (!(connect = PsychOSCheckKDAvailable(screenId, status))) {
        if (status) *status = ENODEV;
        return(0xffffffff);
    }

    if (status) *status = 0;

    // Write the register:
    WriteRegister(offset, value);

    // Return success:
    return(0);
}

// Synchronize display screens video refresh cycle of DCE-4 (and later) GPU's, aka Evergreen. See PsychSynchronizeDisplayScreens() for help and details...
static PsychError PsychOSSynchronizeDisplayScreensDCE4(int *numScreens, int* screenIds, int* residuals, unsigned int syncMethod, double syncTimeOut, int allowedResidual)
{
    int             screenId = 0;
    double          abortTimeOut, now;
    int             residual;
    int             i, iter;
    unsigned int    old_crtc_master_enable = 0;
    unsigned int    crtc_control_reg;

    // Check availability of connection:
    int             connect;
    unsigned int    status;

    // No support for other methods than fast hard sync:
    if (syncMethod > 1) {
        if (PsychPrefStateGet_Verbosity() > 1) printf("PTB-WARNING: Could not execute display resync operation with requested non hard sync method. Not supported for this setup and settings.\n");
        return(PsychError_unimplemented);
    }

    // The current implementation only supports syncing the heads of a single card
    if (*numScreens <= 0) {
        // Resync all displays requested: Choose screenID zero for connect handle:
        screenId = 0;
    }
    else {
        // Resync of specific display requested: We only support resync of all heads of a single multi-head card,
        // therefore just choose the screenId of the passed master-screen for resync handle:
        screenId = screenIds[0];
    }

    if (!(connect = PsychOSCheckKDAvailable(screenId, &status))) {
        if (PsychPrefStateGet_Verbosity() > 1) printf("PTB-WARNING: Could not execute display resync operation for master screenId %i. Not supported for this setup and settings.\n", screenId);
        return(PsychError_unimplemented);
    }

    if (fDeviceType != kPsychRadeon) {
        if (PsychPrefStateGet_Verbosity() > 2) printf("PTB-INFO: PsychOSSynchronizeDisplayScreens(): This function is not supported on non-ATI/AMD GPU's! Aborted.\n");
        return(PsychError_unimplemented);
    }

    crtc_control_reg = isDCE12(screenId) ? DCE12_CRTC_CONTROL : EVERGREEN_CRTC_CONTROL;

    // Setup deadline for abortion or repeated retries:
    PsychGetAdjustedPrecisionTimerSeconds(&abortTimeOut);
    abortTimeOut+=syncTimeOut;
    residual = INT_MAX;

    // Repeat until timeout or good enough result:
    do {
        // If this isn't the first try, wait 0.5 secs before retry:
        if (residual != INT_MAX) PsychWaitIntervalSeconds(0.5);

        residual = INT_MAX;

        if (PsychPrefStateGet_Verbosity() > 3) printf("PTB-INFO: PsychOSSynchronizeDisplayScreens(): About to resynchronize all DCE-4+ display heads by use of a 1 second CRTC stop->start cycle:\n");

        if (PsychPrefStateGet_Verbosity() > 3) {
            printf("Trying to stop and reset all display heads by disabling them one by one.\n");
            printf("Will wait individually for each head to reach its defined resting position.\n");
        }

        // Detect enabled heads:
        old_crtc_master_enable = 0;
        for (iter = 0; iter < kPsychMaxPossibleCrtcs; iter++) {
            // Map 'iter'th head for this screenId to crtc index 'i'. Iterate over all crtc's for screen:
            if ((i = PsychScreenToCrtcId(screenId, iter)) < 0) break;

            // Sanity check crtc id i:
            if (i > (int) fNumDisplayHeads - 1) {
                if (PsychPrefStateGet_Verbosity() > 0)
                    printf("PTB-ERROR: PsychOSSynchronizeDisplayScreens(): Invalid headId %i provided! Must be between 0 and %i. Aborted.\n", i, (fNumDisplayHeads - 1));
                return(PsychError_user);
            }

            // Bit 16 "CRTC_CURRENT_MASTER_EN_STATE" allows read-only polling
            // of current activation state of crtc:
            if (ReadRegister(crtc_control_reg + crtcoff[i]) & (0x1 << 16)) old_crtc_master_enable |= (0x1 << i);
        }

        // Shut down heads, one after each other, wait for each one to settle at its defined resting position:
        for (iter = 0; iter < kPsychMaxPossibleCrtcs; iter++) {
            // Map 'iter'th head for this screenId to crtc index 'i'. Iterate over all crtc's for screen:
            if ((i = PsychScreenToCrtcId(screenId, iter)) < 0) break;

            if (PsychPrefStateGet_Verbosity() > 3) printf("Head %ld ...  ", i);
            if (old_crtc_master_enable & (0x1 << i)) {
                if (PsychPrefStateGet_Verbosity() > 3) printf("active -> Shutdown. ");

                // Shut down this CRTC by clearing its master enable bit (bit 0):
                WriteRegister(crtc_control_reg + crtcoff[i], ReadRegister(crtc_control_reg + crtcoff[i]) & ~(0x1 << 0));

                // Wait 50 msecs, so CRTC has enough time to settle and disable at its
                // programmed resting position:
                PsychWaitIntervalSeconds(0.050);

                // Double check - Poll until crtc is offline:
                while(ReadRegister(crtc_control_reg + crtcoff[i]) & (0x1 << 16));
                if (PsychPrefStateGet_Verbosity() > 3) printf("-> Offline.\n");
            }
            else {
                if (PsychPrefStateGet_Verbosity() > 3) printf("already offline.\n");
            }
        }

        // Need realtime priority for following synchronized start to minimize delays:
        PsychRealtimePriority(true);

        // Sleep for 1 second: This is a blocking call, ie. the thread goes to sleep and may wakeup a bit later:
        PsychWaitIntervalSeconds(1);

        // Reenable all now disabled, but previously enabled display heads.
        // This must be a tight loop, as every microsecond counts for a good sync...
        for (iter = 0; iter < kPsychMaxPossibleCrtcs; iter++) {
            // Map 'iter'th head for this screenId to crtc index 'i'. Iterate over all crtc's for screen:
            if ((i = PsychScreenToCrtcId(screenId, iter)) < 0) break;

            if (old_crtc_master_enable & (0x1 << i)) {
                // Restart this CRTC by setting its master enable bit (bit 0):
                WriteRegister(crtc_control_reg + crtcoff[i], ReadRegister(crtc_control_reg + crtcoff[i]) | (0x1 << 0));
            }
        }

        // Done with realtime bits:
        PsychRealtimePriority(false);

        // We don't have meaningful residual info. Just assume we succeeded:
        residual = 0;
        if (PsychPrefStateGet_Verbosity() > 2) printf("PTB-INFO: Graphics display heads hopefully resynchronized.\n");

        // Timestamp:
        PsychGetAdjustedPrecisionTimerSeconds(&now);
    } while ((now < abortTimeOut) && (abs(residual) > allowedResidual));

    // Return residual value if wanted:
    if (residuals) {
        residuals[0] = residual;
    }

    if (abs(residual) > allowedResidual) {
        if (PsychPrefStateGet_Verbosity() > 1) printf("PTB-WARNING: Failed to synchronize heads down to the allowable residual of +/- %i scanlines. Final residual %i lines.\n", allowedResidual, residual);
    }

    // TODO: Error handling not really worked out...
    if (residual == INT_MAX) return(PsychError_system);

    // Done.
    return(PsychError_none);
}

// Helper function for PsychOSSynchronizeDisplayScreens().
static unsigned int GetBeamPosition(int headId)
{
    return((unsigned int) ReadRegister((headId == 0) ? RADEON_D1CRTC_STATUS_POSITION : RADEON_D2CRTC_STATUS_POSITION) & RADEON_VBEAMPOSITION_BITMASK);
}

// Synchronize display screens video refresh cycle. See PsychSynchronizeDisplayScreens() for help and details...
PsychError PsychOSSynchronizeDisplayScreens(int *numScreens, int* screenIds, int* residuals, unsigned int syncMethod, double syncTimeOut, int allowedResidual)
{
    int             screenId = 0;
    double          abortTimeOut, now;
    int             residual;
    int             deltabeampos;
    unsigned int    beampos0, beampos1, i;
    unsigned int    old_crtc_master_enable = 0;
    unsigned int    new_crtc_master_enable = 0;

    // Check availability of connection:
    int             connect;
    unsigned int    status;

    // No support for other methods than fast hard sync:
    if (syncMethod > 1) {
        if (PsychPrefStateGet_Verbosity() > 1) printf("PTB-WARNING: Could not execute display resync operation with requested non hard sync method. Not supported for this setup and settings.\n");
        return(PsychError_unimplemented);
    }

    // The current implementation only supports syncing all heads of a single card
    if (*numScreens <= 0) {
        // Resync all displays requested: Choose screenID zero for connect handle:
        screenId = 0;
    }
    else {
        // Resync of specific display requested: We only support resync of all heads of a single multi-head card,
        // therefore just choose the screenId of the passed master-screen for resync handle:
        screenId = screenIds[0];
    }

    if (!(connect = PsychOSCheckKDAvailable(screenId, &status))) {
        if (PsychPrefStateGet_Verbosity() > 1) printf("PTB-WARNING: Could not execute display resync operation for master screenId %i. Not supported for this setup and settings.\n", screenId);
        return(PsychError_unimplemented);
    }

    if (fDeviceType != kPsychRadeon) {
        if (PsychPrefStateGet_Verbosity() > 2) printf("PTB-INFO: PsychOSSynchronizeDisplayScreens(): This function is not supported on non-ATI/AMD GPU's! Aborted.\n");
        return(PsychError_unimplemented);
    }

    // DCE-4 display engine of Evergreen or later?
    if (isDCE4(screenId) || isDCE5(screenId) || isDCE10(screenId) || isDCE11(screenId) || isDCE12(screenId)) {
        // Yes. Use DCE-4+ specific sync routine:
        return(PsychOSSynchronizeDisplayScreensDCE4(numScreens, screenIds, residuals, syncMethod, syncTimeOut, allowedResidual));
    }

    // Setup deadline for abortion or repeated retries:
    PsychGetAdjustedPrecisionTimerSeconds(&abortTimeOut);
    abortTimeOut+=syncTimeOut;
    residual = INT_MAX;

    // Repeat until timeout or good enough result:
    do {
        // If this isn't the first try, wait 0.5 secs before retry:
        if (residual != INT_MAX) PsychWaitIntervalSeconds(0.5);

        residual = INT_MAX;

        if (PsychPrefStateGet_Verbosity() > 3) printf("PTB-INFO: PsychOSSynchronizeDisplayScreens(): About to resynchronize all display heads by use of a 1 second CRTC stop->start cycle:\n");

        // A little pretest...
        if (PsychPrefStateGet_Verbosity() > 3) printf("Pretest...\n");
        for (i = 0; i < 10; i++) {
            beampos0 = GetBeamPosition(0);
            beampos1 = GetBeamPosition(1);
            if (PsychPrefStateGet_Verbosity() > 3) printf("Sample %ld: Beampositions are %ld vs. %ld . Offset %ld\n", i, beampos0, beampos1, (int) beampos1 - (int) beampos0);
        }

        // Query the CRTC scan-converter master enable state: Bit 0 (value 0x1) controls Pipeline 1,
        // whereas Bit 1(value 0x2) controls Pipeline 2:
        old_crtc_master_enable = ReadRegister(RADEON_DC_CRTC_MASTER_ENABLE);
        if (PsychPrefStateGet_Verbosity() > 3) {
            printf("Current CRTC Master enable state is %ld . Trying to stop and reset all display heads.\n", old_crtc_master_enable);
            printf("Will wait individually for each head to get close to scanline 0, then disable it.\n");
        }

        // Shut down heads, one after each other, each one at the start of a new refresh cycle:
        for (i = 0; i <= 1; i++) {
            // Wait for head i to start a new display cycle (scanline 0), then shut it down - well if it is active at all:
            if (PsychPrefStateGet_Verbosity() > 3) printf("Head %ld ...  ", i);
            if (old_crtc_master_enable & (0x1 << i)) {
                if (PsychPrefStateGet_Verbosity() > 3) printf("active -> Shutdown. ");
                // Wait for beam going above scanline 240: We choose 240, because even at the lowest conceivable
                // useful display resolution of 640 x 480, 240 will be in the middle of the frame, aka far away
                // from both, the start and the end of a frame:
                while (GetBeamPosition(i) <= 240);

                // Beam is heading for the end of the frame + VBL area. Wait for wrap-around, ie. until
                // reaching a scanline value smaller than 100 --> Until it wraps back to zero or at least
                // a value close to zero:
                while (GetBeamPosition(i) > 240);

                // Start of new refresh interval! Shut down this heads CRTC!
                // We do so by clearing enable bit for this head:
                WriteRegister(RADEON_DC_CRTC_MASTER_ENABLE, ReadRegister(RADEON_DC_CRTC_MASTER_ENABLE) & ~(0x1 << i));
                if (PsychPrefStateGet_Verbosity() > 3) printf("New state is %ld.\n", ReadRegister(RADEON_DC_CRTC_MASTER_ENABLE));

                // Head should be down, close to scanline 0.
                PsychWaitIntervalSeconds(0.050);
            }
            else {
                if (PsychPrefStateGet_Verbosity() > 3) printf("already offline.\n");
            }
        }

        // All display heads should be disabled now.
        PsychWaitIntervalSeconds(0.100);

        // Query current beamposition and check state:
        beampos0 = GetBeamPosition(0);
        beampos1 = GetBeamPosition(1);

        new_crtc_master_enable = ReadRegister(RADEON_DC_CRTC_MASTER_ENABLE);

        if (new_crtc_master_enable == 0) {
            if (PsychPrefStateGet_Verbosity() > 3) printf("CRTC's down (state %ld): Beampositions are [0]=%ld and [1]=%ld. Synchronized restart in 1 second...\n", new_crtc_master_enable, beampos0, beampos1);
        }
        else {
            if (PsychPrefStateGet_Verbosity() > 3) printf("CRTC's shutdown failed!! (state %ld): Beamposition are [0]=%ld and [1]=%ld. Will try to restart in 1 second...\n", new_crtc_master_enable, beampos0, beampos1);
        }

        // Sleep for 1 second: This is a blocking call, ie. the thread goes to sleep and may wakeup a bit later:
        PsychWaitIntervalSeconds(1);

        // Reset all display heads enable state to original setting:
        WriteRegister(RADEON_DC_CRTC_MASTER_ENABLE, old_crtc_master_enable);

        // Query position and state after restart:
        beampos0 = GetBeamPosition(0);
        beampos1 = GetBeamPosition(1);
        new_crtc_master_enable = ReadRegister(RADEON_DC_CRTC_MASTER_ENABLE);
        if (new_crtc_master_enable == old_crtc_master_enable) {
            if (PsychPrefStateGet_Verbosity() > 3) printf("CRTC's restarted in sync: Master enable state is %ld. Beampositions after restart: [0]=%ld and [1]=%ld.\n", new_crtc_master_enable, beampos0, beampos1);
        }
        else {
            if (PsychPrefStateGet_Verbosity() > 3) printf("CRTC's restart FAILED!!: Master enable state is %ld. Beampositions: [0]=%ld and [1]=%ld.\n", new_crtc_master_enable, beampos0, beampos1);
        }

        deltabeampos = (int) beampos1 - (int) beampos0;
        if (PsychPrefStateGet_Verbosity() > 3) printf("Residual beam offset after display sync: %ld.\n\n", deltabeampos);

        // A little posttest...
        if (PsychPrefStateGet_Verbosity() > 3) printf("Posttest...\n");
        for (i = 0; i < 10; i++) {
            beampos0 = GetBeamPosition(0);
            beampos1 = GetBeamPosition(1);
            if (PsychPrefStateGet_Verbosity() > 3) printf("Sample %ld: Beampositions are %ld vs. %ld . Offset %ld\n", i, beampos0, beampos1, (int) beampos1 - (int) beampos0);
        }

        if (PsychPrefStateGet_Verbosity() > 3) printf("Display head resync operation finished.\n\n");

        // Assign residual for this iteration:
        residual = deltabeampos;

        if (PsychPrefStateGet_Verbosity() > 2) printf("PTB-INFO: Graphics display heads resynchronized. Residual vertical beamposition error is %ld scanlines.\n", residual);

        // Timestamp:
        PsychGetAdjustedPrecisionTimerSeconds(&now);
    } while ((now < abortTimeOut) && (abs(residual) > allowedResidual));

    // Return residual value if wanted:
    if (residuals) {
        residuals[0] = residual;
    }

    if (abs(residual) > allowedResidual) {
        if (PsychPrefStateGet_Verbosity() > 1) printf("PTB-WARNING: Failed to synchronize heads down to the allowable residual of +/- %i scanlines. Final residual %i lines.\n", allowedResidual, residual);
    }

    // TODO: Error handling not really worked out...
    if (residual == INT_MAX) return(PsychError_system);

    // Done.
    return(PsychError_none);
}

int PsychOSKDGetBeamposition(int screenId)
{
    int beampos = -1;
    int headId  = PsychScreenToCrtcId(screenId, 0);
    static psych_bool firstTime = TRUE;

    if (headId < 0 || headId > ((int) fNumDisplayHeads - 1)) {
        if (PsychPrefStateGet_Verbosity() > 0) printf("PTB-ERROR: PsychOSKDGetBeamposition: Invalid headId %i provided! Must be between 0 and %i. Aborted.\n", headId, (fNumDisplayHeads - 1));
        return(beampos);
    }

    // MMIO registers mapped?
    if (gfx_cntl_mem) {
        // Query code for ATI/AMD Radeon/FireGL/FirePro:
        if (fDeviceType == kPsychRadeon) {
            if (isDCE4(screenId) || isDCE5(screenId) || isDCE10(screenId) || isDCE11(screenId) || isDCE12(screenId)) {
                // DCE-4+ display engine (CEDAR and later afaik): Up to six or seven crtc's.

                // Read raw beampostion from GPU:
                beampos = (int) (ReadRegister((isDCE12(screenId) ? DCE12_CRTC_STATUS_POSITION : EVERGREEN_CRTC_STATUS_POSITION) + crtcoff[headId]) & RADEON_VBEAMPOSITION_BITMASK);

                // Query end-offset of VBLANK interval of this GPU and correct for it:
                beampos = beampos - (int) ((ReadRegister((isDCE12(screenId) ? DCE12_CRTC_V_BLANK_START_END : EVERGREEN_CRTC_V_BLANK_START_END) + crtcoff[headId]) >> 16) & RADEON_VBEAMPOSITION_BITMASK);

                // Correction for in-VBLANK range:
                if (beampos < 0) beampos = ((int) ReadRegister((isDCE12(screenId) ? DCE12_CRTC_V_TOTAL : EVERGREEN_CRTC_V_TOTAL) + crtcoff[headId])) + beampos;
            } else {
                // AVIVO / DCE-2 / DCE-3 display engine (R300 - R700 afaik): At most two display heads for dual-head gpu's.

                // Read raw beampostion from GPU:
                beampos = (int) (ReadRegister((headId == 0) ? RADEON_D1CRTC_STATUS_POSITION : RADEON_D2CRTC_STATUS_POSITION) & RADEON_VBEAMPOSITION_BITMASK);

                // Query end-offset of VBLANK interval of this GPU and correct for it:
                beampos = beampos - (int) ((ReadRegister((headId == 0) ? AVIVO_D1CRTC_V_BLANK_START_END : AVIVO_D2CRTC_V_BLANK_START_END) >> 16) & RADEON_VBEAMPOSITION_BITMASK);

                // Correction for in-VBLANK range:
                if (beampos < 0) beampos = ((int) ReadRegister((headId == 0) ? AVIVO_D1CRTC_V_TOTAL : AVIVO_D2CRTC_V_TOTAL)) + beampos;
            }
        }

        // Query code for NVidia GeForce/Quadro:
        if (fDeviceType == kPsychGeForce) {
            // Pre NV-50 GPU? [Anything before GeForce-8 series]
            if ((fCardType > 0x0) && (fCardType < 0x50)) {
                // Pre NV-50, e.g., RivaTNT-1/2 and all GeForce 256/2/3/4/5/FX/6/7:

                // Lower 12 bits are vertical scanout position (scanline), bit 16 is "in vblank" indicator.
                // Offset between crtc's is 0x2000, we're only interested in scanline, not "in vblank" status:
                // beampos = (int) (ReadRegister((headId == 0) ? 0x600808 : 0x600808 + 0x2000) & 0xFFF);

                // NV-47: Lower 16 bits are vertical scanout position (scanline), upper 16 bits are horizontal
                // scanout position. Offset between crtc's is 0x2000. We only use the lower 16 bits and
                // ignore horizontal scanout position for now:
                beampos = (int) (ReadRegister((headId == 0) ? 0x600868 : 0x600868 + 0x2000) & 0xFFFF);
            } else if ((fCardType > 0x0) && (fCardType < 0x140)) {
                // NV-50 (GeForce-8) up to and including Pascal:

                // Lower 16 bits are vertical scanout position (scanline), upper 16 bits are vblank counter.
                // Offset between crtc's is 0x800, we're only interested in scanline, not vblank counter:
                beampos = (int) (ReadRegister(0x616340 + (0x800 * headId)) & 0xFFFF);
                if (PsychPrefStateGet_Verbosity() > 11) printf("PTB-DEBUG: Head %i, HW-Vblankcount: %i\n", headId, (int) ((ReadRegister(0x616340 + (0x800 * headId)) >> 16) & 0xFFFF));

                if (FALSE && firstTime) {
                    firstTime = FALSE;
                    int newcount = -1;
                    int oldcount = (int) ((ReadRegister(0x616340 + (0x800 * headId)) >> 16) & 0xFFFF);
                    unsigned int foo;
                    while (newcount <= oldcount) {
                        foo = ReadRegister(0x616340 + (0x800 * headId));
                        newcount = (int) ((foo >> 16) & 0xFFFF);
                        beampos = (int) (foo & 0xFFFF);
                    }
                    printf("VBLIncrement %i -> %i at scanline %i\n", oldcount, newcount, beampos);
                }
            } else {
                // NV-140 Volta, NV-160 Turing, NV-170 Ampere, NV-180/190 Ada Lovelace / Hopper and later:

                // Lower 16 bits are vertical scanout position (scanline), upper 16 bits are vblank counter.
                // Offset between crtc's is 0x800, we're only interested in scanline, not vblank counter:
                beampos = (int) (ReadRegister(0x616330 + (0x800 * headId)) & 0xFFFF);
                if (PsychPrefStateGet_Verbosity() > 11) printf("PTB-DEBUG: Head %i, HW-Vblankcount: %i\n", headId, (int) ((ReadRegister(0x616330 + (0x800 * headId)) >> 16) & 0xFFFF));

                if (FALSE && firstTime) {
                    firstTime = FALSE;
                    int newcount = -1;
                    int oldcount = (int) ((ReadRegister(0x616330 + (0x800 * headId)) >> 16) & 0xFFFF);
                    unsigned int foo;
                    while (newcount <= oldcount) {
                        foo = ReadRegister(0x616330 + (0x800 * headId));
                        newcount = (int) ((foo >> 16) & 0xFFFF);
                        beampos = (int) (foo & 0xFFFF);
                    }
                    printf("VBLIncrement %i -> %i at scanline %i\n", oldcount, newcount, beampos);
                }
            }
        }

        // Query code for Intel IGP's:
        if (fDeviceType == kPsychIntelIGP) {
            beampos = (int) (ReadRegister(0x70000 + (headId * 0x1000)) & 0x1FFF);
        }

        // Safety measure: Cap to zero if something went wrong -> This will trigger proper high level error handling in PTB:
        if (beampos < 0) beampos = -1;
    }

    return(beampos);
}

// Try to change hardware dither mode on GPU:
void PsychOSKDSetDitherMode(int screenId, unsigned int ditherOn)
{
    static unsigned int oldDither[kPsychMaxPossibleCrtcs] = { 0, 0, 0, 0, 0, 0 };
    unsigned int reg;
    int headId, iter;

    // MMIO registers mapped?
    if (!gfx_cntl_mem) return;

    // Check if the method is supported for this GPU type:
    // Currently ATI/AMD GPU's only...
    if (fDeviceType != kPsychRadeon) {
        // Other unsupported GPU:
        if (PsychPrefStateGet_Verbosity() > 3) printf("PTB-INFO: SetDitherMode: Tried to call me on a non ATI/AMD GPU. Unsupported.\n");
        return;
    }

    // Start with headId undefined:
    headId = -1;

    for (iter = 0; iter < kPsychMaxPossibleCrtcs; iter++) {
        if (screenId >= 0) {
            // Positive screenId: Apply to all crtc's for this screenId:

            // Is there an iter'th crtc assigned to this screen?
            headId = PsychScreenToCrtcId(screenId, iter);

            // If end of list of associated crtc's for this screenId reached, then we're done:
            if (headId < 0) break;
        }
        else {
            // Negative screenId -> Only affect one head defined by screenId:
            if (headId < 0) {
                // Setup single target head in this iteration:
                headId = -screenId;
            }
            else {
                // Single target head already set up: We're done:
                break;
            }
        }

        // AMD/ATI Radeon, FireGL or FirePro GPU?
        if (fDeviceType == kPsychRadeon) {
            if (PsychPrefStateGet_Verbosity() > 2) printf("PTB-INFO: SetDitherMode: Trying to %s digital display dithering on display head %d.\n", (ditherOn) ? "enable" : "disable", headId);

            // Map headId to proper hardware control register offset:
            if (isDCE4(screenId) || isDCE5(screenId) || isDCE6(screenId) || isDCE8(screenId) || isDCE10(screenId) || isDCE11(screenId) || isDCE12(screenId)) {
                // DCE-4+ display engine (CEDAR and later afaik): Map to proper register offset for this headId:
                if (headId > ((int) fNumDisplayHeads - 1)) {
                    // Invalid head - bail:
                    if (PsychPrefStateGet_Verbosity() > 0) printf("SetDitherMode: ERROR! Invalid headId %d provided. Must be between 0 and %i. Aborted.\n", headId, (fNumDisplayHeads - 1));
                    continue;
                }

                // Map to dither format control register for head 'headId':
                reg = (isDCE12(screenId) ? DCE12_FMT_BIT_DEPTH_CONTROL : EVERGREEN_FMT_BIT_DEPTH_CONTROL) + crtcoff[headId];
            } else if (isDCE3(screenId)) {
                // DCE-3 display engine for R700: HD4330 - HD5165, HD5xxV, and some R600's:
                reg = (headId == 0) ? DCE3_FMT_BIT_DEPTH_CONTROL : DCE3_FMT_BIT_DEPTH_CONTROL + 0x800;
            } else {
                // AVIVO / DCE-1 / DCE-2 display engine (R300 - R600 afaik): At most two display heads for dual-head gpu's.

                // These have a weird wiring of encoders/transmitters to output connectors with no simple 1:1 correspondence
                // between crtc's and encoders. We need to probe each encoder block if it is enabled and sourcing from our headId,
                // respective its corresponding crtc to find which encoder block needs to be configured wrt. dithering on this
                // display headId:
                reg = 0x0;

                // TMDSA block enabled, and driven by headId? Then we control its encoder:
                if ((ReadRegister(0x7880) & 0x1) && ((ReadRegister(0x7884) & 0x1) == (unsigned int) headId)) reg = RADEON_TMDSA_BIT_DEPTH_CONTROL;

                // LVTMA block enabled, and driven by headId? Then we control its encoder:
                if ((ReadRegister(0x7A80) & 0x1) && ((ReadRegister(0x7A84) & 0x1) == (unsigned int) headId)) reg = RADEON_LVTMA_BIT_DEPTH_CONTROL;

                // DVOA block enabled, and driven by headId? Then we control its encoder:
                if ((ReadRegister(0x7980) & 0x1) && ((ReadRegister(0x7984) & 0x1) == (unsigned int) headId)) reg = RADEON_DVOA_BIT_DEPTH_CONTROL;

                // If no digital encoder block was assigned, then this likely means we're connected to a
                // analog VGA monitor driven by the DAC. The DAC doesn't have dithering ever, so we are
                // done with a simple no-op:
                if (reg == 0x0) {
                    if (PsychPrefStateGet_Verbosity() > 2) printf("PTB-INFO: SetDitherMode: Screen %i, head %i connected to analog VGA DAC. Dithering control skipped.\n", screenId, headId);
                    continue;
                }
                else if (PsychPrefStateGet_Verbosity() > 3) {
                    switch (reg) {
                        case RADEON_TMDSA_BIT_DEPTH_CONTROL:
                            printf("PTB-INFO: SetDitherMode: Screen %i, head %i connected to TMDSA block.\n", screenId, headId);
                        break;

                        case RADEON_LVTMA_BIT_DEPTH_CONTROL:
                            printf("PTB-INFO: SetDitherMode: Screen %i, head %i connected to LVTMA block.\n", screenId, headId);
                        break;

                        case RADEON_DVOA_BIT_DEPTH_CONTROL:
                            printf("PTB-INFO: SetDitherMode: Screen %i, head %i connected to DVOA block.\n", screenId, headId);
                        break;
                    }
                }
            }

            // Perform actual enable/disable/reconfigure sequence for target encoder/head:

            // Enable dithering?
            if (ditherOn) {
                // Special ditherOn value specified?
                if (ditherOn == 0xffffffff) {
                    // Magic 0xffffffff means to check if (spatial) dithering is effectively off, and if so,
                    // to enable it to dither down to 10 bpc. This is some special-case handling for output
                    // of > 10 bpc fb content to a == 10 bpc video output sink on AMD DCE-8+ display engines,
                    // for which the display driver does not handle the "dither to 10 bpc" case, but only the
                    // "dither to 6/8 bpc" case. It is exclusively called by PsychOSEnsureMinimumOutputPrecision()
                    // for DCE8/10/11/12 iff > 10 bpc content is sent to outputs restricted to max 10 bpc, iow.
                    // to outputs where dithering must be used for precise display, and therefore enabled either
                    // by the Linux amdgpu DC display driver itself, or by us here with this hack:
                    unsigned int val = ReadRegister(reg);
                    if ((val & (0x100 | 0x10000)) == 0) { // SPATIAL_DITHER_EN | TEMPORAL_DITHER_EN ?
                        // Spatial/Temporal dithering disabled, because driver chickened out on doing this
                        // for a target depth of 10 bpc -- it would have enabled it automatically for 6
                        // or 8 bpc, therefore from it being off we can conclude it is off because the 10 bpc
                        // case applies and the driver didn't do the enable. Enforce spatial dithering to 10 bpc
                        // manually with the following magic value from Linux DC function
                        // ./drivers/gpu/drm/amd/display/dc/core/dc_resource.c line 2735 in Linux 5.9, ie. the function resource_build_bit_depth_reduction_params():
                        val = 0xd100; // == SPATIAL_DITHER_EN=1, SPATIAL_DITHER_DEPTH=2 (10bpc), RGB_RANDOM_ENABLE 1, HIGHPASS_RANDOM_ENABLE 1, FRAME_RANDOM_ENABLE 0.

                        // Note that this 0xd100 setting seems to work well at least on the tested POLARIS11 gpu with DCE11.2 display engine.
                        if (PsychPrefStateGet_Verbosity() > 2) printf("PTB-INFO: SetDitherMode: Setting dithering mode to special dither-down-to-10bpc setting 0x%x. Cross your fingers!\n", val);
                        WriteRegister(reg, val);
                    }
                    else {
                        if (PsychPrefStateGet_Verbosity() > 2) printf("PTB-INFO: SetDitherMode: Dithering according to setting 0x%x already active.\n", val);
                    }
                }
                else {
                    // Regular dither enable/set path:

                    // Dithering currently off (all zeros)?
                    if (ReadRegister(reg) == 0) {
                        // Dithering is currently off. Do we know the old setting from a previous
                        // disable?
                        if (oldDither[headId] > 0) {
                            // Yes: Restore old "factory settings":
                            if (PsychPrefStateGet_Verbosity() > 2) printf("PTB-INFO: SetDitherMode: Dithering previously disabled by us. Reenabling with old control setting 0x%x.\n", oldDither[headId]);
                            WriteRegister(reg, oldDither[headId]);
                        }
                        else {
                            // No: Dithering was disabled all the time, so we don't know the
                            // OS defaults. Use the numeric value of 'ditherOn' itself:
                            if (PsychPrefStateGet_Verbosity() > 2) printf("PTB-INFO: SetDitherMode: Dithering off. Enabling with userspace provided setting 0x%x. Cross your fingers!\n", ditherOn);
                            WriteRegister(reg, ditherOn);
                        }
                    }
                    else {
                        // Dithering currently on - or at least bit depth reduction is not totally off, as all-zeros would imply.
                        // Shall we literally use the value provided by ditherOn?
                        if (ditherOn > 1) {
                            // Yes. Use it "as is":
                            if (PsychPrefStateGet_Verbosity() > 2) printf("PTB-INFO: SetDitherMode: Setting dithering mode to userspace provided setting 0x%x. Cross your fingers!\n", ditherOn);
                            WriteRegister(reg, ditherOn);
                        }
                        else if (PsychPrefStateGet_Verbosity() > 2) printf("PTB-INFO: SetDitherMode: Dithering already enabled with current control value 0x%x. Skipped.\n", ReadRegister(reg));
                    }
                }
            }
            else {
                // Disable all dithering if it is enabled: Clearing the register to all zero bits does this.
                if (ReadRegister(reg) != 0) {
                    oldDither[headId] = ReadRegister(reg);
                    if (PsychPrefStateGet_Verbosity() > 2) printf("PTB-INFO: SetDitherMode: Current dither setting before our dither disable on head %d is 0x%x. Disabling.\n", headId, oldDither[headId]);
                    WriteRegister(reg, 0x0);
                }
                else {
                    if (PsychPrefStateGet_Verbosity() > 2) printf("PTB-INFO: SetDitherMode: Dithering already disabled. Skipped.\n");
                }
            }
            // End of Radeon et al. support code.
        }
        // Next head for this screenId, if any...
    }

    return;
}

unsigned int PsychOSGetRegammaMode(unsigned int screenId, unsigned int offset)
{
    return(ReadRegister((isDCE12(screenId) ? DCE12_REGAMMA_CONTROL : NI_REGAMMA_CONTROL) + offset) & 0x7);
}

// Query if LUT for given headId is all-zero: 0 = Something else, 1 = Zero-LUT, 2 = It's an identity LUT,
// 3 = Not-quite-identity mapping, 0xffffffff = don't know.
unsigned int PsychOSKDGetLUTState(int screenId, unsigned int headId, unsigned int debug)
{
    unsigned int i, v, r, m, bo, wo, offset, reg;
    unsigned int isZero = 1;
    unsigned int isIdentity = 1;

    // AMD GPU's:
    if (fDeviceType == kPsychRadeon) {
        if (PsychPrefStateGet_Verbosity() > 3) printf("PsychOSKDGetLUTState(): Checking LUT and bias values on GPU for headId %d.\n", headId);

        if (isDCE4(screenId) || isDCE5(screenId) || isDCE10(screenId) || isDCE11(screenId) || isDCE12(screenId)) {
            // DCE-4.0 and later: Up to (so far) six display heads:
            if (headId > (fNumDisplayHeads - 1)) {
                // Invalid head - bail:
                if (PsychPrefStateGet_Verbosity() > 2) printf("PsychOSKDGetLUTState: ERROR! Invalid headId %d provided. Must be between 0 and %i. Aborted.\n", headId, (fNumDisplayHeads - 1));
                return(0xffffffff);
            }

            offset = crtcoff[headId];

            // Skip disabled display engines: Just return "don't know" 0xffffffff:
            // Probe for crtc master disable, inactive or no memory read requests active. Note: Often not effective...
            v = ReadRegister((isDCE12(screenId) ? DCE12_CRTC_CONTROL : EVERGREEN_CRTC_CONTROL) + offset);
            if ((v & (EVERGREEN_CRTC_MASTER_EN | (0x1 << 16)) == 0) || (!isDCE12(screenId) && (v & EVERGREEN_CRTC_DISP_READ_REQUEST_DISABLE))) {
                if (PsychPrefStateGet_Verbosity() > 3)
                    printf("PsychOSKDGetLUTState(): Skipping headId %d as it is disabled [EVERGREEN_CRTC_CONTROL]\n", headId);

                return(0xffffffff);
            }

            // Probe for crtc blanked. Note: Often not effective...
            v = ReadRegister((isDCE12(screenId) ? DCE12_CRTC_BLANK_CONTROL : EVERGREEN_CRTC_BLANK_CONTROL) + offset);
            if (v & EVERGREEN_CRTC_BLANK_DATA_EN) {
                if (PsychPrefStateGet_Verbosity() > 3)
                    printf("PsychOSKDGetLUTState(): Skipping headId %d as it is disabled [EVERGREEN_CRTC_BLANK_CONTROL].\n", headId);

                return(0xffffffff);
            }

            // Probe for graphics enable off:
            v = ReadRegister((isDCE12(screenId) ? DCE12_GRPH_ENABLE : EVERGREEN_GRPH_ENABLE) + offset);
            if (v == 0) {
                if (PsychPrefStateGet_Verbosity() > 3)
                    printf("PsychOSKDGetLUTState(): Skipping headId %d as it is disabled [EVERGREEN_GRPH_ENABLE].\n", headId);

                return(0xffffffff);
            }

            // DCE-12 / Vega always uses display core:
            amdgpuUsesDisplayCore |= isDCE12(screenId) ? TRUE : FALSE;

            // If even only one of the display engines does use a NI_GRPH_REGAMMA_MODE other than NI_REGAMMA_BYPASS,
            // then this indicates that an amdgpu-kms driver with the new AMD DC "DisplayCore" is in use. Our startup
            // default is amdgpuUsesDisplayCore == FALSE, but we switch to TRUE as soon as we find this hint of DC:
            amdgpuUsesDisplayCore |= (PsychOSGetRegammaMode(screenId, offset) != NI_REGAMMA_BYPASS) ? TRUE : FALSE;
            if (amdgpuUsesDisplayCore) {
                if (PsychPrefStateGet_Verbosity() > 3)
                    printf("PsychOSKDGetLUTState(): headId %d [Offset 0x%x] uses DC and REGAMMA_LUT [%i].\n",
                            headId, offset, PsychOSGetRegammaMode(screenId, offset));
            }
            else {
                if (PsychPrefStateGet_Verbosity() > 3)
                    printf("PsychOSKDGetLUTState(): headId %d [Offset 0x%x] uses old modesetting with REGAMMA_LUT [%i].\n",
                            headId, offset, PsychOSGetRegammaMode(screenId, offset));
            }

            // Use the classic code-path if DisplayCore is not used, or if regamma control is not
            // set to user-defined (value 3 or 4), as in those cases, the pwl lut won't be used.
            // Before Linux 4.17, AMD DC didn't allow user-controlled regamma and set a fixed SRGB
            // mode (value 1). Since 4.17, atomic color management is supported, and seems to result
            // in use of mode 3 == user defined.
            // Evidence: New code-path in else-branch is needed on POLARIS11 + Linux 4.20 and 5.0, but
            // does not work on same POLARIS11 with Linux 4.15, where the regamma mode is 1 (SRGB fixed)
            // instead of 3 (user programmable). Let's hope this is the final word on this...
            if (!isDCE12(screenId) && (!amdgpuUsesDisplayCore || (PsychOSGetRegammaMode(screenId, offset) < 3))) {
                // Classic code path for radeon-kms and amdgpu-kms without DC/DAL on pre-DCE12 hardware.
                // Uses 256-slot 10 bit wide standard LUT:
                if ((ReadRegister(EVERGREEN_DC_LUT_CONTROL + offset) & 0xf) != 0) {
                    if (PsychPrefStateGet_Verbosity() > 3)
                        printf("PsychOSKDGetLUTState(): Skipping headId %d as LUT not in 256-slot mode [%i].\n",
                                headId, ReadRegister(EVERGREEN_DC_LUT_CONTROL + offset) & 0xf);

                    return(0xffffffff);
                }

                WriteRegister(EVERGREEN_DC_LUT_RW_MODE + offset, 0);
                WriteRegister(EVERGREEN_DC_LUT_RW_INDEX + offset, 0);
                reg = EVERGREEN_DC_LUT_30_COLOR + offset;
            }
            else {
                // New amdgpu-kms with DC/DAL on Linux 4.17+. Uses REGAMMA_LUT:
                WriteRegister((isDCE12(screenId) ? DCE12_REGAMMA_LUT_WRITE_EN_MASK : NI_REGAMMA_LUT_WRITE_EN_MASK) + offset, 0);
                WriteRegister((isDCE12(screenId) ? DCE12_REGAMMA_LUT_INDEX : NI_REGAMMA_LUT_INDEX) + offset, 0);
                reg = (isDCE12(screenId) ? DCE12_REGAMMA_LUT_DATA : NI_REGAMMA_LUT_DATA) + offset;
            }

            // Find out if there are non-zero black offsets:
            bo = 0x0;
            bo|= ReadRegister((isDCE12(screenId) ? DCE12_DC_LUT_BLACK_OFFSET_BLUE : EVERGREEN_DC_LUT_BLACK_OFFSET_BLUE) + offset);
            bo|= ReadRegister((isDCE12(screenId) ? DCE12_DC_LUT_BLACK_OFFSET_GREEN : EVERGREEN_DC_LUT_BLACK_OFFSET_GREEN) + offset);
            bo|= ReadRegister((isDCE12(screenId) ? DCE12_DC_LUT_BLACK_OFFSET_RED : EVERGREEN_DC_LUT_BLACK_OFFSET_RED) + offset);

            // Find out if there are non-0xffff white offsets:
            wo = 0x0;
            wo|= 0xffff - ReadRegister((isDCE12(screenId) ? DCE12_DC_LUT_WHITE_OFFSET_BLUE : EVERGREEN_DC_LUT_WHITE_OFFSET_BLUE) + offset);
            wo|= 0xffff - ReadRegister((isDCE12(screenId) ? DCE12_DC_LUT_WHITE_OFFSET_GREEN : EVERGREEN_DC_LUT_WHITE_OFFSET_GREEN) + offset);
            wo|= 0xffff - ReadRegister((isDCE12(screenId) ? DCE12_DC_LUT_WHITE_OFFSET_RED : EVERGREEN_DC_LUT_WHITE_OFFSET_RED) + offset);
        }
        else {
            // AVIVO: Dualhead.
            offset = (headId > 0) ? 0x800 : 0x0;
            WriteRegister(AVIVO_DC_LUT_RW_SELECT, headId & 0x1);
            WriteRegister(AVIVO_DC_LUT_RW_MODE, 0);
            WriteRegister(AVIVO_DC_LUT_RW_INDEX, 0);
            reg = AVIVO_DC_LUT_30_COLOR;

            // Find out if there are non-zero black offsets:
            bo = 0x0;
            bo|= ReadRegister(AVIVO_DC_LUTA_BLACK_OFFSET_BLUE + offset);
            bo|= ReadRegister(AVIVO_DC_LUTA_BLACK_OFFSET_GREEN + offset);
            bo|= ReadRegister(AVIVO_DC_LUTA_BLACK_OFFSET_RED + offset);

            // Find out if there are non-0xffff white offsets:
            wo = 0x0;
            wo|= 0xffff - ReadRegister(AVIVO_DC_LUTA_WHITE_OFFSET_BLUE + offset);
            wo|= 0xffff - ReadRegister(AVIVO_DC_LUTA_WHITE_OFFSET_GREEN + offset);
            wo|= 0xffff - ReadRegister(AVIVO_DC_LUTA_WHITE_OFFSET_RED + offset);
        }

        if (debug) if (PsychPrefStateGet_Verbosity() > 3) printf("PsychOSKDOffsets: Black %d : White %d.\n", bo, wo);

        if (amdgpuUsesDisplayCore) {
            // DC in use: REGAMMA_LUT's are used, with some custom floating point
            // piece-wise-linear encoding of the LUT of style redbase, redslope,
            // greenbase, greenslope, bluebase, blueslope, ie. 6 values per input
            // LUT slot to define one line segment, and then at least 160 segments,
            // for a total of at least 160 * 6 = 960 values. Some early DC versions
            // used even more segments.
            // Trying to decode the values into something meaningful is pretty
            // hopeless, given the complexity of the hw programming and approximation
            // algorithms used to fit the pwl segments to the gamma lut input curve,
            // and given that these algorithms are still subject to change.
            // Testing if we have an identity lut, or creating one, is therefore a
            // no-go. What we still can do is test for an all-zero LUT, as that still
            // maps to all-zeros in the hw lut's. Iow. our trick for finding the
            // output -> display engine mappings should still work, but checking for
            // passthrough lut's, or setting them ourselves is not workable in the future.
            // For reference: Function "static void program_pwl()" in
            // linux/drivers/gpu/drm/amd/display/dc/dce/dce_transform.c is our main actor,
            // as of Linux 4.18.

            // Under DC our assumption is that if regamma lut is bypassed, then we get our desirable
            // identity mapping, even though we can not actually set the regamma lut to identity, but
            // bypass obviously means that doesn't matter. However, there are other things that can
            // mess with us, so this may not be the last word on the matter... ... to be verified.
            isIdentity = (PsychOSGetRegammaMode(screenId, offset) == NI_REGAMMA_BYPASS) ? TRUE : FALSE;

            // An identity LUT y=x implies it is not an all-zero LUT y=0:
            if (isIdentity) {
                if (PsychPrefStateGet_Verbosity() > 3) printf("PsychOSKDGetLUTState(): headId %d: Identity/Bypass LUT, therefore not a zero LUT.\n", headId);
                isZero = 0;
            }

            // Use a slight variant of the classic path in the else-branch. Read the
            // 256 slot lut registers and just check for all-zero vs. not-all-zero to
            // do the detection, as the 256 legacy lut seems to get mirrored by the hw
            // from the new pwl lut. isIdentity detection is done the new way though,
            // as the lut values we read can't be meaningfully interpreted beyond the
            // "is it all zeros?" check:
            for (i = 0; i < 256; i++) {
                // Read 32 bit value of this slot, mask out upper 2 bits,
                // so the least significant 30 bits are left, as these
                // contain the 3 * 10 bits for the 10 bit R,G,B channels:
                v = ReadRegister(reg) & (0xffffffff >> 2);

                // All zero as they should be for a all-zero LUT?
                if (v > 0) isZero = 0;

                if (PsychPrefStateGet_Verbosity() > 4) {
                    printf("%d:%d,%d,%d\n", i, (v >> 20) & 0x3ff, (v >> 10) & 0x3ff, (v >> 0) & 0x3ff);
                }
            }
        } else {
            for (i = 0; i < 256; i++) {
                // Read 32 bit value of this slot, mask out upper 2 bits,
                // so the least significant 30 bits are left, as these
                // contain the 3 * 10 bits for the 10 bit R,G,B channels:
                v = ReadRegister(reg) & (0xffffffff >> 2);

                // All zero as they should be for a all-zero LUT?
                if (v > 0) isZero = 0;

                // Compare with expected value in slot i for a perfect 10 bit identity LUT
                // intended for a 8 bit output encoder, i.e., 2 least significant bits
                // zero to avoid dithering and similar stuff:
                r = i << 2;
                m = (r << 20) | (r << 10) | (r << 0);

                // Mismatch? Not a perfect identity LUT:
                if (v != m) isIdentity = 0;

                if (PsychPrefStateGet_Verbosity() > 4) {
                    printf("%d:%d,%d,%d\n", i, (v >> 20) & 0x3ff, (v >> 10) & 0x3ff, (v >> 0) & 0x3ff);
                }
            }
        }

        if (isZero) return(1);  // All zero LUT.

        if (isIdentity) {
            // If wo or bo is non-zero then it is not quite an identity
            // mapping, as the black and white offset are not neutral.
            // Return 3 in this case:
            if ((wo | bo) > 0) return(3);

            // Perfect identity LUT:
            return(2);
        }

        // Regular LUT:
        return(0);
    }

    // Unhandled:
    if (PsychPrefStateGet_Verbosity() > 3) printf("PsychOSKDGetLUTState(): This function is not supported on this GPU. Returning 0xffffffff.\n");
    return(0xffffffff);
}

// Load an identity LUT into display head 'headid': Return 1 on success, 0 on failure or if unsupported for this GPU:
unsigned int PsychOSKDLoadIdentityLUT(int screenId, unsigned int headId)
{
    unsigned int i, r, m, offset, reg;

    // AMD GPU's:
    if ((fDeviceType == kPsychRadeon) && !isDCE12(screenId)) {
        if (PsychPrefStateGet_Verbosity() > 3) printf("PsychOSKDLoadIdentityLUT(): Uploading identity LUT and bias values into GPU for headId %d.\n", headId);

        if (isDCE4(screenId) || isDCE5(screenId) || isDCE10(screenId) || isDCE11(screenId)) {
            // DCE-4.0+ and later: Up to (so far) six display heads:
            if (headId > (fNumDisplayHeads - 1)) {
                // Invalid head - bail:
                if (PsychPrefStateGet_Verbosity() > 3) printf("PsychOSKDLoadIdentityLUT: ERROR! Invalid headId %d provided. Must be between 0 and %i. Aborted.\n", headId, (fNumDisplayHeads - 1));
                return(0);
            }

            offset = crtcoff[headId];
            reg = EVERGREEN_DC_LUT_30_COLOR + offset;

            WriteRegister(EVERGREEN_DC_LUT_CONTROL + offset, 0);

            if (isDCE5(screenId) || isDCE10(screenId)) {
                WriteRegister(NI_INPUT_CSC_CONTROL + offset,
                              (NI_INPUT_CSC_GRPH_MODE(NI_INPUT_CSC_BYPASS) |
                               NI_INPUT_CSC_OVL_MODE(NI_INPUT_CSC_BYPASS)));
                WriteRegister(NI_PRESCALE_GRPH_CONTROL + offset,
                              NI_GRPH_PRESCALE_BYPASS);
                WriteRegister(NI_PRESCALE_OVL_CONTROL + offset,
                              NI_OVL_PRESCALE_BYPASS);
                WriteRegister(NI_INPUT_GAMMA_CONTROL + offset,
                              (NI_GRPH_INPUT_GAMMA_MODE(NI_INPUT_GAMMA_USE_LUT) |
                               NI_OVL_INPUT_GAMMA_MODE(NI_INPUT_GAMMA_USE_LUT)));
            }

            // Set zero black offsets:
            WriteRegister(EVERGREEN_DC_LUT_BLACK_OFFSET_BLUE  + offset, 0x0);
            WriteRegister(EVERGREEN_DC_LUT_BLACK_OFFSET_GREEN + offset, 0x0);
            WriteRegister(EVERGREEN_DC_LUT_BLACK_OFFSET_RED   + offset, 0x0);

            // Set 0xffff white offsets:
            WriteRegister(EVERGREEN_DC_LUT_WHITE_OFFSET_BLUE  + offset, 0xffff);
            WriteRegister(EVERGREEN_DC_LUT_WHITE_OFFSET_GREEN + offset, 0xffff);
            WriteRegister(EVERGREEN_DC_LUT_WHITE_OFFSET_RED   + offset, 0xffff);

            WriteRegister(EVERGREEN_DC_LUT_RW_MODE + offset, 0);
            WriteRegister(EVERGREEN_DC_LUT_WRITE_EN_MASK + offset, 0x00000007);

            WriteRegister(EVERGREEN_DC_LUT_RW_INDEX + offset, 0);

        }
        else {
            // AVIVO: Dualhead.
            offset = (headId > 0) ? 0x800 : 0x0;
            reg = AVIVO_DC_LUT_30_COLOR;

            WriteRegister(AVIVO_DC_LUTA_CONTROL + offset, 0);

            // Set zero black offsets:
            WriteRegister(AVIVO_DC_LUTA_BLACK_OFFSET_BLUE  + offset, 0x0);
            WriteRegister(AVIVO_DC_LUTA_BLACK_OFFSET_GREEN + offset, 0x0);
            WriteRegister(AVIVO_DC_LUTA_BLACK_OFFSET_RED   + offset, 0x0);

            // Set 0xffff white offsets:
            WriteRegister(AVIVO_DC_LUTA_WHITE_OFFSET_BLUE  + offset, 0xffff);
            WriteRegister(AVIVO_DC_LUTA_WHITE_OFFSET_GREEN + offset, 0xffff);
            WriteRegister(AVIVO_DC_LUTA_WHITE_OFFSET_RED   + offset, 0xffff);

            WriteRegister(AVIVO_DC_LUT_RW_SELECT, headId & 0x1);
            WriteRegister(AVIVO_DC_LUT_RW_MODE, 0);
            WriteRegister(AVIVO_DC_LUT_WRITE_EN_MASK, 0x0000003f);

            WriteRegister(AVIVO_DC_LUT_RW_INDEX, 0);
        }

        for (i = 0; i < 256; i++) {
            // Compute perfect value for slot i for a perfect 10 bit identity LUT
            // intended for a 8 bit output encoder, i.e., 2 least significant bits
            // zero to avoid dithering and similar stuff, the 8 most significant
            // bits for each 10 bit color channel linearly increasing one unit
            // per slot:
            r = i << 2;
            m = (r << 20) | (r << 10) | (r << 0);

            // Write 32 bit value of this slot:
            WriteRegister(reg, m);
        }

        if (isDCE5(screenId) || isDCE10(screenId)) {
            WriteRegister(NI_DEGAMMA_CONTROL + offset,
                          (NI_GRPH_DEGAMMA_MODE(NI_DEGAMMA_BYPASS) |
                           NI_OVL_DEGAMMA_MODE(NI_DEGAMMA_BYPASS) |
                           NI_ICON_DEGAMMA_MODE(NI_DEGAMMA_BYPASS) |
                           NI_CURSOR_DEGAMMA_MODE(NI_DEGAMMA_BYPASS)));
            WriteRegister(NI_GAMUT_REMAP_CONTROL + offset,
                          (NI_GRPH_GAMUT_REMAP_MODE(NI_GAMUT_REMAP_BYPASS) |
                           NI_OVL_GAMUT_REMAP_MODE(NI_GAMUT_REMAP_BYPASS)));
            WriteRegister(NI_REGAMMA_CONTROL + offset,
                          (NI_GRPH_REGAMMA_MODE(NI_REGAMMA_BYPASS) |
                           NI_OVL_REGAMMA_MODE(NI_REGAMMA_BYPASS)));
            WriteRegister(NI_OUTPUT_CSC_CONTROL + offset,
                          (NI_OUTPUT_CSC_GRPH_MODE(NI_OUTPUT_CSC_BYPASS) |
                           NI_OUTPUT_CSC_OVL_MODE(NI_OUTPUT_CSC_BYPASS)));
            /* XXX match this to the depth of the crtc fmt block, move to modeset? */
            WriteRegister(0x6940 + offset, 0);
        }

        // Done.
        return(1);
    }

    // Unhandled:
    if (PsychPrefStateGet_Verbosity() > 3) printf("PsychOSKDLoadIdentityLUT(): This function is not supported on this GPU. Returning 0.\n");
    return(0);
}