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

/*
 * Copyright (c) 1997-2003 by The XFree86 Project, Inc.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
 * THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
 * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
 * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 * OTHER DEALINGS IN THE SOFTWARE.
 *
 * Except as contained in this notice, the name of the copyright holder(s)
 * and author(s) shall not be used in advertising or otherwise to promote
 * the sale, use or other dealings in this Software without prior written
 * authorization from the copyright holder(s) and author(s).
 */

/*
 * Authors: Dirk Hohndel <hohndel@XFree86.Org>
 *          David Dawes <dawes@XFree86.Org>
 *          ... and others
 *
 * This file includes the helper functions that the server provides for
 * different drivers.
 */

#ifdef HAVE_XORG_CONFIG_H
#include <xorg-config.h>
#endif

#include <X11/X.h>
#include "os.h"
#include "servermd.h"
#include "pixmapstr.h"
#include "windowstr.h"
#include "propertyst.h"
#include "gcstruct.h"
#include "loaderProcs.h"
#include "xf86.h"
#include "xf86Priv.h"
#include "xf86_OSlib.h"
#include "micmap.h"
#include "xf86PciInfo.h"
#include "xf86DDC.h"
#include "xf86Xinput.h"
#include "xf86InPriv.h"
#include "mivalidate.h"
#include "xf86RAC.h"
#include "xf86Bus.h"
#include "xf86Version.h"

/* For xf86GetClocks */
#if defined(CSRG_BASED) || defined(__GNU__)
#define HAS_SETPRIORITY
#include <sys/resource.h>
#endif

static int xf86ScrnInfoPrivateCount = 0;


/* Add a pointer to a new DriverRec to xf86DriverList */

_X_EXPORT void
xf86AddDriver(DriverPtr driver, pointer module, int flags)
{
    /* Don't add null entries */
    if (!driver)
	return;

    if (xf86DriverList == NULL)
	xf86NumDrivers = 0;

    xf86NumDrivers++;
    xf86DriverList = xnfrealloc(xf86DriverList,
				xf86NumDrivers * sizeof(DriverPtr));
    xf86DriverList[xf86NumDrivers - 1] = xnfalloc(sizeof(DriverRec));
    if (flags & HaveDriverFuncs)
	*xf86DriverList[xf86NumDrivers - 1] = *driver;
    else {
	(void) memset( xf86DriverList[xf86NumDrivers - 1], 0,
		       sizeof( DriverRec ) );
	(void) memcpy( xf86DriverList[xf86NumDrivers - 1], driver, 
		       sizeof(DriverRec1));

    }
    xf86DriverList[xf86NumDrivers - 1]->module = module;
    xf86DriverList[xf86NumDrivers - 1]->refCount = 0;
}

_X_EXPORT void
xf86DeleteDriver(int drvIndex)
{
    if (xf86DriverList[drvIndex]
	&& (!xf86DriverHasEntities(xf86DriverList[drvIndex]))) {
	if (xf86DriverList[drvIndex]->module)
	    UnloadModule(xf86DriverList[drvIndex]->module);
	xfree(xf86DriverList[drvIndex]);
	xf86DriverList[drvIndex] = NULL;
    }
}

/* Add a pointer to a new InputDriverRec to xf86InputDriverList */

_X_EXPORT void
xf86AddInputDriver(InputDriverPtr driver, pointer module, int flags)
{
    /* Don't add null entries */
    if (!driver)
	return;

    if (xf86InputDriverList == NULL)
	xf86NumInputDrivers = 0;

    xf86NumInputDrivers++;
    xf86InputDriverList = xnfrealloc(xf86InputDriverList,
				xf86NumInputDrivers * sizeof(InputDriverPtr));
    xf86InputDriverList[xf86NumInputDrivers - 1] =
				xnfalloc(sizeof(InputDriverRec));
    *xf86InputDriverList[xf86NumInputDrivers - 1] = *driver;
    xf86InputDriverList[xf86NumInputDrivers - 1]->module = module;
    xf86InputDriverList[xf86NumInputDrivers - 1]->refCount = 0;
}

void
xf86DeleteInputDriver(int drvIndex)
{
    if (xf86InputDriverList[drvIndex] && xf86InputDriverList[drvIndex]->module)
	UnloadModule(xf86InputDriverList[drvIndex]->module);
    xfree(xf86InputDriverList[drvIndex]);
    xf86InputDriverList[drvIndex] = NULL;
}

_X_EXPORT void
xf86AddModuleInfo(ModuleInfoPtr info, pointer module)
{
    /* Don't add null entries */
    if (!module)
	return;

    if (xf86ModuleInfoList == NULL)
	xf86NumModuleInfos = 0;

    xf86NumModuleInfos++;
    xf86ModuleInfoList = xnfrealloc(xf86ModuleInfoList,
				    xf86NumModuleInfos * sizeof(ModuleInfoPtr));
    xf86ModuleInfoList[xf86NumModuleInfos - 1] = xnfalloc(sizeof(ModuleInfoRec));
    *xf86ModuleInfoList[xf86NumModuleInfos - 1] = *info;
    xf86ModuleInfoList[xf86NumModuleInfos - 1]->module = module;
    xf86ModuleInfoList[xf86NumModuleInfos - 1]->refCount = 0;
}

_X_EXPORT void
xf86DeleteModuleInfo(int idx)
{
    if (xf86ModuleInfoList[idx]) {
	if (xf86ModuleInfoList[idx]->module)
	    UnloadModule(xf86ModuleInfoList[idx]->module);
	xfree(xf86ModuleInfoList[idx]);
	xf86ModuleInfoList[idx] = NULL;
    }
}


/* Allocate a new ScrnInfoRec in xf86Screens */

_X_EXPORT ScrnInfoPtr
xf86AllocateScreen(DriverPtr drv, int flags)
{
    int i;

    if (xf86Screens == NULL)
	xf86NumScreens = 0;

    i = xf86NumScreens++;
    xf86Screens = xnfrealloc(xf86Screens, xf86NumScreens * sizeof(ScrnInfoPtr));
    xf86Screens[i] = xnfcalloc(sizeof(ScrnInfoRec), 1);
    xf86Screens[i]->scrnIndex = i;	/* Changes when a screen is removed */
    xf86Screens[i]->origIndex = i;	/* This never changes */
    xf86Screens[i]->privates = xnfcalloc(sizeof(DevUnion),
					 xf86ScrnInfoPrivateCount);
    /*
     * EnableDisableFBAccess now gets initialized in InitOutput()
     * xf86Screens[i]->EnableDisableFBAccess = xf86EnableDisableFBAccess;
     */

    xf86Screens[i]->drv = drv;
    drv->refCount++;
    xf86Screens[i]->module = DuplicateModule(drv->module, NULL);
    /*
     * set the initial access state. This will be modified after PreInit.
     * XXX Or should we do it some other place?
     */
    xf86Screens[i]->CurrentAccess = &xf86CurrentAccess;
    xf86Screens[i]->resourceType = MEM_IO;

#ifdef DEBUG
    /* OOps -- What's this ? */
    ErrorF("xf86AllocateScreen - xf86Screens[%d]->pScreen = %p\n",
	   i, xf86Screens[i]->pScreen );
    if ( NULL != xf86Screens[i]->pScreen ) {
      ErrorF("xf86Screens[%d]->pScreen->CreateWindow = %p\n",
	     i, xf86Screens[i]->pScreen->CreateWindow );
    }
#endif

    xf86Screens[i]->DriverFunc = drv->driverFunc;
    
    return xf86Screens[i];
}


/*
 * Remove an entry from xf86Screens.  Ideally it should free all allocated
 * data.  To do this properly may require a driver hook.
 */

_X_EXPORT void
xf86DeleteScreen(int scrnIndex, int flags)
{
    ScrnInfoPtr pScrn;
    int i;

    /* First check if the screen is valid */
    if (xf86NumScreens == 0 || xf86Screens == NULL)
	return;

    if (scrnIndex > xf86NumScreens - 1)
	return;

    if (!(pScrn = xf86Screens[scrnIndex]))
	return;

    /* If a FreeScreen function is defined, call it here */
    if (pScrn->FreeScreen != NULL)
	pScrn->FreeScreen(scrnIndex, 0);

    while (pScrn->modes)
	xf86DeleteMode(&pScrn->modes, pScrn->modes);

    while (pScrn->modePool)
	xf86DeleteMode(&pScrn->modePool, pScrn->modePool);

    xf86OptionListFree(pScrn->options);

    if (pScrn->module)
	UnloadModule(pScrn->module);

    if (pScrn->drv)
	pScrn->drv->refCount--;

    if (pScrn->privates)
	xfree(pScrn->privates);

    xf86ClearEntityListForScreen(scrnIndex);

    xfree(pScrn);

    /* Move the other entries down, updating their scrnIndex fields */
    
    xf86NumScreens--;

    for (i = scrnIndex; i < xf86NumScreens; i++) {
	xf86Screens[i] = xf86Screens[i + 1];
	xf86Screens[i]->scrnIndex = i;
	/* Also need to take care of the screen layout settings */
    }
}

/*
 * Allocate a private in ScrnInfoRec.
 */

_X_EXPORT int
xf86AllocateScrnInfoPrivateIndex(void)
{
    int idx, i;
    ScrnInfoPtr pScr;
    DevUnion *nprivs;

    idx = xf86ScrnInfoPrivateCount++;
    for (i = 0; i < xf86NumScreens; i++) {
	pScr = xf86Screens[i];
	nprivs = xnfrealloc(pScr->privates,
			    xf86ScrnInfoPrivateCount * sizeof(DevUnion));
	/* Zero the new private */
	bzero(&nprivs[idx], sizeof(DevUnion));
	pScr->privates = nprivs;
    }
    return idx;
}

/* Allocate a new InputInfoRec and add it to the head xf86InputDevs. */

_X_EXPORT InputInfoPtr
xf86AllocateInput(InputDriverPtr drv, int flags)
{
    InputInfoPtr new;

    if (!(new = xcalloc(sizeof(InputInfoRec), 1)))
	return NULL;

    new->drv = drv;
    drv->refCount++;
    new->module = DuplicateModule(drv->module, NULL);
    new->next = xf86InputDevs;
    xf86InputDevs = new;
    return new;
}


/*
 * Remove an entry from xf86InputDevs.  Ideally it should free all allocated
 * data.  To do this properly may require a driver hook.
 */

_X_EXPORT void
xf86DeleteInput(InputInfoPtr pInp, int flags)
{
    InputInfoPtr p;

    /* First check if the inputdev is valid. */
    if (pInp == NULL)
	return;

#if 0
    /* If a free function is defined, call it here. */
    if (pInp->free)
	pInp->free(pInp, 0);
#endif

    if (pInp->module)
	UnloadModule(pInp->module);

    if (pInp->drv)
	pInp->drv->refCount--;

    if (pInp->private)
	xfree(pInp->private);

    /* Remove the entry from the list. */
    if (pInp == xf86InputDevs)
	xf86InputDevs = pInp->next;
    else {
	p = xf86InputDevs;
	while (p && p->next != pInp)
	    p = p->next;
	if (p)
	    p->next = pInp->next;
	/* Else the entry wasn't in the xf86InputDevs list (ignore this). */
    }
    xfree(pInp);
}

_X_EXPORT Bool
xf86AddPixFormat(ScrnInfoPtr pScrn, int depth, int bpp, int pad)
{
    int i;

    if (pScrn->numFormats >= MAXFORMATS)
	return FALSE;

    if (bpp <= 0) {
	if (depth == 1)
	    bpp = 1;
	else if (depth <= 8)
	    bpp = 8;
	else if (depth <= 16)
	    bpp = 16;
	else if (depth <= 32)
	    bpp = 32;
	else
	    return FALSE;
    }
    if (pad <= 0)
	pad = BITMAP_SCANLINE_PAD;

    i = pScrn->numFormats++;
    pScrn->formats[i].depth = depth;
    pScrn->formats[i].bitsPerPixel = bpp;
    pScrn->formats[i].scanlinePad = pad;
    return TRUE;
}

/*
 * Set the depth we are using based on (in the following order of preference):
 *  - values given on the command line
 *  - values given in the config file
 *  - values provided by the driver
 *  - an overall default when nothing else is given
 *
 * Also find a Display subsection matching the depth/bpp found.
 *
 * Sets the following ScrnInfoRec fields:
 *     bitsPerPixel, pixmap24, depth, display, imageByteOrder,
 *     bitmapScanlinePad, bitmapScanlineUnit, bitmapBitOrder, numFormats,
 *     formats, fbFormat.
 */

/* Can the screen handle 24 bpp pixmaps */
#define DO_PIX24(f) ((f & Support24bppFb) || \
		     ((f & Support32bppFb) && (f & SupportConvert24to32)))

/* Can the screen handle 32 bpp pixmaps */
#define DO_PIX32(f) ((f & Support32bppFb) || \
		     ((f & Support24bppFb) && (f & SupportConvert32to24)))

/* Does the screen prefer 32bpp fb for 24bpp pixmaps */
#define CHOOSE32FOR24(f) ((f & Support32bppFb) && (f & SupportConvert24to32) \
			  && (f & PreferConvert24to32))

/* Does the screen prefer 24bpp fb for 32bpp pixmaps */
#define CHOOSE24FOR32(f) ((f & Support24bppFb) && (f & SupportConvert32to24) \
			  && (f & PreferConvert32to24))

/* Can the screen handle 32bpp pixmaps for 24bpp fb */
#define DO_PIX32FOR24(f) ((f & Support24bppFb) && (f & SupportConvert32to24))

/* Can the screen handle 24bpp pixmaps for 32bpp fb */
#define DO_PIX24FOR32(f) ((f & Support32bppFb) && (f & SupportConvert24to32))

#ifndef GLOBAL_DEFAULT_DEPTH
#define GLOBAL_DEFAULT_DEPTH 16
#endif

#ifndef GLOBAL_DEFAULT_FBBPP
#define GLOBAL_DEFAULT_FBBPP 16
#endif

_X_EXPORT Bool
xf86SetDepthBpp(ScrnInfoPtr scrp, int depth, int dummy, int fbbpp,
		int depth24flags)
{
    int i;
    DispPtr disp;
    Pix24Flags pix24 = xf86Info.pixmap24;
    Bool nomatch = FALSE;

    scrp->bitsPerPixel = -1;
    scrp->depth = -1;
    scrp->pixmap24 = Pix24DontCare;
    scrp->bitsPerPixelFrom = X_DEFAULT;
    scrp->depthFrom = X_DEFAULT;

#if BITMAP_SCANLINE_UNIT == 64
    /*
     * For platforms with 64-bit scanlines, modify the driver's depth24flags
     * to remove preferences for packed 24bpp modes, which are not currently
     * supported on these platforms.
     */
    depth24flags &= ~(SupportConvert32to24 | SupportConvert32to24 |
		      PreferConvert24to32 | PreferConvert32to24);
#endif
     
    if (xf86FbBpp > 0) {
	scrp->bitsPerPixel = xf86FbBpp;
	scrp->bitsPerPixelFrom = X_CMDLINE;
    }

    if (xf86Depth > 0) {
	scrp->depth = xf86Depth;
	scrp->depthFrom = X_CMDLINE;
    }

    if (xf86FbBpp < 0 && xf86Depth < 0) {
	if (scrp->confScreen->defaultfbbpp > 0) {
	    scrp->bitsPerPixel = scrp->confScreen->defaultfbbpp;
	    scrp->bitsPerPixelFrom = X_CONFIG;
	}
	if (scrp->confScreen->defaultdepth > 0) {
	    scrp->depth = scrp->confScreen->defaultdepth;
	    scrp->depthFrom = X_CONFIG;
	}

	if (scrp->confScreen->defaultfbbpp <= 0 &&
	    scrp->confScreen->defaultdepth <= 0) {
	    /*
	     * Check for DefaultDepth and DefaultFbBpp options in the
	     * Device sections.
	     */
	    int i;
	    GDevPtr device;
	    Bool found = FALSE;

	    for (i = 0; i < scrp->numEntities; i++) {
		device = xf86GetDevFromEntity(scrp->entityList[i],
					      scrp->entityInstanceList[i]);
		if (device && device->options) {
		    if (xf86FindOption(device->options, "DefaultDepth")) {
			scrp->depth = xf86SetIntOption(device->options,
						       "DefaultDepth", -1);
			scrp->depthFrom = X_CONFIG;
			found = TRUE;
		    }
		    if (xf86FindOption(device->options, "DefaultFbBpp")) {
			scrp->bitsPerPixel = xf86SetIntOption(device->options,
							      "DefaultFbBpp",
							      -1);
			scrp->bitsPerPixelFrom = X_CONFIG;
			found = TRUE;
		    }
		}
		if (found)
		    break;
	    }
	}
    }

    /* If none of these is set, pick a default */
    if (scrp->bitsPerPixel < 0 && scrp->depth < 0) {
        if (fbbpp > 0 || depth > 0) {
	    if (fbbpp > 0)
		scrp->bitsPerPixel = fbbpp;
	    if (depth > 0)
		scrp->depth = depth;
	} else {
	    scrp->bitsPerPixel = GLOBAL_DEFAULT_FBBPP;
	    scrp->depth = GLOBAL_DEFAULT_DEPTH;
	}
    }

    /* If any are not given, determine a default for the others */

    if (scrp->bitsPerPixel < 0) {
	/* The depth must be set */
	if (scrp->depth > -1) {
	    if (scrp->depth == 1)
		scrp->bitsPerPixel = 1;
	    else if (scrp->depth <= 4)
		scrp->bitsPerPixel = 4;
	    else if (scrp->depth <= 8)
		scrp->bitsPerPixel = 8;
	    else if (scrp->depth <= 16)
		scrp->bitsPerPixel = 16;
	    else if (scrp->depth <= 24) {
		/*
		 * Figure out if a choice is possible based on the depth24
		 * and pix24 flags.
		 */
		/* Check pix24 first */
		if (pix24 != Pix24DontCare) {
		    if (pix24 == Pix24Use32) {
			if (DO_PIX32(depth24flags)) {
			    if (CHOOSE24FOR32(depth24flags))
				scrp->bitsPerPixel = 24;
			    else
				scrp->bitsPerPixel = 32;
			} else {
			    nomatch = TRUE;
			}
		    } else if (pix24 == Pix24Use24) {
			if (DO_PIX24(depth24flags)) {
			    if (CHOOSE32FOR24(depth24flags))
				scrp->bitsPerPixel = 32;
			    else
				scrp->bitsPerPixel = 24;
			} else {
			    nomatch = TRUE;
			}
		    }
		} else {
		    if (DO_PIX32(depth24flags)) {
			if (CHOOSE24FOR32(depth24flags))
			    scrp->bitsPerPixel = 24;
			else
			    scrp->bitsPerPixel = 32;
		    } else if (DO_PIX24(depth24flags)) {
			if (CHOOSE32FOR24(depth24flags))
			    scrp->bitsPerPixel = 32;
			else
			    scrp->bitsPerPixel = 24;
		    }
		}
	    } else if (scrp->depth <= 32)
		scrp->bitsPerPixel = 32;
	    else {
		xf86DrvMsg(scrp->scrnIndex, X_ERROR,
			   "Specified depth (%d) is greater than 32\n",
			   scrp->depth);
		return FALSE;
	    }
	} else {
	    xf86DrvMsg(scrp->scrnIndex, X_ERROR,
			"xf86SetDepthBpp: internal error: depth and fbbpp"
			" are both not set\n");
	    return FALSE;
	}
	if (scrp->bitsPerPixel < 0) {
	    if (nomatch)
		xf86DrvMsg(scrp->scrnIndex, X_ERROR,
			"Driver can't support depth 24 pixmap format (%d)\n",
			PIX24TOBPP(pix24));
	    else if ((depth24flags & (Support24bppFb | Support32bppFb)) ==
		     NoDepth24Support)
		xf86DrvMsg(scrp->scrnIndex, X_ERROR,
			"Driver can't support depth 24\n");
	    else
		xf86DrvMsg(scrp->scrnIndex, X_ERROR,
			"Can't find fbbpp for depth 24\n");
	    return FALSE;
	}
	scrp->bitsPerPixelFrom = X_PROBED;
    }

    if (scrp->depth <= 0) {
	/* bitsPerPixel is already set */
	switch (scrp->bitsPerPixel) {
	case 32:
	    scrp->depth = 24;
	    break;
	default:
	    /* 1, 4, 8, 16 and 24 */
	    scrp->depth = scrp->bitsPerPixel;
	    break;
	}
	scrp->depthFrom = X_PROBED;
    }

    /* Sanity checks */
    if (scrp->depth < 1 || scrp->depth > 32) {
	xf86DrvMsg(scrp->scrnIndex, X_ERROR,
		   "Specified depth (%d) is not in the range 1-32\n",
		    scrp->depth);
	return FALSE;
    }
    switch (scrp->bitsPerPixel) {
    case 1:
    case 4:
    case 8:
    case 16:
    case 24:
    case 32:
	break;
    default:
	xf86DrvMsg(scrp->scrnIndex, X_ERROR,
		   "Specified fbbpp (%d) is not a permitted value\n",
		   scrp->bitsPerPixel);
	return FALSE;
    }
    if (scrp->depth > scrp->bitsPerPixel) {
	xf86DrvMsg(scrp->scrnIndex, X_ERROR,
		   "Specified depth (%d) is greater than the fbbpp (%d)\n",
		   scrp->depth, scrp->bitsPerPixel);
	return FALSE;
    }

    /* set scrp->pixmap24 if the driver isn't flexible */
    if (scrp->bitsPerPixel == 24 && !DO_PIX32FOR24(depth24flags)) {
	scrp->pixmap24 = Pix24Use24;
    }
    if (scrp->bitsPerPixel == 32 && !DO_PIX24FOR32(depth24flags)) {
	scrp->pixmap24 = Pix24Use32;
    }

    /*
     * Find the Display subsection matching the depth/fbbpp and initialise
     * scrp->display with it.
     */
    for (i = 0, disp = scrp->confScreen->displays;
	 i < scrp->confScreen->numdisplays; i++, disp++) {
	if ((disp->depth == scrp->depth && disp->fbbpp == scrp->bitsPerPixel)
	    || (disp->depth == scrp->depth && disp->fbbpp <= 0)
	    || (disp->fbbpp == scrp->bitsPerPixel && disp->depth <= 0)) {
	    scrp->display = disp;
	    break;
	}
    }

    /*
     * If an exact match can't be found, see if there is one with no
     * depth or fbbpp specified.
     */
    if (i == scrp->confScreen->numdisplays) {
	for (i = 0, disp = scrp->confScreen->displays;
	     i < scrp->confScreen->numdisplays; i++, disp++) {
	    if (disp->depth <= 0 && disp->fbbpp <= 0) {
		scrp->display = disp;
		break;
	    }
	}
    }

    /*
     * If all else fails, create a default one.
     */
    if (i == scrp->confScreen->numdisplays) {
	scrp->confScreen->numdisplays++;
	scrp->confScreen->displays =
		xnfrealloc(scrp->confScreen->displays,
			   scrp->confScreen->numdisplays * sizeof(DispRec));
	xf86DrvMsg(scrp->scrnIndex, X_INFO,
		   "Creating default Display subsection in Screen section\n"
		   "\t\"%s\" for depth/fbbpp %d/%d\n",
		   scrp->confScreen->id, scrp->depth, scrp->bitsPerPixel);
	memset(&scrp->confScreen->displays[i], 0, sizeof(DispRec));
	scrp->confScreen->displays[i].blackColour.red = -1;
	scrp->confScreen->displays[i].blackColour.green = -1;
	scrp->confScreen->displays[i].blackColour.blue = -1;
	scrp->confScreen->displays[i].whiteColour.red = -1;
	scrp->confScreen->displays[i].whiteColour.green = -1;
	scrp->confScreen->displays[i].whiteColour.blue = -1;
	scrp->confScreen->displays[i].defaultVisual = -1;
	scrp->confScreen->displays[i].modes = xnfalloc(sizeof(char *));
	scrp->confScreen->displays[i].modes[0] = NULL;
	scrp->confScreen->displays[i].depth = depth;
	scrp->confScreen->displays[i].fbbpp = fbbpp;
	scrp->display = &scrp->confScreen->displays[i];
    }

    /*
     * Setup defaults for the display-wide attributes the framebuffer will
     * need.  These defaults should eventually be set globally, and not
     * dependent on the screens.
     */
    scrp->imageByteOrder = IMAGE_BYTE_ORDER;
    scrp->bitmapScanlinePad = BITMAP_SCANLINE_PAD;
    if (scrp->depth < 8) {
	/* Planar modes need these settings */
	scrp->bitmapScanlineUnit = 8;
	scrp->bitmapBitOrder = MSBFirst;
    } else {
	scrp->bitmapScanlineUnit = BITMAP_SCANLINE_UNIT;
	scrp->bitmapBitOrder = BITMAP_BIT_ORDER;
    }

    /*
     * If an unusual depth is required, add it to scrp->formats.  The formats
     * for the common depths are handled globally in InitOutput
     */
    switch (scrp->depth) {
    case 1:
    case 4:
    case 8:
    case 15:
    case 16:
    case 24:
	/* Common depths.  Nothing to do for them */
	break;
    default:
	if (!xf86AddPixFormat(scrp, scrp->depth, 0, 0)) {
	    xf86DrvMsg(scrp->scrnIndex, X_ERROR,
		       "Can't add pixmap format for depth %d\n", scrp->depth);
	    return FALSE;
	}
    }

    /* Initialise the framebuffer format for this screen */
    scrp->fbFormat.depth = scrp->depth;
    scrp->fbFormat.bitsPerPixel = scrp->bitsPerPixel;
    scrp->fbFormat.scanlinePad = BITMAP_SCANLINE_PAD;

    return TRUE;
}

/*
 * Print out the selected depth and bpp.
 */
_X_EXPORT void
xf86PrintDepthBpp(ScrnInfoPtr scrp)
{
    xf86DrvMsg(scrp->scrnIndex, scrp->depthFrom, "Depth %d, ", scrp->depth);
    xf86Msg(scrp->bitsPerPixelFrom, "framebuffer bpp %d\n", scrp->bitsPerPixel);
}

/*
 * xf86SetWeight sets scrp->weight, scrp->mask, scrp->offset, and for depths
 * greater than MAX_PSEUDO_DEPTH also scrp->rgbBits.
 */
_X_EXPORT Bool
xf86SetWeight(ScrnInfoPtr scrp, rgb weight, rgb mask)
{
    MessageType weightFrom = X_DEFAULT;

    scrp->weight.red = 0;
    scrp->weight.green = 0;
    scrp->weight.blue = 0;

    if (xf86Weight.red > 0 && xf86Weight.green > 0 && xf86Weight.blue > 0) {
	scrp->weight = xf86Weight;
	weightFrom = X_CMDLINE;
    } else if (scrp->display->weight.red > 0 && scrp->display->weight.green > 0
	       && scrp->display->weight.blue > 0) {
	scrp->weight = scrp->display->weight;
	weightFrom = X_CONFIG;
    } else if (weight.red > 0 && weight.green > 0 && weight.blue > 0) {
	scrp->weight = weight;
    } else {
	switch (scrp->depth) {
	case 1:
	case 4:
	case 8:
	    scrp->weight.red = scrp->weight.green =
		scrp->weight.blue = scrp->rgbBits;
	    break;
	case 15:
	    scrp->weight.red = scrp->weight.green = scrp->weight.blue = 5;
	    break;
	case 16:
	    scrp->weight.red = scrp->weight.blue = 5;
	    scrp->weight.green = 6;
	    break;
	case 24:
	    scrp->weight.red = scrp->weight.green = scrp->weight.blue = 8;
	    break;
	case 30:
	    scrp->weight.red = scrp->weight.green = scrp->weight.blue = 10;
	    break;
	}
    }

    if (scrp->weight.red)
	xf86DrvMsg(scrp->scrnIndex, weightFrom, "RGB weight %d%d%d\n",
		   (int)scrp->weight.red, (int)scrp->weight.green,
		   (int)scrp->weight.blue);

    if (scrp->depth > MAX_PSEUDO_DEPTH &&
	(scrp->depth != scrp->weight.red + scrp->weight.green +
			scrp->weight.blue)) {
	xf86DrvMsg(scrp->scrnIndex, X_ERROR,
		   "Weight given (%d%d%d) is inconsistent with the "
		   "depth (%d)\n",
		   (int)scrp->weight.red, (int)scrp->weight.green,
		   (int)scrp->weight.blue, scrp->depth);
	return FALSE;
    }
    if (scrp->depth > MAX_PSEUDO_DEPTH && scrp->weight.red) {
	/*
	 * XXX Does this even mean anything for TrueColor visuals?
	 * If not, we shouldn't even be setting it here.  However, this
	 * matches the behaviour of 3.x versions of XFree86.
	 */
	scrp->rgbBits = scrp->weight.red;
	if (scrp->weight.green > scrp->rgbBits)
	    scrp->rgbBits = scrp->weight.green;
	if (scrp->weight.blue > scrp->rgbBits)
	    scrp->rgbBits = scrp->weight.blue;
    }

    /* Set the mask and offsets */
    if (mask.red == 0 || mask.green == 0 || mask.blue == 0) {
	/* Default to a setting common to PC hardware */
	scrp->offset.red = scrp->weight.green + scrp->weight.blue;
	scrp->offset.green = scrp->weight.blue;
	scrp->offset.blue = 0;
	scrp->mask.red = ((1 << scrp->weight.red) - 1) << scrp->offset.red;
	scrp->mask.green = ((1 << scrp->weight.green) - 1)
				<< scrp->offset.green;
	scrp->mask.blue = (1 << scrp->weight.blue) - 1;
    } else {
	/* Initialise to the values passed */
	scrp->mask.red = mask.red;
	scrp->mask.green = mask.green;
	scrp->mask.blue = mask.blue;
	scrp->offset.red = ffs(mask.red);
	scrp->offset.green = ffs(mask.green);
	scrp->offset.blue = ffs(mask.blue);
    }
    return TRUE;
}

_X_EXPORT Bool
xf86SetDefaultVisual(ScrnInfoPtr scrp, int visual)
{
    MessageType visualFrom = X_DEFAULT;

    if (defaultColorVisualClass >= 0) {
	scrp->defaultVisual = defaultColorVisualClass;
	visualFrom = X_CMDLINE;
    } else if (scrp->display->defaultVisual >= 0) {
	scrp->defaultVisual = scrp->display->defaultVisual;
	visualFrom = X_CONFIG;
    } else if (visual >= 0) {
	scrp->defaultVisual = visual;
    } else {
	if (scrp->depth == 1)
	    scrp->defaultVisual = StaticGray;
	else if (scrp->depth == 4)
	    scrp->defaultVisual = StaticColor;
	else if (scrp->depth <= MAX_PSEUDO_DEPTH)
	    scrp->defaultVisual = PseudoColor;
	else
	    scrp->defaultVisual = TrueColor;
    }
    switch (scrp->defaultVisual) {
    case StaticGray:
    case GrayScale:
    case StaticColor:
    case PseudoColor:
    case TrueColor:
    case DirectColor:
	xf86DrvMsg(scrp->scrnIndex, visualFrom, "Default visual is %s\n",
		   xf86VisualNames[scrp->defaultVisual]);
	    return TRUE;
    default:

	xf86DrvMsg(scrp->scrnIndex, X_ERROR,
		   "Invalid default visual class (%d)\n", scrp->defaultVisual);
	return FALSE;
    }
}

#define TEST_GAMMA(g) \
	(g).red > GAMMA_ZERO || (g).green > GAMMA_ZERO || (g).blue > GAMMA_ZERO

#define SET_GAMMA(g) \
	(g) > GAMMA_ZERO ? (g) : 1.0

_X_EXPORT Bool
xf86SetGamma(ScrnInfoPtr scrp, Gamma gamma)
{
    MessageType from = X_DEFAULT;
#if 0
    xf86MonPtr DDC = (xf86MonPtr)(scrp->monitor->DDC); 
#endif
    if (TEST_GAMMA(xf86Gamma)) {
	from = X_CMDLINE;
	scrp->gamma.red = SET_GAMMA(xf86Gamma.red);
	scrp->gamma.green = SET_GAMMA(xf86Gamma.green);
	scrp->gamma.blue = SET_GAMMA(xf86Gamma.blue);
    } else if (TEST_GAMMA(scrp->monitor->gamma)) {
	from = X_CONFIG;
	scrp->gamma.red = SET_GAMMA(scrp->monitor->gamma.red);
	scrp->gamma.green = SET_GAMMA(scrp->monitor->gamma.green);
	scrp->gamma.blue = SET_GAMMA(scrp->monitor->gamma.blue);
#if 0
    } else if ( DDC && DDC->features.gamma > GAMMA_ZERO ) {
        from = X_PROBED;
	scrp->gamma.red = SET_GAMMA(DDC->features.gamma);
	scrp->gamma.green = SET_GAMMA(DDC->features.gamma);
	scrp->gamma.blue = SET_GAMMA(DDC->features.gamma);
	/* EDID structure version 2 gives optional seperate red, green & blue gamma values
	 * in bytes 0x57-0x59 */
#endif
    } else if (TEST_GAMMA(gamma)) {
	scrp->gamma.red = SET_GAMMA(gamma.red);
	scrp->gamma.green = SET_GAMMA(gamma.green);
	scrp->gamma.blue = SET_GAMMA(gamma.blue);
    } else {
	scrp->gamma.red = 1.0;
	scrp->gamma.green = 1.0;
	scrp->gamma.blue = 1.0;
    }
    xf86DrvMsg(scrp->scrnIndex, from,
	       "Using gamma correction (%.1f, %.1f, %.1f)\n",
	       scrp->gamma.red, scrp->gamma.green, scrp->gamma.blue);

    return TRUE;
}

#undef TEST_GAMMA
#undef SET_GAMMA


/*
 * Set the DPI from the command line option.  XXX should allow it to be
 * calculated from the widthmm/heightmm values.
 */

#undef MMPERINCH
#define MMPERINCH 25.4

_X_EXPORT void
xf86SetDpi(ScrnInfoPtr pScrn, int x, int y)
{
    MessageType from = X_DEFAULT;
    xf86MonPtr DDC = (xf86MonPtr)(pScrn->monitor->DDC); 
    int ddcWidthmm, ddcHeightmm;
    int widthErr, heightErr;

    /* XXX Maybe there is no need for widthmm/heightmm in ScrnInfoRec */
    pScrn->widthmm = pScrn->monitor->widthmm;
    pScrn->heightmm = pScrn->monitor->heightmm;

    if (DDC && (DDC->features.hsize > 0 && DDC->features.vsize > 0) ) {
      /* DDC gives display size in mm for individual modes,
       * but cm for monitor 
       */
      ddcWidthmm = DDC->features.hsize * 10; /* 10mm in 1cm */
      ddcHeightmm = DDC->features.vsize * 10; /* 10mm in 1cm */
    } else {
      ddcWidthmm = ddcHeightmm = 0;
    }

    if (monitorResolution > 0) {
	pScrn->xDpi = monitorResolution;
	pScrn->yDpi = monitorResolution;
	from = X_CMDLINE;
    } else if (pScrn->widthmm > 0 || pScrn->heightmm > 0) {
	from = X_CONFIG;
	if (pScrn->widthmm > 0) {
	   pScrn->xDpi =
		(int)((double)pScrn->virtualX * MMPERINCH / pScrn->widthmm);
	}
	if (pScrn->heightmm > 0) {
	   pScrn->yDpi =
		(int)((double)pScrn->virtualY * MMPERINCH / pScrn->heightmm);
	}
	if (pScrn->xDpi > 0 && pScrn->yDpi <= 0)
	    pScrn->yDpi = pScrn->xDpi;
	if (pScrn->yDpi > 0 && pScrn->xDpi <= 0)
	    pScrn->xDpi = pScrn->yDpi;
	xf86DrvMsg(pScrn->scrnIndex, from, "Display dimensions: (%d, %d) mm\n",
		   pScrn->widthmm, pScrn->heightmm);

	/* Warn if config and probe disagree about display size */
	if ( ddcWidthmm && ddcHeightmm ) {
	  if (pScrn->widthmm > 0) {
	    widthErr  = abs(ddcWidthmm  - pScrn->widthmm);
	  } else {
	    widthErr  = 0;
	  }
	  if (pScrn->heightmm > 0) {
	    heightErr = abs(ddcHeightmm - pScrn->heightmm);
	  } else {
	    heightErr = 0;
	  }
	  if (widthErr>10 || heightErr>10) {
	    /* Should include config file name for monitor here */
	    xf86DrvMsg(pScrn->scrnIndex, X_WARNING,
		       "Probed monitor is %dx%d mm, using Displaysize %dx%d mm\n", 
		       ddcWidthmm,ddcHeightmm, pScrn->widthmm,pScrn->heightmm);
	  }
	}
    } else if ( ddcWidthmm && ddcHeightmm ) {
	from = X_PROBED;
	xf86DrvMsg(pScrn->scrnIndex, from, "Display dimensions: (%d, %d) mm\n",
		   ddcWidthmm, ddcHeightmm );
	pScrn->widthmm = ddcWidthmm;
	pScrn->heightmm = ddcHeightmm;
	if (pScrn->widthmm > 0) {
	   pScrn->xDpi =
		(int)((double)pScrn->virtualX * MMPERINCH / pScrn->widthmm);
	}
	if (pScrn->heightmm > 0) {
	   pScrn->yDpi =
		(int)((double)pScrn->virtualY * MMPERINCH / pScrn->heightmm);
	}
	if (pScrn->xDpi > 0 && pScrn->yDpi <= 0)
	    pScrn->yDpi = pScrn->xDpi;
	if (pScrn->yDpi > 0 && pScrn->xDpi <= 0)
	    pScrn->xDpi = pScrn->yDpi;
    } else {
	if (x > 0)
	    pScrn->xDpi = x;
	else
	    pScrn->xDpi = DEFAULT_DPI;
	if (y > 0)
	    pScrn->yDpi = y;
	else
	    pScrn->yDpi = DEFAULT_DPI;
    }
    xf86DrvMsg(pScrn->scrnIndex, from, "DPI set to (%d, %d)\n",
	       pScrn->xDpi, pScrn->yDpi);
}

#undef MMPERINCH


_X_EXPORT void
xf86SetBlackWhitePixels(ScreenPtr pScreen)
{
    if (xf86FlipPixels) {
	pScreen->whitePixel = 0;
	pScreen->blackPixel = 1;
    } else {
	pScreen->whitePixel = 1;
	pScreen->blackPixel = 0;
    }
}

/*
 * xf86SetRootClip --
 *	Enable or disable rendering to the screen by
 *	setting the root clip list and revalidating
 *	all of the windows
 */

static void
xf86SetRootClip (ScreenPtr pScreen, Bool enable)
{
    WindowPtr	pWin = WindowTable[pScreen->myNum];
    WindowPtr	pChild;
    Bool	WasViewable = (Bool)(pWin->viewable);
    Bool	anyMarked = FALSE;
    RegionPtr	pOldClip = NULL, bsExposed;
#ifdef DO_SAVE_UNDERS
    Bool	dosave = FALSE;
#endif
    WindowPtr   pLayerWin;
    BoxRec	box;

    if (WasViewable)
    {
	for (pChild = pWin->firstChild; pChild; pChild = pChild->nextSib)
	{
	    (void) (*pScreen->MarkOverlappedWindows)(pChild,
						     pChild,
						     &pLayerWin);
	}
	(*pScreen->MarkWindow) (pWin);
	anyMarked = TRUE;
	if (pWin->valdata)
	{
	    if (HasBorder (pWin))
	    {
		RegionPtr	borderVisible;

		borderVisible = REGION_CREATE(pScreen, NullBox, 1);
		REGION_SUBTRACT(pScreen, borderVisible,
				&pWin->borderClip, &pWin->winSize);
		pWin->valdata->before.borderVisible = borderVisible;
	    }
	    pWin->valdata->before.resized = TRUE;
	}
    }
    
    /*
     * Use REGION_BREAK to avoid optimizations in ValidateTree
     * that assume the root borderClip can't change well, normally
     * it doesn't...)
     */
    if (enable)
    {
	box.x1 = 0;
	box.y1 = 0;
	box.x2 = pScreen->width;
	box.y2 = pScreen->height;
	REGION_INIT (pScreen, &pWin->winSize, &box, 1);
	REGION_INIT (pScreen, &pWin->borderSize, &box, 1);
	if (WasViewable)
	    REGION_RESET(pScreen, &pWin->borderClip, &box);
	pWin->drawable.width = pScreen->width;
	pWin->drawable.height = pScreen->height;
        REGION_BREAK (pWin->drawable.pScreen, &pWin->clipList);
    }
    else
    {
	REGION_EMPTY(pScreen, &pWin->borderClip);
	REGION_BREAK (pWin->drawable.pScreen, &pWin->clipList);
    }
    
    ResizeChildrenWinSize (pWin, 0, 0, 0, 0);
    
    if (WasViewable)
    {
	if (pWin->backStorage)
	{
	    pOldClip = REGION_CREATE(pScreen, NullBox, 1);
	    REGION_COPY(pScreen, pOldClip, &pWin->clipList);
	}

	if (pWin->firstChild)
	{
	    anyMarked |= (*pScreen->MarkOverlappedWindows)(pWin->firstChild,
							   pWin->firstChild,
							   (WindowPtr *)NULL);
	}
	else
	{
	    (*pScreen->MarkWindow) (pWin);
	    anyMarked = TRUE;
	}

#ifdef DO_SAVE_UNDERS
	if (DO_SAVE_UNDERS(pWin))
	{
	    dosave = (*pScreen->ChangeSaveUnder)(pLayerWin, pLayerWin);
	}
#endif /* DO_SAVE_UNDERS */

	if (anyMarked)
	    (*pScreen->ValidateTree)(pWin, NullWindow, VTOther);
    }

    if (pWin->backStorage &&
	((pWin->backingStore == Always) || WasViewable))
    {
	if (!WasViewable)
	    pOldClip = &pWin->clipList; /* a convenient empty region */
	bsExposed = (*pScreen->TranslateBackingStore)
			     (pWin, 0, 0, pOldClip,
			      pWin->drawable.x, pWin->drawable.y);
	if (WasViewable)
	    REGION_DESTROY(pScreen, pOldClip);
	if (bsExposed)
	{
	    RegionPtr	valExposed = NullRegion;
    
	    if (pWin->valdata)
		valExposed = &pWin->valdata->after.exposed;
	    (*pScreen->WindowExposures) (pWin, valExposed, bsExposed);
	    if (valExposed)
		REGION_EMPTY(pScreen, valExposed);
	    REGION_DESTROY(pScreen, bsExposed);
	}
    }
    if (WasViewable)
    {
	if (anyMarked)
	    (*pScreen->HandleExposures)(pWin);
#ifdef DO_SAVE_UNDERS
	if (dosave)
	    (*pScreen->PostChangeSaveUnder)(pLayerWin, pLayerWin);
#endif /* DO_SAVE_UNDERS */
	if (anyMarked && pScreen->PostValidateTree)
	    (*pScreen->PostValidateTree)(pWin, NullWindow, VTOther);
    }
    if (pWin->realized)
	WindowsRestructured ();
    FlushAllOutput ();
}

/*
 * Function to enable/disable access to the frame buffer
 *
 * This is used when VT switching and when entering/leaving DGA direct mode.
 *
 * This has been rewritten again to eliminate the saved pixmap.  The
 * devPrivate field in the screen pixmap is set to NULL to catch code
 * accidentally referencing the frame buffer while the X server is not
 * supposed to touch it.
 *
 * Here, we exchange the pixmap private data, rather than the pixmaps
 * themselves to avoid having to find and change any references to the screen
 * pixmap such as GC's, window privates etc.  This also means that this code
 * does not need to know exactly how the pixmap pixels are accessed.  Further,
 * this exchange is >not< done through the screen's ModifyPixmapHeader()
 * vector.  This means the called frame buffer code layers can determine
 * whether they are switched in or out by keeping track of the root pixmap's
 * private data, and therefore don't need to access pScrnInfo->vtSema.
 */
_X_EXPORT void
xf86EnableDisableFBAccess(int scrnIndex, Bool enable)
{
    ScrnInfoPtr pScrnInfo = xf86Screens[scrnIndex];
    ScreenPtr pScreen = pScrnInfo->pScreen;
    PixmapPtr pspix;

    pspix = (*pScreen->GetScreenPixmap) (pScreen);
    if (enable)
    {
	/*
	 * Restore the screen pixmap devPrivate field
	 */
	pspix->devPrivate = pScrnInfo->pixmapPrivate;
	/*
	 * Restore all of the clip lists on the screen 
	 */
	if (!xf86Resetting)
	    xf86SetRootClip (pScreen, TRUE);

    }
    else
    {
	/*
	 * Empty all of the clip lists on the screen 
	 */
	xf86SetRootClip (pScreen, FALSE);
	/*
	 * save the screen pixmap devPrivate field and
	 * replace it with NULL so accidental references
	 * to the frame buffer are caught
	 */
	pScrnInfo->pixmapPrivate = pspix->devPrivate;
	pspix->devPrivate.ptr = NULL;
    }
}

/* Print driver messages in the standard format */

#undef PREFIX_SIZE
#define PREFIX_SIZE 14

_X_EXPORT void
xf86VDrvMsgVerb(int scrnIndex, MessageType type, int verb, const char *format,
		va_list args)
{
    char *tmpFormat;

    /* Prefix the scrnIndex name to the format string. */
    if (scrnIndex >= 0 && scrnIndex < xf86NumScreens &&
	xf86Screens[scrnIndex]->name) {
	tmpFormat = xalloc(strlen(format) +
			   strlen(xf86Screens[scrnIndex]->name) +
			   PREFIX_SIZE + 1);
	if (!tmpFormat)
	    return;

	snprintf(tmpFormat, PREFIX_SIZE + 1, "%s(%d): ",
		 xf86Screens[scrnIndex]->name, scrnIndex);

	strcat(tmpFormat, format);
	LogVMessageVerb(type, verb, tmpFormat, args);
	xfree(tmpFormat);
    } else
	LogVMessageVerb(type, verb, format, args);
}
#undef PREFIX_SIZE

/* Print driver messages, with verbose level specified directly */
_X_EXPORT void
xf86DrvMsgVerb(int scrnIndex, MessageType type, int verb, const char *format,
	       ...)
{
    va_list ap;

    va_start(ap, format);
    xf86VDrvMsgVerb(scrnIndex, type, verb, format, ap);
    va_end(ap);
}

/* Print driver messages, with verbose level of 1 (default) */
_X_EXPORT void
xf86DrvMsg(int scrnIndex, MessageType type, const char *format, ...)
{
    va_list ap;

    va_start(ap, format);
    xf86VDrvMsgVerb(scrnIndex, type, 1, format, ap);
    va_end(ap);
}

/* Print non-driver messages with verbose level specified directly */
_X_EXPORT void
xf86MsgVerb(MessageType type, int verb, const char *format, ...)
{
    va_list ap;

    va_start(ap, format);
    xf86VDrvMsgVerb(-1, type, verb, format, ap);
    va_end(ap);
}

/* Print non-driver messages with verbose level of 1 (default) */
_X_EXPORT void
xf86Msg(MessageType type, const char *format, ...)
{
    va_list ap;

    va_start(ap, format);
    xf86VDrvMsgVerb(-1, type, 1, format, ap);
    va_end(ap);
}

/* Just like ErrorF, but with the verbose level checked */
_X_EXPORT void
xf86ErrorFVerb(int verb, const char *format, ...)
{
    va_list ap;

    va_start(ap, format);
    if (xf86Verbose >= verb || xf86LogVerbose >= verb)
	LogVWrite(verb, format, ap);
    va_end(ap);
}

/* Like xf86ErrorFVerb, but with an implied verbose level of 1 */
_X_EXPORT void
xf86ErrorF(const char *format, ...)
{
    va_list ap;

    va_start(ap, format);
    if (xf86Verbose >= 1 || xf86LogVerbose >= 1)
	LogVWrite(1, format, ap);
    va_end(ap);
}


void
xf86LogInit()
{
    char *lf;

#define LOGSUFFIX ".log"
#define LOGOLDSUFFIX ".old"
    
    /* Get the log file name */
    if (xf86LogFileFrom == X_DEFAULT) {
	/* Append the display number and ".log" */
	lf = malloc(strlen(xf86LogFile) + strlen("%s") +
		    strlen(LOGSUFFIX) + 1);
	if (!lf)
	    FatalError("Cannot allocate space for the log file name\n");
	sprintf(lf, "%s%%s" LOGSUFFIX, xf86LogFile);
	xf86LogFile = lf;
    }

    xf86LogFile = LogInit(xf86LogFile, LOGOLDSUFFIX);
    xf86LogFileWasOpened = TRUE;

    xf86SetVerbosity(xf86Verbose);
    xf86SetLogVerbosity(xf86LogVerbose);

#undef LOGSUFFIX
#undef LOGOLDSUFFIX
}

void
xf86CloseLog()
{
    LogClose();
}


/*
 * Drivers can use these for using their own SymTabRecs.
 */

_X_EXPORT const char *
xf86TokenToString(SymTabPtr table, int token)
{
    int i;

    for (i = 0; table[i].token >= 0 && table[i].token != token; i++)
	;

    if (table[i].token < 0)
	return NULL;
    else
	return(table[i].name);
}

_X_EXPORT int
xf86StringToToken(SymTabPtr table, const char *string)
{
    int i;

    if (string == NULL)
	return -1;

    for (i = 0; table[i].token >= 0 && xf86NameCmp(string, table[i].name); i++)
	;

    return(table[i].token);
}

/*
 * helper to display the clocks found on a card
 */
_X_EXPORT void
xf86ShowClocks(ScrnInfoPtr scrp, MessageType from)
{
    int j;

    xf86DrvMsg(scrp->scrnIndex, from, "Pixel clocks available:");
    for (j=0; j < scrp->numClocks; j++) {
	if ((j % 4) == 0) {
	    xf86ErrorF("\n");
	    xf86DrvMsg(scrp->scrnIndex, from, "pixel clocks:");
	}
	xf86ErrorF(" %7.3f", (double)scrp->clock[j] / 1000.0);
    }
    xf86ErrorF("\n");
}


/*
 * This prints out the driver identify message, including the names of
 * the supported chipsets.
 *
 * XXX This makes assumptions about the line width, etc.  Maybe we could
 * use a more general "pretty print" function for messages.
 */
_X_EXPORT void
xf86PrintChipsets(const char *drvname, const char *drvmsg, SymTabPtr chips)
{
    int len, i;

    len = 6 + strlen(drvname) + 2 + strlen(drvmsg) + 2;
    xf86Msg(X_INFO, "%s: %s:", drvname, drvmsg);
    for (i = 0; chips[i].name != NULL; i++) {
	if (i != 0) {
	    xf86ErrorF(",");
	    len++;
	}
	if (len + 2 + strlen(chips[i].name) < 78) {
	    xf86ErrorF(" ");
	    len++;
	} else {
	    xf86ErrorF("\n\t");
	    len = 8;
	}
	xf86ErrorF("%s", chips[i].name);
	len += strlen(chips[i].name);
    }
    xf86ErrorF("\n");
}


#define MAXDRIVERS 64	/* A >hack<, to be sure ... */


_X_EXPORT int
xf86MatchDevice(const char *drivername, GDevPtr **sectlist)
{
    GDevPtr       gdp, *pgdp = NULL;
    confScreenPtr screensecptr;
    int i,j;

    if (sectlist)
	*sectlist = NULL;

    if (xf86DoProbe) return 1;
  
    if (xf86DoConfigure && xf86DoConfigurePass1) return 1;

    /*
     * This is a very important function that matches the device sections
     * as they show up in the config file with the drivers that the server
     * loads at run time.
     *
     * ChipProbe can call 
     * int xf86MatchDevice(char * drivername, GDevPtr ** sectlist) 
     * with its driver name. The function allocates an array of GDevPtr and
     * returns this via sectlist and returns the number of elements in
     * this list as return value. 0 means none found, -1 means fatal error.
     * 
     * It can figure out which of the Device sections to use for which card
     * (using things like the Card statement, etc). For single headed servers
     * there will of course be just one such Device section.
     */
    i = 0;
    
    /*
     * first we need to loop over all the Screens sections to get to all
     * 'active' device sections
     */
    for (j=0; xf86ConfigLayout.screens[j].screen != NULL; j++) {
        screensecptr = xf86ConfigLayout.screens[j].screen;
        if ((screensecptr->device->driver != NULL)
            && (xf86NameCmp( screensecptr->device->driver,drivername) == 0)
            && (! screensecptr->device->claimed)) {
            /*
             * we have a matching driver that wasn't claimed, yet
             */
            pgdp = xnfrealloc(pgdp, (i + 2) * sizeof(GDevPtr));
            pgdp[i++] = screensecptr->device;
        }
    }

    /* Then handle the inactive devices */
    j = 0;
    while (xf86ConfigLayout.inactives[j].identifier) {
	gdp = &xf86ConfigLayout.inactives[j];
	if (gdp->driver && !gdp->claimed &&
	    !xf86NameCmp(gdp->driver,drivername)) {
	    /* we have a matching driver that wasn't claimed yet */
	    pgdp = xnfrealloc(pgdp, (i + 2) * sizeof(GDevPtr));
	    pgdp[i++] = gdp;
	}
	j++;
    }
    
    /*
     * make the array NULL terminated and return its address
     */
    if (i)
        pgdp[i] = NULL;

    if (sectlist)
	*sectlist = pgdp;
    else
	xfree(pgdp);
    return i;
}

struct Inst {
    pciVideoPtr	pci;
    GDevPtr		dev;
    Bool		foundHW;  /* PCIid in list of supported chipsets */
    Bool		claimed;  /* BusID matches with a device section */
    int 		chip;
    int 		screen;
};


/**
 * Find set of unclaimed devices matching a given vendor ID.
 * 
 * Used by drivers to find as yet unclaimed devices matching the specified
 * vendor ID.
 *
 * \param driverName     Name of the driver.  This is used to find Device
 *                       sections in the config file.
 * \param vendorID       PCI vendor ID of associated devices.  If zero, then
 *                       the true vendor ID must be encoded in the \c PCIid
 *                       fields of the \c PCIchipsets entries.
 * \param chipsets       Symbol table used to associate chipset names with
 *                       PCI IDs.
 * \param devList        List of Device sections parsed from the config file.
 * \param numDevs        Number of entries in \c devList.
 * \param drvp           Pointer the driver's control structure.
 * \param foundEntities  Returned list of entity indicies associated with the
 *                       driver.
 * 
 * \returns
 * The number of elements in returned in \c foundEntities on success or zero
 * on failure.
 *
 * \todo
 * This function does a bit more than short description says.  Fill in some
 * more of the details of its operation.
 *
 * \todo
 * The \c driverName parameter is redundant.  It is the same as
 * \c DriverRec::driverName.  In a future version of this function, remove
 * that parameter.
 */
_X_EXPORT int
xf86MatchPciInstances(const char *driverName, int vendorID, 
		      SymTabPtr chipsets, PciChipsets *PCIchipsets,
		      GDevPtr *devList, int numDevs, DriverPtr drvp,
		      int **foundEntities)
{
    int i,j;
    pciVideoPtr pPci, *ppPci;
    struct Inst *instances = NULL;
    int numClaimedInstances = 0;
    int allocatedInstances = 0;
    int numFound = 0;
    SymTabRec *c;
    PciChipsets *id;
    int *retEntities = NULL;

    *foundEntities = NULL;


    /* Each PCI device will contribute at least one entry.  Each device
     * section can contribute at most one entry.  The sum of the two is
     * guaranteed to be larger than the maximum possible number of entries.
     * Do this calculation and memory allocation once now to eliminate the
     * need for realloc calls inside the loop.
     */
    if ( !xf86DoProbe && !(xf86DoConfigure && xf86DoConfigurePass1) ) {
	unsigned max_entries = numDevs;
	for (ppPci = xf86PciVideoInfo ; *ppPci != NULL ; ppPci++) {
	    max_entries++;
	}

	instances = xnfalloc( max_entries * sizeof(struct Inst) );
    }

    for (ppPci = xf86PciVideoInfo; *ppPci != NULL; ppPci++) {
	unsigned device_class = ((*ppPci)->class << 16)
	    | ((*ppPci)->subclass << 8) | ((*ppPci)->interface);
	Bool foundVendor = FALSE;


	pPci = *ppPci;

	/* Convert the pre-PCI 2.0 device class for a VGA adapter to the
	 * 2.0 version of the same class.
	 */
	if ( device_class == 0x00000101 ) {
	    device_class = 0x00030000;
	}


	/* Find PCI devices that match the given vendor ID.  The vendor ID is
	 * either specified explicitly as a parameter to the function or
	 * implicitly encoded in the high bits of id->PCIid.
	 *
	 * The first device with a matching vendor is recorded, even if the
	 * device ID doesn't match.  This is done because the Device section
	 * in the xorg.conf file can over-ride the device ID.  A matching PCI
	 * ID might not be found now, but after the device ID over-ride is
	 * applied there /might/ be a match.
	 */
	for (id = PCIchipsets; id->PCIid != -1; id++) {
	    const unsigned vendor_id = ((id->PCIid & 0xFFFF0000) >> 16)
		| vendorID;
	    const unsigned device_id = (id->PCIid & 0x0000FFFF);
	    const unsigned match_class = 0x00030000 | id->PCIid;

	    if ( (vendor_id == pPci->vendor)
		 || ((vendorID == PCI_VENDOR_GENERIC) && (match_class == device_class)) ) {
		if ( !foundVendor && (instances != NULL) ) {
		    ++allocatedInstances;
		    instances[allocatedInstances - 1].pci = *ppPci;
		    instances[allocatedInstances - 1].dev = NULL;
		    instances[allocatedInstances - 1].claimed = FALSE;
		    instances[allocatedInstances - 1].foundHW = FALSE;
		    instances[allocatedInstances - 1].screen = 0;
		    foundVendor = TRUE;
		}
		if ( (device_id == pPci->chipType)
		     || ((vendorID == PCI_VENDOR_GENERIC) 
			 && (match_class == device_class)) ) {
		    if ( instances != NULL ) {
			instances[allocatedInstances - 1].foundHW = TRUE;
			instances[allocatedInstances - 1].chip = id->numChipset;
		    }


		    if ( xf86DoConfigure && xf86DoConfigurePass1 ) {
			if ( xf86CheckPciSlot(pPci->bus, pPci->device,
					      pPci->func) ) {
			    GDevPtr pGDev = 
			      xf86AddDeviceToConfigure( drvp->driverName,
							pPci, -1 );
			    if (pGDev) {
				/* After configure pass 1, chipID and chipRev
				 * are treated as over-rides, so clobber them
				 * here.
				 */
				pGDev->chipID = -1;
				pGDev->chipRev = -1;
			    }

			    numFound++;
			}
		    }
		    else {
			numFound++;
		    }

		    break;
		}
	    }
	}
    }


    /* In "probe only" or "configure" mode (signaled by instances being NULL),
     * our work is done.  Return the number of detected devices.
     */
    if ( instances == NULL ) {
	return numFound;
    }


    /*
     * This may be debatable, but if no PCI devices with a matching vendor
     * type is found, return zero now.  It is probably not desirable to
     * allow the config file to override this.
     */
    if (allocatedInstances <= 0) {
	xfree(instances);
	return 0;
    }


#ifdef DEBUG
    ErrorF("%s instances found: %d\n", driverName, allocatedInstances);
#endif

   /*
    * Check for devices that need duplicated instances.  This is required
    * when there is more than one screen per entity.
    *
    * XXX This currently doesn't work for cases where the BusID isn't
    * specified explicitly in the config file.
    */

    for (j = 0; j < numDevs; j++) {
        if (devList[j]->screen > 0 && devList[j]->busID 
	    && *devList[j]->busID) {
	    for (i = 0; i < allocatedInstances; i++) {
	        pPci = instances[i].pci;
	        if (xf86ComparePciBusString(devList[j]->busID, pPci->bus,
					    pPci->device,
					    pPci->func)) {
		    allocatedInstances++;
		    instances[allocatedInstances - 1] = instances[i];
		    instances[allocatedInstances - 1].screen =
		      				devList[j]->screen;
		    numFound++;
		    break;
		}
	    }
	}
    }

    for (i = 0; i < allocatedInstances; i++) {
	GDevPtr dev = NULL;
	GDevPtr devBus = NULL;

	pPci = instances[i].pci;
	for (j = 0; j < numDevs; j++) {
	    if (devList[j]->busID && *devList[j]->busID) {
		if (xf86ComparePciBusString(devList[j]->busID, pPci->bus,
					   pPci->device,
					   pPci->func) &&
		    devList[j]->screen == instances[i].screen) {
		   
		    if (devBus)
                        xf86MsgVerb(X_WARNING,0,
			    "%s: More than one matching Device section for "
			    "instances\n\t(BusID: %s) found: %s\n",
			    driverName, devList[j]->busID,
			    devList[j]->identifier);
		    else
			devBus = devList[j];
		} 
	    } else {
		/* 
		 * if device section without BusID is found 
		 * only assign to it to the primary device.
		 */
		if (xf86IsPrimaryPci(pPci)) {
		    xf86Msg(X_PROBED, "Assigning device section with no busID"
			    " to primary device\n");
		    if (dev || devBus)
			xf86MsgVerb(X_WARNING, 0,
			    "%s: More than one matching Device section "
			    "found: %s\n", driverName, devList[j]->identifier);
		    else
			dev = devList[j];
		}
	    }
	}
	if (devBus) dev = devBus;  /* busID preferred */ 
	if (!dev) {
	    if (xf86CheckPciSlot(pPci->bus, pPci->device, pPci->func)) {
		xf86MsgVerb(X_WARNING, 0, "%s: No matching Device section "
			    "for instance (BusID PCI:%i:%i:%i) found\n",
			    driverName, pPci->bus, pPci->device, pPci->func);
	    }
	} else {
	    numClaimedInstances++;
	    instances[i].claimed = TRUE;
	    instances[i].dev = dev;
	}
    }
#ifdef DEBUG
    ErrorF("%s instances found: %d\n", driverName, numClaimedInstances);
#endif
    /*
     * Now check that a chipset or chipID override in the device section
     * is valid.  Chipset has precedence over chipID.
     * If chipset is not valid ignore BusSlot completely.
     */
    for (i = 0; i < allocatedInstances && numClaimedInstances > 0; i++) {
	MessageType from = X_PROBED;

	if (!instances[i].claimed) {
	    continue;
	}
	if (instances[i].dev->chipset) {
	    for (c = chipsets; c->token >= 0; c++) {
		if (xf86NameCmp(c->name, instances[i].dev->chipset) == 0)
		    break;
	    }
	    if (c->token == -1) {
		instances[i].claimed = FALSE;
		numClaimedInstances--;
		xf86MsgVerb(X_WARNING, 0, "%s: Chipset \"%s\" in Device "
			    "section \"%s\" isn't valid for this driver\n",
			    driverName, instances[i].dev->chipset,
			    instances[i].dev->identifier);
	    } else {
		instances[i].chip = c->token;

		for (id = PCIchipsets; id->numChipset >= 0; id++) {
		    if (id->numChipset == instances[i].chip)
			break;
		}
		if(id->numChipset >=0){
		    xf86Msg(X_CONFIG,"Chipset override: %s\n",
			     instances[i].dev->chipset);
		    from = X_CONFIG;
		} else {
		    instances[i].claimed = FALSE;
		    numClaimedInstances--;
		    xf86MsgVerb(X_WARNING, 0, "%s: Chipset \"%s\" in Device "
				"section \"%s\" isn't a valid PCI chipset\n",
				driverName, instances[i].dev->chipset,
				instances[i].dev->identifier);
		}
	    }
	} else if (instances[i].dev->chipID > 0) {
	    for (id = PCIchipsets; id->numChipset >= 0; id++) {
		if (id->PCIid == instances[i].dev->chipID)
		    break;
	    }
	    if (id->numChipset == -1) {
		instances[i].claimed = FALSE;
		numClaimedInstances--;
		xf86MsgVerb(X_WARNING, 0, "%s: ChipID 0x%04X in Device "
			    "section \"%s\" isn't valid for this driver\n",
			    driverName, instances[i].dev->chipID,
			    instances[i].dev->identifier);
	    } else {
		instances[i].chip = id->numChipset;

		xf86Msg( X_CONFIG,"ChipID override: 0x%04X\n",
			 instances[i].dev->chipID);
		from = X_CONFIG;
	    }
	} else if (!instances[i].foundHW) {
	    /*
	     * This means that there was no override and the PCI chipType
	     * doesn't match one that is supported
	     */
	    instances[i].claimed = FALSE;
	    numClaimedInstances--;
	}
	if (instances[i].claimed == TRUE){
	    for (c = chipsets; c->token >= 0; c++) {
		if (c->token == instances[i].chip)
		    break;
	    }
	    xf86Msg(from,"Chipset %s found\n",
		    c->name);
	}
    }

    /*
     * Of the claimed instances, check that another driver hasn't already
     * claimed its slot.
     */
    numFound = 0;
    for (i = 0; i < allocatedInstances && numClaimedInstances > 0; i++) {
	
	if (!instances[i].claimed)
	    continue;
	pPci = instances[i].pci;


        /*
	 * Allow the same entity to be used more than once for devices with
	 * multiple screens per entity.  This assumes implicitly that there
	 * will be a screen == 0 instance.
	 *
	 * XXX Need to make sure that two different drivers don't claim
	 * the same screen > 0 instance.
	 */
        if (instances[i].screen == 0 &&
	    !xf86CheckPciSlot(pPci->bus, pPci->device, pPci->func))
	    continue;

#ifdef DEBUG
	ErrorF("%s: card at %d:%d:%d is claimed by a Device section\n",
	       driverName, pPci->bus, pPci->device, pPci->func);
#endif
	
	/* Allocate an entry in the lists to be returned */
	numFound++;
	retEntities = xnfrealloc(retEntities, numFound * sizeof(int));
	retEntities[numFound - 1]
	    = xf86ClaimPciSlot(pPci->bus, pPci->device,
			       pPci->func,drvp,	instances[i].chip,
			       instances[i].dev,instances[i].dev->active ?
			       TRUE : FALSE);
        if (retEntities[numFound - 1] == -1 && instances[i].screen > 0) {
	    for (j = 0; j < xf86NumEntities; j++) {
	        EntityPtr pEnt = xf86Entities[j];
	        if (pEnt->busType != BUS_PCI)
		    continue;
	        if (pEnt->pciBusId.bus == pPci->bus &&
		    pEnt->pciBusId.device == pPci->device &&
		    pEnt->pciBusId.func == pPci->func) {
		    retEntities[numFound - 1] = j;
		    xf86AddDevToEntity(j, instances[i].dev);
		    break;
		}
	    }
	}
    }
    xfree(instances);
    if (numFound > 0) {
	*foundEntities = retEntities;
    }
	
    return numFound;
}

_X_EXPORT int
xf86MatchIsaInstances(const char *driverName, SymTabPtr chipsets,
		      IsaChipsets *ISAchipsets, DriverPtr drvp,
		      FindIsaDevProc FindIsaDevice, GDevPtr *devList,
		      int numDevs, int **foundEntities)
{
    SymTabRec *c;
    IsaChipsets *Chips;
    int i;
    int numFound = 0;
    int foundChip = -1;
    int *retEntities = NULL;

    *foundEntities = NULL;

#if defined(__sparc__) || defined(__powerpc__)
    FindIsaDevice = NULL;	/* Temporary */
#endif

    if (xf86DoProbe || (xf86DoConfigure && xf86DoConfigurePass1)) {
	if (FindIsaDevice &&
	    ((foundChip = (*FindIsaDevice)(NULL)) != -1)) {
	    xf86AddDeviceToConfigure(drvp->driverName, NULL, foundChip);
	    return 1;
	}
	return 0;
    }

    for (i = 0; i < numDevs; i++) {
	MessageType from = X_CONFIG;
	GDevPtr dev = NULL;
	GDevPtr devBus = NULL;

	if (devList[i]->busID && *devList[i]->busID) {
	    if (xf86ParseIsaBusString(devList[i]->busID)) {
		if (devBus) xf86MsgVerb(X_WARNING,0,
					"%s: More than one matching Device "
					"section for ISA-Bus found: %s\n",
					driverName,devList[i]->identifier);
		else devBus = devList[i];
	    }
	} else {
	    if (xf86IsPrimaryIsa()) {
		if (dev) xf86MsgVerb(X_WARNING,0,
				     "%s: More than one matching "
				     "Device section found: %s\n",
				     driverName,devList[i]->identifier);
		else dev = devList[i];
	    }
	}
	if (devBus) dev = devBus;
	if (dev) {
	    if (dev->chipset) {
		for (c = chipsets; c->token >= 0; c++) {
		    if (xf86NameCmp(c->name, dev->chipset) == 0)
			break;
		}
		if (c->token == -1) {
		    xf86MsgVerb(X_WARNING, 0, "%s: Chipset \"%s\" in Device "
				"section \"%s\" isn't valid for this driver\n",
				driverName, dev->chipset,
				dev->identifier);
		} else
		    foundChip = c->token;
	    } else { 
		if (FindIsaDevice) foundChip = (*FindIsaDevice)(dev);
                                                        /* Probe it */
		from = X_PROBED;
	    }
	}
	
	/* Check if the chip type is listed in the chipset table - for sanity*/

	if (foundChip >= 0){
	    for (Chips = ISAchipsets; Chips->numChipset >= 0; Chips++) {
		if (Chips->numChipset == foundChip) 
		    break;
	    }
	    if (Chips->numChipset == -1){
		foundChip = -1;
		xf86MsgVerb(X_WARNING,0,
			    "%s: Driver detected unknown ISA-Bus Chipset\n",
			    driverName);
	    }
	}
	if (foundChip != -1) {
	    numFound++;
	    retEntities = xnfrealloc(retEntities,numFound * sizeof(int));
	    retEntities[numFound - 1] =
	    xf86ClaimIsaSlot(drvp,foundChip,dev, dev->active ? TRUE : FALSE);
	    for (c = chipsets; c->token >= 0; c++) {
		if (c->token == foundChip)
		    break;
	    }
	    xf86Msg(from, "Chipset %s found\n", c->name);
	}
    }
    *foundEntities = retEntities;
    
    return numFound;
}

/*
 * xf86GetClocks -- get the dot-clocks via a BIG BAD hack ...
 */
_X_EXPORT void
xf86GetClocks(ScrnInfoPtr pScrn, int num, Bool (*ClockFunc)(ScrnInfoPtr, int),
	      void (*ProtectRegs)(ScrnInfoPtr, Bool),
	      void (*BlankScreen)(ScrnInfoPtr, Bool), IOADDRESS vertsyncreg,
	      int maskval, int knownclkindex, int knownclkvalue)
{
    register int status = vertsyncreg;
    unsigned long i, cnt, rcnt, sync;

    /* First save registers that get written on */
    (*ClockFunc)(pScrn, CLK_REG_SAVE);

    xf86SetPriority(TRUE);

    if (num > MAXCLOCKS)
	num = MAXCLOCKS;

    for (i = 0; i < num; i++) 
    {
	if (ProtectRegs)
	    (*ProtectRegs)(pScrn, TRUE);
	if (!(*ClockFunc)(pScrn, i))
	{
	    pScrn->clock[i] = -1;
	    continue;
	}
	if (ProtectRegs)
	    (*ProtectRegs)(pScrn, FALSE);
	if (BlankScreen)
	    (*BlankScreen)(pScrn, FALSE);
	    
    	usleep(50000);     /* let VCO stabilise */

    	cnt  = 0;
    	sync = 200000;

	/* XXX How critical is this? */
    	if (!xf86DisableInterrupts())
    	{
	    (*ClockFunc)(pScrn, CLK_REG_RESTORE);
	    ErrorF("Failed to disable interrupts during clock probe.  If\n");
	    ErrorF("your OS does not support disabling interrupts, then you\n");
	    FatalError("must specify a Clocks line in the XF86Config file.\n");
	}
	while ((inb(status) & maskval) == 0x00) 
	    if (sync-- == 0) goto finish;
	/* Something appears to be happening, so reset sync count */
	sync = 200000;
	while ((inb(status) & maskval) == maskval) 
	    if (sync-- == 0) goto finish;
	/* Something appears to be happening, so reset sync count */
	sync = 200000;
	while ((inb(status) & maskval) == 0x00) 
	    if (sync-- == 0) goto finish;
    
	for (rcnt = 0; rcnt < 5; rcnt++) 
	{
	    while (!(inb(status) & maskval)) 
		cnt++;
	    while ((inb(status) & maskval)) 
		cnt++;
	}
    
finish:
	xf86EnableInterrupts();

	pScrn->clock[i] = cnt ? cnt : -1;
	if (BlankScreen)
            (*BlankScreen)(pScrn, TRUE);
    }

    xf86SetPriority(FALSE);

    for (i = 0; i < num; i++) 
    {
	if (i != knownclkindex)
	{
	    if (pScrn->clock[i] == -1)
	    {
		pScrn->clock[i] = 0;
	    }
	    else 
	    {
		pScrn->clock[i] = (int)(0.5 +
                    (((float)knownclkvalue) * pScrn->clock[knownclkindex]) / 
	            (pScrn->clock[i]));
		/* Round to nearest 10KHz */
		pScrn->clock[i] += 5;
		pScrn->clock[i] /= 10;
		pScrn->clock[i] *= 10;
	    }
	}
    }

    pScrn->clock[knownclkindex] = knownclkvalue;
    pScrn->numClocks = num; 

    /* Restore registers that were written on */
    (*ClockFunc)(pScrn, CLK_REG_RESTORE);
}

_X_EXPORT void
xf86SetPriority(Bool up)
{
    static int saved_nice;

    if (up) {
#ifdef HAS_SETPRIORITY
	saved_nice = getpriority(PRIO_PROCESS, 0);
	setpriority(PRIO_PROCESS, 0, -20);
#endif
#if defined(SYSV) || defined(SVR4) || defined(linux)
	saved_nice = nice(0);
	nice(-20 - saved_nice);
#endif
    } else {
#ifdef HAS_SETPRIORITY
	setpriority(PRIO_PROCESS, 0, saved_nice);
#endif
#if defined(SYSV) || defined(SVR4) || defined(linux)
	nice(20 + saved_nice);
#endif
    }
}

_X_EXPORT const char *
xf86GetVisualName(int visual)
{
    if (visual < 0 || visual > DirectColor)
	return NULL;

    return xf86VisualNames[visual];
}


_X_EXPORT int
xf86GetVerbosity()
{
    return max(xf86Verbose, xf86LogVerbose);
}

_X_EXPORT Pix24Flags
xf86GetPix24()
{
    return xf86Info.pixmap24;
}


_X_EXPORT int
xf86GetDepth()
{
    return xf86Depth;
}


_X_EXPORT rgb
xf86GetWeight()
{
    return xf86Weight;
}


_X_EXPORT Gamma
xf86GetGamma()
{
    return xf86Gamma;
}


_X_EXPORT Bool
xf86GetFlipPixels()
{
    return xf86FlipPixels;
}


_X_EXPORT const char *
xf86GetServerName()
{
    return xf86ServerName;
}


_X_EXPORT Bool
xf86ServerIsExiting()
{
    return (dispatchException & DE_TERMINATE) == DE_TERMINATE;
}


_X_EXPORT Bool
xf86ServerIsResetting()
{
    return xf86Resetting;
}


Bool
xf86ServerIsInitialising()
{
    return xf86Initialising;
}


_X_EXPORT Bool
xf86ServerIsOnlyDetecting(void)
{
    return xf86DoProbe || xf86DoConfigure;
}


_X_EXPORT Bool
xf86ServerIsOnlyProbing(void)
{
    return xf86ProbeOnly;
}


_X_EXPORT Bool
xf86CaughtSignal()
{
    return xf86Info.caughtSignal;
}


_X_EXPORT Bool
xf86GetVidModeAllowNonLocal()
{
    return xf86Info.vidModeAllowNonLocal;
}


_X_EXPORT Bool
xf86GetVidModeEnabled()
{
    return xf86Info.vidModeEnabled;
}

_X_EXPORT Bool
xf86GetModInDevAllowNonLocal()
{
    return xf86Info.miscModInDevAllowNonLocal;
}


_X_EXPORT Bool
xf86GetModInDevEnabled()
{
    return xf86Info.miscModInDevEnabled;
}


_X_EXPORT Bool
xf86GetAllowMouseOpenFail()
{
    return xf86Info.allowMouseOpenFail;
}


_X_EXPORT Bool
xf86IsPc98()
{
#if defined(i386) || defined(__i386__)
    return xf86Info.pc98;
#else
    return FALSE;
#endif
}

_X_EXPORT void
xf86DisableRandR()
{
    xf86Info.disableRandR = TRUE;
    xf86Info.randRFrom = X_PROBED;
}

_X_EXPORT CARD32
xf86GetVersion()
{
    return XF86_VERSION_CURRENT;
}

_X_EXPORT CARD32
xf86GetModuleVersion(pointer module)
{
    return (CARD32)LoaderGetModuleVersion(module);
}

_X_EXPORT pointer
xf86LoadDrvSubModule(DriverPtr drv, const char *name)
{
    pointer ret;
    int errmaj = 0, errmin = 0;

    ret = LoadSubModule(drv->module, name, NULL, NULL, NULL, NULL,
			&errmaj, &errmin);
    if (!ret)
	LoaderErrorMsg(NULL, name, errmaj, errmin);
    return ret;
}

_X_EXPORT pointer
xf86LoadSubModule(ScrnInfoPtr pScrn, const char *name)
{
    pointer ret;
    int errmaj = 0, errmin = 0;

    ret = LoadSubModule(pScrn->module, name, NULL, NULL, NULL, NULL,
			&errmaj, &errmin);
    if (!ret)
	LoaderErrorMsg(pScrn->name, name, errmaj, errmin);
    return ret;
}

/*
 * xf86LoadOneModule loads a single module.
 */             
_X_EXPORT pointer
xf86LoadOneModule(char *name, pointer opt)
{
    int errmaj, errmin;
    char *Name;
    pointer mod;
    
    if (!name)
	return NULL;
    
#ifndef NORMALISE_MODULE_NAME
    Name = xstrdup(name);
#else
    /* Normalise the module name */
    Name = xf86NormalizeName(name);
#endif

    /* Skip empty names */
    if (Name == NULL)
	return NULL;
    if (*Name == '\0') {
	xfree(Name);
	return NULL;
    }

    mod = LoadModule(Name, NULL, NULL, NULL, opt, NULL, &errmaj, &errmin);
    if (!mod)
	LoaderErrorMsg(NULL, Name, errmaj, errmin);
    xfree(Name);
    return mod;
}

_X_EXPORT void
xf86UnloadSubModule(pointer mod)
{
    /*
     * This is disabled for now.  The loader isn't smart enough yet to undo
     * relocations.
     */
#if 0
    UnloadSubModule(mod);
#endif
}

_X_EXPORT Bool
xf86LoaderCheckSymbol(const char *name)
{
    return LoaderSymbol(name) != NULL;
}

_X_EXPORT void
xf86LoaderReqSymLists(const char **list0, ...)
{
    va_list ap;

    va_start(ap, list0);
    LoaderVReqSymLists(list0, ap);
    va_end(ap);
}

_X_EXPORT void
xf86LoaderReqSymbols(const char *sym0, ...)
{
    va_list ap;

    va_start(ap, sym0);
    LoaderVReqSymbols(sym0, ap);
    va_end(ap);
}

_X_EXPORT void
xf86LoaderRefSymLists(const char **list0, ...)
{
    va_list ap;

    va_start(ap, list0);
    LoaderVRefSymLists(list0, ap);
    va_end(ap);
}

_X_EXPORT void
xf86LoaderRefSymbols(const char *sym0, ...)
{
    va_list ap;

    va_start(ap, sym0);
    LoaderVRefSymbols(sym0, ap);
    va_end(ap);
}


typedef enum {
   OPTION_BACKING_STORE
} BSOpts;

static const OptionInfoRec BSOptions[] = {
   { OPTION_BACKING_STORE, "BackingStore", OPTV_BOOLEAN, {0}, FALSE },
   { -1,                   NULL,           OPTV_NONE,    {0}, FALSE }
};

_X_EXPORT void 
xf86SetBackingStore(ScreenPtr pScreen)
{
    Bool useBS = FALSE;
    MessageType from = X_DEFAULT;
    ScrnInfoPtr pScrn = xf86Screens[pScreen->myNum];
    OptionInfoPtr options;

    options = xnfalloc(sizeof(BSOptions));
    (void)memcpy(options, BSOptions, sizeof(BSOptions));
    xf86ProcessOptions(pScrn->scrnIndex, pScrn->options, options);

    /* check for commandline option here */
    if (xf86bsEnableFlag) {
	from = X_CMDLINE;
	useBS = TRUE;
    } else if (xf86bsDisableFlag) {
	from = X_CMDLINE;
	useBS = FALSE;
    } else {
	if (xf86GetOptValBool(options, OPTION_BACKING_STORE, &useBS))
	    from = X_CONFIG;
    }
    xfree(options);
    pScreen->backingStoreSupport = useBS ? Always : NotUseful;
    if (serverGeneration == 1)
	xf86DrvMsg(pScreen->myNum, from, "Backing store %s\n",
		   useBS ? "enabled" : "disabled");
}


typedef enum {
   OPTION_SILKEN_MOUSE
} SMOpts;

static const OptionInfoRec SMOptions[] = {
   { OPTION_SILKEN_MOUSE, "SilkenMouse",   OPTV_BOOLEAN, {0}, FALSE },
   { -1,                   NULL,           OPTV_NONE,    {0}, FALSE }
};

_X_EXPORT void 
xf86SetSilkenMouse (ScreenPtr pScreen)
{
    Bool useSM = TRUE;
    MessageType from = X_DEFAULT;
    ScrnInfoPtr pScrn = xf86Screens[pScreen->myNum];
    OptionInfoPtr options;

    options = xnfalloc(sizeof(SMOptions));
    (void)memcpy(options, SMOptions, sizeof(SMOptions));
    xf86ProcessOptions(pScrn->scrnIndex, pScrn->options, options);
    
    /* check for commandline option here */
    /* disable if screen shares resources */
    if (((pScrn->racMemFlags & RAC_CURSOR) && 
	 !xf86NoSharedResources(pScrn->scrnIndex,MEM)) ||
	((pScrn->racIoFlags & RAC_CURSOR) && 
	 !xf86NoSharedResources(pScrn->scrnIndex,IO))) {
	useSM = FALSE;
	from = X_PROBED;
    } else if (xf86silkenMouseDisableFlag) {
        from = X_CMDLINE;
	useSM = FALSE;
    } else {
	if (xf86GetOptValBool(options, OPTION_SILKEN_MOUSE, &useSM))
	    from = X_CONFIG;
    }
    xfree(options);
    /*
     * XXX quick hack to report correctly for OSs that can't do SilkenMouse
     * yet.  Should handle this differently so that alternate async methods
     * like Xqueue work correctly with this too.
     */
    pScrn->silkenMouse = useSM && xf86SIGIOSupported();
    if (serverGeneration == 1)
	xf86DrvMsg(pScreen->myNum, from, "Silken mouse %s\n",
		   pScrn->silkenMouse ? "enabled" : "disabled");
}

/* Wrote this function for the PM2 Xv driver, preliminary. */

_X_EXPORT pointer
xf86FindXvOptions(int scrnIndex, int adaptor_index, char *port_name,
		  char **adaptor_name, pointer *adaptor_options)
{
    ScrnInfoPtr pScrn = xf86Screens[scrnIndex];
    confXvAdaptorPtr adaptor;
    int i;

    if (adaptor_index >= pScrn->confScreen->numxvadaptors) {
	if (adaptor_name) *adaptor_name = NULL;
	if (adaptor_options) *adaptor_options = NULL;
	return NULL;
    }

    adaptor = &pScrn->confScreen->xvadaptors[adaptor_index];
    if (adaptor_name) *adaptor_name = adaptor->identifier;
    if (adaptor_options) *adaptor_options = adaptor->options;

    for (i = 0; i < adaptor->numports; i++)
	if (!xf86NameCmp(adaptor->ports[i].identifier, port_name))
	    return adaptor->ports[i].options;

    return NULL;
}

/* Rather than duplicate loader's get OS function, just include it directly */
#define LoaderGetOS xf86GetOS
#include "loader/os.c"

/* new RAC */
/*
 * xf86ConfigIsa/PciEntity() -- These helper functions assign an
 * active entity to a screen, registers its fixed resources, assign
 * special enter/leave functions and their private scratch area to
 * this entity, take the dog for a walk...
 */
_X_EXPORT ScrnInfoPtr
xf86ConfigIsaEntity(ScrnInfoPtr pScrn, int scrnFlag, int entityIndex,
			  IsaChipsets *i_chip, resList res, EntityProc init,
			  EntityProc enter, EntityProc leave, pointer private)
{
    IsaChipsets *i_id;
    EntityInfoPtr pEnt = xf86GetEntityInfo(entityIndex);
    if (!pEnt) return pScrn;
    
    if (!(pEnt->location.type == BUS_ISA)) {
	xfree(pEnt);
	return pScrn;
    }

    if (!pEnt->active) {
	xf86ConfigIsaEntityInactive(pEnt, i_chip, res, init,  enter,
				    leave,  private);
	xfree(pEnt);
	return pScrn;
    }

    if (!pScrn)
	pScrn = xf86AllocateScreen(pEnt->driver,scrnFlag); 
    xf86AddEntityToScreen(pScrn,entityIndex);

    if (i_chip) {
	for (i_id = i_chip; i_id->numChipset != -1; i_id++) {
	    if (pEnt->chipset == i_id->numChipset) break;
	}
	xf86ClaimFixedResources(i_id->resList,entityIndex);
    }
    xfree(pEnt);
    xf86ClaimFixedResources(res,entityIndex);
    xf86SetEntityFuncs(entityIndex,init,enter,leave,private);

    return pScrn;
}

_X_EXPORT ScrnInfoPtr
xf86ConfigPciEntity(ScrnInfoPtr pScrn, int scrnFlag, int entityIndex,
			  PciChipsets *p_chip, resList res, EntityProc init,
			  EntityProc enter, EntityProc leave, pointer private)
{
    PciChipsets *p_id;
    EntityInfoPtr pEnt = xf86GetEntityInfo(entityIndex);
    if (!pEnt) return pScrn;

    if (!(pEnt->location.type == BUS_PCI) 
	|| !xf86GetPciInfoForEntity(entityIndex)) {
	xfree(pEnt);
	return pScrn;
    }
    if (!pEnt->active) {
	xf86ConfigPciEntityInactive(pEnt, p_chip, res, init,  enter,
				    leave,  private);
	xfree(pEnt);
	return pScrn;
    }

    if (!pScrn)
	pScrn = xf86AllocateScreen(pEnt->driver,scrnFlag);
    if (xf86IsEntitySharable(entityIndex)) {
        xf86SetEntityShared(entityIndex);
    }
    xf86AddEntityToScreen(pScrn,entityIndex);
    if (xf86IsEntityShared(entityIndex)) {
        return pScrn;
    }
    if (p_chip) {
	for (p_id = p_chip; p_id->numChipset != -1; p_id++) {
	    if (pEnt->chipset == p_id->numChipset) break;
	}
	xf86ClaimFixedResources(p_id->resList,entityIndex);
    }
    xfree(pEnt);

    xf86ClaimFixedResources(res,entityIndex);
    xf86SetEntityFuncs(entityIndex,init,enter,leave,private);

    return pScrn;
}

_X_EXPORT ScrnInfoPtr
xf86ConfigFbEntity(ScrnInfoPtr pScrn, int scrnFlag, int entityIndex,
		   EntityProc init, EntityProc enter, EntityProc leave, 
		   pointer private)
{
    EntityInfoPtr pEnt = xf86GetEntityInfo(entityIndex);
    if (!pEnt) return pScrn;
    
    if (!(pEnt->location.type == BUS_NONE)) {
	xfree(pEnt);
	return pScrn;
    }

    if (!pEnt->active) {
	xf86ConfigFbEntityInactive(pEnt, init,  enter, leave,  private);
	xfree(pEnt);
	return pScrn;
    }

    if (!pScrn)
	pScrn = xf86AllocateScreen(pEnt->driver,scrnFlag); 
    xf86AddEntityToScreen(pScrn,entityIndex);

    xf86SetEntityFuncs(entityIndex,init,enter,leave,private);

    return pScrn;
}

/*
 *
 *  OBSOLETE ! xf86ConfigActiveIsaEntity() and xf86ConfigActivePciEntity()
 *             are obsolete functions. They the are likely to be removed
 *             Don't use!
 */
_X_EXPORT Bool
xf86ConfigActiveIsaEntity(ScrnInfoPtr pScrn, int entityIndex,
                          IsaChipsets *i_chip, resList res, EntityProc init,
                          EntityProc enter, EntityProc leave, pointer private)
{
    IsaChipsets *i_id;
    EntityInfoPtr pEnt = xf86GetEntityInfo(entityIndex);
    if (!pEnt) return FALSE;
 
    if (!pEnt->active || !(pEnt->location.type == BUS_ISA)) {
        xfree(pEnt);
        return FALSE;
    }
 
    xf86AddEntityToScreen(pScrn,entityIndex);
 
    if (i_chip) {
        for (i_id = i_chip; i_id->numChipset != -1; i_id++) {
            if (pEnt->chipset == i_id->numChipset) break;
        }
        xf86ClaimFixedResources(i_id->resList,entityIndex);
    }
    xfree(pEnt);
    xf86ClaimFixedResources(res,entityIndex);
    if (!xf86SetEntityFuncs(entityIndex,init,enter,leave,private))
        return FALSE;
 
    return TRUE;
}
 
_X_EXPORT Bool
xf86ConfigActivePciEntity(ScrnInfoPtr pScrn, int entityIndex,
                          PciChipsets *p_chip, resList res, EntityProc init,
                          EntityProc enter, EntityProc leave, pointer private)
{
    PciChipsets *p_id;
    EntityInfoPtr pEnt = xf86GetEntityInfo(entityIndex);
    if (!pEnt) return FALSE;
 
    if (!pEnt->active || !(pEnt->location.type == BUS_PCI)) {
        xfree(pEnt);
        return FALSE;
    }
    xf86AddEntityToScreen(pScrn,entityIndex);
 
    if (p_chip) {
        for (p_id = p_chip; p_id->numChipset != -1; p_id++) {
            if (pEnt->chipset == p_id->numChipset) break;
        }
        xf86ClaimFixedResources(p_id->resList,entityIndex);
    }
    xfree(pEnt);
 
    xf86ClaimFixedResources(res,entityIndex);
    if (!xf86SetEntityFuncs(entityIndex,init,enter,leave,private))
        return FALSE;
 
    return TRUE;
}

/*
 * xf86ConfigPci/IsaEntityInactive() -- These functions can be used
 * to configure an inactive entity as well as to reconfigure an
 * previously active entity inactive. If the entity has been
 * assigned to a screen before it will be removed. If p_pci(p_isa) is
 * non-NULL all static resources listed there will be registered.
 */
_X_EXPORT void
xf86ConfigPciEntityInactive(EntityInfoPtr pEnt, PciChipsets *p_chip,
			    resList res, EntityProc init, EntityProc enter,
			    EntityProc leave, pointer private)
{
    PciChipsets *p_id;
    ScrnInfoPtr pScrn;

    if ((pScrn = xf86FindScreenForEntity(pEnt->index)))
	xf86RemoveEntityFromScreen(pScrn,pEnt->index);
    else if (p_chip) {
	for (p_id = p_chip; p_id->numChipset != -1; p_id++) {
	    if (pEnt->chipset == p_id->numChipset) break;
	}
	xf86ClaimFixedResources(p_id->resList,pEnt->index);
    }
    xf86ClaimFixedResources(res,pEnt->index);
    /* shared resources are only needed when entity is active: remove */
    xf86DeallocateResourcesForEntity(pEnt->index, ResShared);
    xf86SetEntityFuncs(pEnt->index,init,enter,leave,private);
}

_X_EXPORT void
xf86ConfigIsaEntityInactive(EntityInfoPtr pEnt, IsaChipsets *i_chip,
			    resList res, EntityProc init, EntityProc enter,
			    EntityProc leave, pointer private)
{
    IsaChipsets *i_id;
    ScrnInfoPtr pScrn;

    if ((pScrn = xf86FindScreenForEntity(pEnt->index)))
	xf86RemoveEntityFromScreen(pScrn,pEnt->index);
    else if (i_chip) {
	for (i_id = i_chip; i_id->numChipset != -1; i_id++) {
	    if (pEnt->chipset == i_id->numChipset) break;
	}
	xf86ClaimFixedResources(i_id->resList,pEnt->index);
    }
    xf86ClaimFixedResources(res,pEnt->index);
    /* shared resources are only needed when entity is active: remove */
    xf86DeallocateResourcesForEntity(pEnt->index, ResShared);
    xf86SetEntityFuncs(pEnt->index,init,enter,leave,private);
}

void
xf86ConfigFbEntityInactive(EntityInfoPtr pEnt, EntityProc init, 
			   EntityProc enter, EntityProc leave, pointer private)
{
    ScrnInfoPtr pScrn;

    if ((pScrn = xf86FindScreenForEntity(pEnt->index)))
	xf86RemoveEntityFromScreen(pScrn,pEnt->index);
    xf86SetEntityFuncs(pEnt->index,init,enter,leave,private);
}

_X_EXPORT Bool
xf86IsScreenPrimary(int scrnIndex)
{
    ScrnInfoPtr pScrn = xf86Screens[scrnIndex];
    int i;

    for (i=0 ; i < pScrn->numEntities; i++) {
	if (xf86IsEntityPrimary(i))
	    return TRUE;
    }
    return FALSE;
}

_X_EXPORT int
xf86RegisterRootWindowProperty(int ScrnIndex, Atom property, Atom type,
			       int format, unsigned long len, pointer value )
{
    RootWinPropPtr pNewProp = NULL, pRegProp;
    int i;
    Bool existing = FALSE;

#ifdef DEBUG
    ErrorF("xf86RegisterRootWindowProperty(%d, %ld, %ld, %d, %ld, %p)\n",
	   ScrnIndex, property, type, format, len, value);
#endif

    if (ScrnIndex<0 || ScrnIndex>=xf86NumScreens) {
      return(BadMatch);
    }

    if (xf86RegisteredPropertiesTable &&
	xf86RegisteredPropertiesTable[ScrnIndex]) {
      for (pNewProp = xf86RegisteredPropertiesTable[ScrnIndex];
	   pNewProp; pNewProp = pNewProp->next) {
	if (strcmp(pNewProp->name, NameForAtom(property)) == 0)
	  break;
      }
    }

    if (!pNewProp) {
      if ((pNewProp = (RootWinPropPtr)xalloc(sizeof(RootWinProp))) == NULL) {
	return(BadAlloc);
      }
      /*
       * We will put this property at the end of the list so that
       * the changes are made in the order they were requested.
       */
      pNewProp->next = NULL;
    } else {
      if (pNewProp->name)
	xfree(pNewProp->name);
      existing = TRUE;
    }

    pNewProp->name = xnfstrdup(NameForAtom(property));
    pNewProp->type = type;
    pNewProp->format = format;
    pNewProp->size = len;
    pNewProp->data = value;
 
#ifdef DEBUG
    ErrorF("new property filled\n");
#endif

    if (NULL==xf86RegisteredPropertiesTable) {
#ifdef DEBUG
      ErrorF("creating xf86RegisteredPropertiesTable[] size %d\n",
	     xf86NumScreens);
#endif
      if ( NULL==(xf86RegisteredPropertiesTable=(RootWinPropPtr*)xnfcalloc(sizeof(RootWinProp),xf86NumScreens) )) {
	return(BadAlloc);
      }
      for (i=0; i<xf86NumScreens; i++) {
	xf86RegisteredPropertiesTable[i] = NULL;
      }
    }

#ifdef DEBUG
    ErrorF("xf86RegisteredPropertiesTable %p\n",
	   (void *)xf86RegisteredPropertiesTable);
    ErrorF("xf86RegisteredPropertiesTable[%d] %p\n",
	   ScrnIndex, (void *)xf86RegisteredPropertiesTable[ScrnIndex]);
#endif

    if (!existing) {
      if ( xf86RegisteredPropertiesTable[ScrnIndex] == NULL) {
	xf86RegisteredPropertiesTable[ScrnIndex] = pNewProp;
      } else {
	pRegProp = xf86RegisteredPropertiesTable[ScrnIndex];
	while (pRegProp->next != NULL) {
#ifdef DEBUG
	  ErrorF("- next %p\n", (void *)pRegProp);
#endif
	  pRegProp = pRegProp->next;
        }
	pRegProp->next = pNewProp;
      }
    }
#ifdef DEBUG
    ErrorF("xf86RegisterRootWindowProperty succeeded\n");
#endif
    return(Success);    
}

_X_EXPORT Bool
xf86IsUnblank(int mode)
{
    switch(mode) {
    case SCREEN_SAVER_OFF:
    case SCREEN_SAVER_FORCER:
	return TRUE;
    case SCREEN_SAVER_ON:
    case SCREEN_SAVER_CYCLE:
	return FALSE;
    default:
	xf86MsgVerb(X_WARNING, 0, "Unexpected save screen mode: %d\n", mode);
	return TRUE;
    }
}