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

/*
 * This file contains the interfaces to the bus-specific code
 */
#define INCLUDE_DEPRECATED 1

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

#include <ctype.h>
#include <stdlib.h>
#include <unistd.h>
#include <X11/X.h>
#include <X11/os.h>
#include "Pci.h"
#include "xf86.h"
#include "xf86Priv.h"
#include "xf86Resources.h"

/* Bus-specific headers */
#include "xf86PciData.h"

#include "xf86Bus.h"

#define XF86_OS_PRIVS
#define NEED_OS_RAC_PROTOS
#include "xf86_OSproc.h"

#include "xf86RAC.h"

/* Bus-specific globals */
Bool pciSlotClaimed = FALSE;
pciConfigPtr *xf86PciInfo = NULL;		/* Full PCI probe info */
pciVideoPtr *xf86PciVideoInfo = NULL;		/* PCI probe for video hw */
pciAccPtr * xf86PciAccInfo = NULL;              /* PCI access related */

/* pcidata globals */
ScanPciSetupProcPtr xf86SetupPciIds = NULL;
ScanPciCloseProcPtr xf86ClosePciIds = NULL;
ScanPciFindByDeviceProcPtr xf86FindPciNamesByDevice = NULL;
ScanPciFindBySubsysProcPtr xf86FindPciNamesBySubsys = NULL;
ScanPciFindClassBySubsysProcPtr xf86FindPciClassBySubsys = NULL;
ScanPciFindClassByDeviceProcPtr xf86FindPciClassByDevice = NULL;

static resPtr pciAvoidRes = NULL;

/* PCI buses */
static PciBusPtr xf86PciBus = NULL;
/* Bus-specific probe/sorting functions */

/* PCI classes that get included in xf86PciVideoInfo */
#define PCIINFOCLASSES(b,s)						      \
    (((b) == PCI_CLASS_PREHISTORIC) ||					      \
     ((b) == PCI_CLASS_DISPLAY) ||					      \
     ((b) == PCI_CLASS_MULTIMEDIA && (s) == PCI_SUBCLASS_MULTIMEDIA_VIDEO) || \
     ((b) == PCI_CLASS_PROCESSOR && (s) == PCI_SUBCLASS_PROCESSOR_COPROC))

/*
 * PCI classes that have messages printed always.  The others are only
 * have a message printed when the vendor/dev IDs are recognised.
 */
#define PCIALWAYSPRINTCLASSES(b,s)					      \
    (((b) == PCI_CLASS_PREHISTORIC && (s) == PCI_SUBCLASS_PREHISTORIC_VGA) || \
     ((b) == PCI_CLASS_DISPLAY) ||					      \
     ((b) == PCI_CLASS_MULTIMEDIA && (s) == PCI_SUBCLASS_MULTIMEDIA_VIDEO))
 
/*
 * PCI classes for which potentially destructive checking of the map sizes
 * may be done.  Any classes where this may be unsafe should be omitted
 * from this list.
 */
#define PCINONSYSTEMCLASSES(b,s) PCIALWAYSPRINTCLASSES(b,s)

/* 
 * PCI classes that use RAC 
 */
#define PCISHAREDIOCLASSES(b,s)					      \
    (((b) == PCI_CLASS_PREHISTORIC && (s) == PCI_SUBCLASS_PREHISTORIC_VGA) || \
     ((b) == PCI_CLASS_DISPLAY && (s) == PCI_SUBCLASS_DISPLAY_VGA))

#define PCI_MEM32_LENGTH_MAX 0xFFFFFFFF

#define B2M(tag,base) pciBusAddrToHostAddr(tag,PCI_MEM,base)
#define B2I(tag,base) pciBusAddrToHostAddr(tag,PCI_IO,base)
#define B2H(tag,base,type) (((type & ResPhysMask) == ResMem) ? \
			B2M(tag, base) : B2I(tag, base))
#define M2B(tag,base) pciHostAddrToBusAddr(tag,PCI_MEM,base)
#define I2B(tag,base) pciHostAddrToBusAddr(tag,PCI_IO,base)
#define H2B(tag,base,type) (((type & ResPhysMask) == ResMem) ? \
			M2B(tag, base) : I2B(tag, base))
#define TAG(pvp) (pciTag(pvp->bus,pvp->device,pvp->func))
#define SIZE(size) ((1 << size) - 1)
#define PCI_SIZE(type,tag,size) (((type & ResPhysMask) == ResMem) \
                        ? pciBusAddrToHostAddr(tag,PCI_MEM_SIZE,size) \
                        : pciBusAddrToHostAddr(tag,PCI_IO_SIZE,size))
#define PCI_M_RANGE(range,tag,begin,end,type) \
	{ \
	    RANGE(range, B2M(tag, begin), B2M(tag, end), \
		  RANGE_TYPE(type, xf86GetPciDomain(tag))); \
	}
#define PCI_I_RANGE(range,tag,begin,end,type) \
	{ \
	    RANGE(range, B2I(tag, begin), B2I(tag, end), \
		  RANGE_TYPE(type, xf86GetPciDomain(tag))); \
	}
#define PCI_X_RANGE(range,tag,begin,end,type) \
{ if ((type & ResPhysMask) == ResMem)  PCI_M_RANGE(range,tag,begin,end,type); \
                else PCI_I_RANGE(range,tag,begin,end,type); } 
#define P_M_RANGE(range,tag,begin,size,type) \
                    PCI_M_RANGE(range,tag,begin,(begin + SIZE(size)),type)
#define P_I_RANGE(range,tag,begin,size,type) \
                    PCI_I_RANGE(range,tag,begin,(begin + SIZE(size)),type)
#define P_X_RANGE(range,tag,begin,size,type) \
{ if ((type & ResPhysMask) == ResMem)  P_M_RANGE(range,tag,begin,size,type); \
                else P_I_RANGE(range,tag,begin,size,type); }
#define PV_M_RANGE(range,pvp,i,type) \
                  P_M_RANGE(range,TAG(pvp),pvp->memBase[i],pvp->size[i],type)
#define PV_B_RANGE(range,pvp,type) \
                  P_M_RANGE(range,TAG(pvp),pvp->biosBase,pvp->biosSize,type)
#define PV_I_RANGE(range,pvp,i,type) \
                  P_I_RANGE(range,TAG(pvp),pvp->ioBase[i],pvp->size[i],type)

static void getPciClassFlags(pciConfigPtr *pcrpp);
static void pciConvertListToHost(int bus, int dev, int func, resPtr list);
static PciBusPtr xf86GetPciBridgeInfo(void);

void
xf86FormatPciBusNumber(int busnum, char *buffer)
{
    /* 'buffer' should be at least 8 characters long */
    if (busnum < 256)
	sprintf(buffer, "%d", busnum);
    else
	sprintf(buffer, "%d@%d", busnum & 0x00ff, busnum >> 8);
}

static Bool
IsBaseUnassigned(CARD32 base)
{
    CARD32 mask;

    if (base & PCI_MAP_IO)
	mask = ~PCI_MAP_IO_ATTR_MASK;
    else
	mask = ~PCI_MAP_MEMORY_ATTR_MASK;

    base &= mask;
    return (!base || (base == mask));
}

static Bool
IsBaseUnassigned64(CARD32 base0, CARD32 base1)
{
    base0 &= ~PCI_MAP_MEMORY_ATTR_MASK;
    base1 &= 0xffffffff;
    
    return ((!base0 && !base1)
	    || ((base0 == ~PCI_MAP_MEMORY_ATTR_MASK)
		&& (base1 == 0xffffffff)));
}

static void
FindPCIVideoInfo(void)
{
    pciConfigPtr pcrp, *pcrpp;
    int i = 0, j, k;
    int num = 0;
    pciVideoPtr info;

    pcrpp = xf86PciInfo = xf86scanpci(0);
    getPciClassFlags(pcrpp);
    
    if (pcrpp == NULL) {
	xf86PciVideoInfo = NULL;
	return;
    }
    xf86PciBus = xf86GetPciBridgeInfo();
    
    while ((pcrp = pcrpp[i])) {
	int baseclass;
	int subclass;

	if (pcrp->listed_class & 0xffff) {
	    baseclass = (pcrp->listed_class >> 8) & 0xff;
	    subclass = pcrp->listed_class & 0xff;
	} else {
	    baseclass = pcrp->pci_base_class;
	    subclass = pcrp->pci_sub_class;
	}
	
	if (PCIINFOCLASSES(baseclass, subclass)) {
	    num++;
	    xf86PciVideoInfo = xnfrealloc(xf86PciVideoInfo,
					  sizeof(pciVideoPtr) * (num + 1));
	    xf86PciVideoInfo[num] = NULL;
	    info = xf86PciVideoInfo[num - 1] = xnfalloc(sizeof(pciVideoRec));
	    info->validSize = FALSE;
	    info->vendor = pcrp->pci_vendor;
	    info->chipType = pcrp->pci_device;
	    info->chipRev = pcrp->pci_rev_id;
	    info->subsysVendor = pcrp->pci_subsys_vendor;
	    info->subsysCard = pcrp->pci_subsys_card;
	    info->bus = pcrp->busnum;
	    info->device = pcrp->devnum;
	    info->func = pcrp->funcnum;
	    info->class = baseclass;
	    info->subclass = pcrp->pci_sub_class;
	    info->interface = pcrp->pci_prog_if;
	    info->biosBase = PCIGETROM(pcrp->pci_baserom);
	    info->biosSize = pciGetBaseSize(pcrp->tag, 6, TRUE, NULL);
	    info->thisCard = pcrp;
	    info->validate = FALSE;
#ifdef INCLUDE_XF86_NO_DOMAIN
	    if ((PCISHAREDIOCLASSES(baseclass, subclass))
		&& (pcrp->pci_command & PCI_CMD_IO_ENABLE) &&
		(pcrp->pci_prog_if == 0)) {

		/*
		 * Attempt to ensure that VGA is actually routed to this
		 * adapter on entry.  This needs to be fixed when we finally
		 * grok host bridges (and multiple bus trees).
		 */
		j = info->bus;
		while (TRUE) {
		    PciBusPtr pBus = xf86PciBus;
		    while (pBus && j != pBus->secondary)
			pBus = pBus->next;
		    if (!pBus || !(pBus->brcontrol & PCI_PCI_BRIDGE_VGA_EN))
			break;
		    if (j == pBus->primary) {
			if (primaryBus.type == BUS_NONE) {
			    /* assumption: primary adapter is always VGA */
			    primaryBus.type = BUS_PCI;
			    primaryBus.id.pci.bus = pcrp->busnum;
			    primaryBus.id.pci.device = pcrp->devnum;
			    primaryBus.id.pci.func = pcrp->funcnum;
			} else if (primaryBus.type < BUS_last) {
			    xf86Msg(X_NOTICE,
				    "More than one primary device found\n");
			    primaryBus.type ^= (BusType)(-1);
			}
			break;
		    }
		    j = pBus->primary;
		}
	    }
#endif
	    
	    for (j = 0; j < 6; j++) {
		info->memBase[j] = 0;
		info->ioBase[j] = 0;
		if (PCINONSYSTEMCLASSES(baseclass, subclass)) {
		    info->size[j] =
			pciGetBaseSize(pcrp->tag, j, TRUE, &info->validSize);
		    pcrp->minBasesize = info->validSize;
		} else {
		    info->size[j] = pcrp->basesize[j];
		    info->validSize = pcrp->minBasesize;
		}
		info->type[j] = 0;
	    }

	    if (PCINONSYSTEMCLASSES(baseclass, subclass)) {
		/*
		 * Check of a PCI base is unassigned. If so
		 * attempt to fix it. Validation will determine
		 * if the value was correct later on.
		 */
		CARD32 *base = &pcrp->pci_base0;

		for (j = 0; j < 6; j++) {
		    if (!PCI_MAP_IS64BITMEM(base[j])) {
			if (info->size[j] && IsBaseUnassigned(base[j])) 
			    base[j] = pciCheckForBrokenBase(pcrp->tag, j);
		    } else {
			if (j == 5) /* bail out */
			    break;
			if (info->size[j]
			    && IsBaseUnassigned64(base[j],base[j+1])) {
			    base[j] = pciCheckForBrokenBase(pcrp->tag, j);
			    j++;
			    base[j] = pciCheckForBrokenBase(pcrp->tag, j);
			}
		    }
		}
	    }
	    
	    /*
	     * 64-bit base addresses are checked for and avoided on 32-bit
	     * platforms.
	     */
	    for (j = 0; j < 6; ++j) {
		CARD32  bar = (&pcrp->pci_base0)[j];

		if (bar != 0) {
		    if (bar & PCI_MAP_IO) {
			info->ioBase[j] = (memType)PCIGETIO(bar);
			info->type[j] = bar & PCI_MAP_IO_ATTR_MASK;
		    } else {
			info->type[j] = bar & PCI_MAP_MEMORY_ATTR_MASK;
			info->memBase[j] = (memType)PCIGETMEMORY(bar);
			if (PCI_MAP_IS64BITMEM(bar)) {
			    if (j == 5) {
				xf86MsgVerb(X_WARNING, 0,
				    "****BAR5 specified as 64-bit wide, "
				    "which is not possible. "
				    "Ignoring BAR5.****\n");
				info->memBase[j] = 0;
			    } else {
				CARD32  bar_hi = PCIGETMEMORY64HIGH((&pcrp->pci_base0)[j]);
#if defined(LONG64) || defined(WORD64)
				    /* 64 bit architecture */
				    info->memBase[j] |=
					(memType)bar_hi << 32;
#else
				    if (bar_hi != 0)
					info->memBase[j] = 0;
#endif
				    ++j;    /* Step over the next BAR */
			    }
			}
		    }
		}
	    }
	    info->listed_class = pcrp->listed_class;
	}
	i++;
    }

    /* If we haven't found a primary device try a different heuristic */
    if (primaryBus.type == BUS_NONE && num) {
	for (i = 0;  i < num;  i++) {
	    info = xf86PciVideoInfo[i];
	    pcrp = info->thisCard;
	    
	    if ((pcrp->pci_command & PCI_CMD_MEM_ENABLE) &&
		(num == 1 ||
		 ((info->class == PCI_CLASS_DISPLAY) &&
		  (info->subclass == PCI_SUBCLASS_DISPLAY_VGA)))) {
		if (primaryBus.type == BUS_NONE) {
		    primaryBus.type = BUS_PCI;
		    primaryBus.id.pci.bus = pcrp->busnum;
		    primaryBus.id.pci.device = pcrp->devnum;
		    primaryBus.id.pci.func = pcrp->funcnum;
		} else {
		    xf86Msg(X_NOTICE,
			    "More than one possible primary device found\n");
		    primaryBus.type ^= (BusType)(-1);
		}
	    }
	}
    }
    
    /* Print a summary of the video devices found */
    for (k = 0; k < num; k++) {
	const char *vendorname = NULL, *chipname = NULL;
	const char *prim = " ";
	char busnum[8];
	Bool memdone = FALSE, iodone = FALSE;

	i = 0; 
	info = xf86PciVideoInfo[k];
	xf86FormatPciBusNumber(info->bus, busnum);
	xf86FindPciNamesByDevice(info->vendor, info->chipType,
				 NOVENDOR, NOSUBSYS,
				 &vendorname, &chipname, NULL, NULL);
	if ((!vendorname || !chipname) &&
	    !PCIALWAYSPRINTCLASSES(info->class, info->subclass))
	    continue;
	if (xf86IsPrimaryPci(info))
	    prim = "*";

	xf86Msg(X_PROBED, "PCI:%s(%s:%d:%d) ", prim, busnum, info->device,
		info->func);
	if (vendorname)
	    xf86ErrorF("%s ", vendorname);
	else
	    xf86ErrorF("unknown vendor (0x%04x) ", info->vendor);
	if (chipname)
	    xf86ErrorF("%s ", chipname);
	else
	    xf86ErrorF("unknown chipset (0x%04x) ", info->chipType);
	xf86ErrorF("rev %d", info->chipRev);
	for (i = 0; i < 6; i++) {
	    if (info->memBase[i] &&
		(info->memBase[i] < (memType)(-1 << info->size[i]))) {
		if (!memdone) {
		    xf86ErrorF(", Mem @ ");
		    memdone = TRUE;
		} else
		    xf86ErrorF(", ");
		xf86ErrorF("0x%08lx/%d", info->memBase[i], info->size[i]);
	    }
	}
	for (i = 0; i < 6; i++) {
	    if (info->ioBase[i] &&
		(info->ioBase[i] < (memType)(-1 << info->size[i]))) {
		if (!iodone) {
		    xf86ErrorF(", I/O @ ");
		    iodone = TRUE;
		} else
		    xf86ErrorF(", ");
		xf86ErrorF("0x%04lx/%d", info->ioBase[i], info->size[i]);
	    }
	}
	if (info->biosBase &&
	    (info->biosBase < (memType)(-1 << info->biosSize)))
	    xf86ErrorF(", BIOS @ 0x%08lx/%d", info->biosBase, info->biosSize);
	xf86ErrorF("\n");
    }
}

/*
 * fixPciSizeInfo() -- fix pci size info by testing it destructively
 * (if not already done), fix pciVideoInfo and entry in the resource
 * list.
 */
/*
 * Note: once we have OS support to read the sizes GetBaseSize() will
 * have to be wrapped by the OS layer. fixPciSizeInfo() should also
 * be wrapped by the OS layer to do nothing if the size is always
 * returned correctly by GetBaseSize(). It should however set validate
 * in pciVideoRec if validation is required. ValidatePci() also needs
 * to be wrapped by the OS layer. This may do nothing if the OS has
 * already taken care of validation. fixPciResource() may be moved to
 * OS layer with minimal changes. Once the wrapping layer is in place
 * the common level and drivers should not reference these functions
 * directly but thru the OS layer.
 */

static void
fixPciSizeInfo(int entityIndex)
{
    pciVideoPtr pvp;
    resPtr pAcc;
    PCITAG tag;
    int j;
    
    if (! (pvp = xf86GetPciInfoForEntity(entityIndex))) return;
    if (pvp->validSize) return;

    tag = pciTag(pvp->bus,pvp->device,pvp->func);
    
    for (j = 0; j < 6; j++) {
	pAcc = Acc;
	if (pvp->memBase[j]) 
	    while (pAcc) {
		if (((pAcc->res_type & (ResPhysMask | ResBlock))
		     == (ResMem | ResBlock))
		    && (pAcc->block_begin == B2M(TAG(pvp),pvp->memBase[j])) 
		    && (pAcc->block_end == B2M(TAG(pvp),pvp->memBase[j]
		    + SIZE(pvp->size[j])))) break;
		pAcc = pAcc->next;
	    }
	else if (pvp->ioBase[j])
	    while (pAcc) {
		if (((pAcc->res_type & (ResPhysMask | ResBlock)) ==
		     (ResIo | ResBlock))
		    && (pAcc->block_begin == B2I(TAG(pvp),pvp->ioBase[j]))
		    && (pAcc->block_end == B2I(TAG(pvp),pvp->ioBase[j]
		    + SIZE(pvp->size[j])))) break;
		pAcc = pAcc->next;
	    }
	else continue;
	pvp->size[j]  = pciGetBaseSize(tag, j, TRUE, &pvp->validSize);
	if (pAcc) {
	    pAcc->block_end = pvp->memBase[j] ?
		B2M(TAG(pvp),pvp->memBase[j] + SIZE(pvp->size[j]))
		: B2I(TAG(pvp),pvp->ioBase[j] + SIZE(pvp->size[j]));
	    pAcc->res_type &= ~ResEstimated;
	    pAcc->res_type |= ResBios;
	}
    }
    if (pvp->biosBase) {
	pAcc = Acc;
	while (pAcc) {
	    if (((pAcc->res_type & (ResPhysMask | ResBlock)) ==
		 (ResMem | ResBlock))
		&& (pAcc->block_begin == B2M(TAG(pvp),pvp->biosBase))
		    && (pAcc->block_end == B2M(TAG(pvp),pvp->biosBase
		    + SIZE(pvp->biosSize)))) break;
	    pAcc = pAcc->next;
	}
	pvp->biosSize = pciGetBaseSize(tag, 6, TRUE, &pvp->validSize);
	if (pAcc) {
	    pAcc->block_end = B2M(TAG(pvp),pvp->biosBase+SIZE(pvp->biosSize));
	    pAcc->res_type &= ~ResEstimated;
	    pAcc->res_type |= ResBios;
	}
    }
}

/*
 * IO enable/disable related routines for PCI
 */
#define pArg ((pciArg*)arg)
#define SETBITS PCI_CMD_IO_ENABLE
static void
pciIoAccessEnable(void* arg)
{
#ifdef DEBUG
    ErrorF("pciIoAccessEnable: 0x%05lx\n", *(PCITAG *)arg);
#endif
    pArg->ctrl |= SETBITS | PCI_CMD_MASTER_ENABLE;
    pciWriteLong(pArg->tag, PCI_CMD_STAT_REG, pArg->ctrl);
}

static void
pciIoAccessDisable(void* arg)
{
#ifdef DEBUG
    ErrorF("pciIoAccessDisable: 0x%05lx\n", *(PCITAG *)arg);
#endif
    pArg->ctrl &= ~SETBITS;
    pciWriteLong(pArg->tag, PCI_CMD_STAT_REG, pArg->ctrl);
}

#undef SETBITS
#define SETBITS (PCI_CMD_IO_ENABLE | PCI_CMD_MEM_ENABLE)
static void
pciIo_MemAccessEnable(void* arg)
{
#ifdef DEBUG
    ErrorF("pciIo_MemAccessEnable: 0x%05lx\n", *(PCITAG *)arg);
#endif
    pArg->ctrl |= SETBITS | PCI_CMD_MASTER_ENABLE;
    pciWriteLong(pArg->tag, PCI_CMD_STAT_REG, pArg->ctrl);
}

static void
pciIo_MemAccessDisable(void* arg)
{
#ifdef DEBUG
    ErrorF("pciIo_MemAccessDisable: 0x%05lx\n", *(PCITAG *)arg);
#endif
    pArg->ctrl &= ~SETBITS;
    pciWriteLong(pArg->tag, PCI_CMD_STAT_REG, pArg->ctrl);
}

#undef SETBITS
#define SETBITS (PCI_CMD_MEM_ENABLE)
static void
pciMemAccessEnable(void* arg)
{
#ifdef DEBUG
    ErrorF("pciMemAccessEnable: 0x%05lx\n", *(PCITAG *)arg);
#endif
    pArg->ctrl |= SETBITS | PCI_CMD_MASTER_ENABLE;
    pciWriteLong(pArg->tag, PCI_CMD_STAT_REG, pArg->ctrl);
}

static void
pciMemAccessDisable(void* arg)
{
#ifdef DEBUG
    ErrorF("pciMemAccessDisable: 0x%05lx\n", *(PCITAG *)arg);
#endif
    pArg->ctrl &= ~SETBITS;
    pciWriteLong(pArg->tag, PCI_CMD_STAT_REG, pArg->ctrl);
}
#undef SETBITS
#undef pArg


/* move to OS layer */
#define MASKBITS (PCI_PCI_BRIDGE_VGA_EN | PCI_PCI_BRIDGE_MASTER_ABORT_EN)
static void
pciBusAccessEnable(BusAccPtr ptr)
{
    PCITAG tag = ptr->busdep.pci.acc;
    CARD16 ctrl;

#ifdef DEBUG
    ErrorF("pciBusAccessEnable: bus=%d\n", ptr->busdep.pci.bus);
#endif
    ctrl = pciReadWord(tag, PCI_PCI_BRIDGE_CONTROL_REG);
    if ((ctrl & MASKBITS) != PCI_PCI_BRIDGE_VGA_EN) {
	ctrl = (ctrl | PCI_PCI_BRIDGE_VGA_EN) &
	    ~(PCI_PCI_BRIDGE_MASTER_ABORT_EN | PCI_PCI_BRIDGE_SECONDARY_RESET);
	pciWriteWord(tag, PCI_PCI_BRIDGE_CONTROL_REG, ctrl);
    }
}

/* move to OS layer */
static void
pciBusAccessDisable(BusAccPtr ptr)
{
    PCITAG tag = ptr->busdep.pci.acc;
    CARD16 ctrl;

#ifdef DEBUG
    ErrorF("pciBusAccessDisable: bus=%d\n", ptr->busdep.pci.bus);
#endif
    ctrl = pciReadWord(tag, PCI_PCI_BRIDGE_CONTROL_REG);
    if (ctrl & MASKBITS) {
	ctrl &= ~(MASKBITS | PCI_PCI_BRIDGE_SECONDARY_RESET);
	pciWriteWord(tag, PCI_PCI_BRIDGE_CONTROL_REG, ctrl);
    }
}
#undef MASKBITS

/* move to OS layer */
static void
pciDrvBusAccessEnable(BusAccPtr ptr)
{
    int bus = ptr->busdep.pci.bus;

#ifdef DEBUG
    ErrorF("pciDrvBusAccessEnable: bus=%d\n", bus);
#endif
    (*pciBusInfo[bus]->funcs->pciControlBridge)(bus,
						PCI_PCI_BRIDGE_VGA_EN,
						PCI_PCI_BRIDGE_VGA_EN);
}

/* move to OS layer */
static void
pciDrvBusAccessDisable(BusAccPtr ptr)
{
    int bus = ptr->busdep.pci.bus;

#ifdef DEBUG
    ErrorF("pciDrvBusAccessDisable: bus=%d\n", bus);
#endif
    (*pciBusInfo[bus]->funcs->pciControlBridge)(bus,
						PCI_PCI_BRIDGE_VGA_EN, 0);
}


static void
pciSetBusAccess(BusAccPtr ptr)
{
#ifdef DEBUG
    ErrorF("pciSetBusAccess: route VGA to bus %d\n", ptr->busdep.pci.bus);
#endif

    if (!ptr->primary && !ptr->current)
	return;
    
    if (ptr->current && ptr->current->disable_f)
	(*ptr->current->disable_f)(ptr->current);
    ptr->current = NULL;
    
    /* walk down */
    while (ptr->primary) {	/* No enable for root bus */
	if (ptr != ptr->primary->current) {
	    if (ptr->primary->current && ptr->primary->current->disable_f)
		(*ptr->primary->current->disable_f)(ptr->primary->current);
	    if (ptr->enable_f)
		(*ptr->enable_f)(ptr);
	    ptr->primary->current = ptr;
	}
	ptr = ptr->primary;
    }
}

/* move to OS layer */
static void
savePciState(PCITAG tag, pciSavePtr ptr)
{
    int i;
     
    ptr->command = pciReadLong(tag, PCI_CMD_STAT_REG);
    for (i=0; i < 6; i++) 
        ptr->base[i] = pciReadLong(tag, PCI_CMD_BASE_REG + i*4);
    ptr->biosBase = pciReadLong(tag, PCI_CMD_BIOS_REG);
}

/* move to OS layer */
static void
restorePciState(PCITAG tag, pciSavePtr ptr)
{
    int i;
    
    /* disable card before setting anything */
    pciSetBitsLong(tag, PCI_CMD_STAT_REG,
		   PCI_CMD_MEM_ENABLE | PCI_CMD_IO_ENABLE , 0);
    pciWriteLong(tag,PCI_CMD_BIOS_REG, ptr->biosBase);
    for (i=0; i<6; i++)
        pciWriteLong(tag, PCI_CMD_BASE_REG + i*4, ptr->base[i]);        
    pciWriteLong(tag, PCI_CMD_STAT_REG, ptr->command);
}

/* move to OS layer */
static void
savePciBusState(BusAccPtr ptr)
{
    PCITAG tag = ptr->busdep.pci.acc;

    ptr->busdep.pci.save.control =
	pciReadWord(tag, PCI_PCI_BRIDGE_CONTROL_REG) &
	~PCI_PCI_BRIDGE_SECONDARY_RESET;
    /* Allow master aborts to complete normally on non-root buses */
    if (ptr->busdep.pci.save.control & PCI_PCI_BRIDGE_MASTER_ABORT_EN)
	pciWriteWord(tag, PCI_PCI_BRIDGE_CONTROL_REG,
	    ptr->busdep.pci.save.control & ~PCI_PCI_BRIDGE_MASTER_ABORT_EN);
}

/* move to OS layer */
#define MASKBITS (PCI_PCI_BRIDGE_VGA_EN | PCI_PCI_BRIDGE_MASTER_ABORT_EN)
static void
restorePciBusState(BusAccPtr ptr)
{
    PCITAG tag = ptr->busdep.pci.acc;
    CARD16 ctrl;

    /* Only restore the bits we've changed (and don't cause resets) */
    ctrl = pciReadWord(tag, PCI_PCI_BRIDGE_CONTROL_REG);
    if ((ctrl ^ ptr->busdep.pci.save.control) & MASKBITS) {
	ctrl &= ~(MASKBITS | PCI_PCI_BRIDGE_SECONDARY_RESET);
	ctrl |= ptr->busdep.pci.save.control & MASKBITS;
	pciWriteWord(tag, PCI_PCI_BRIDGE_CONTROL_REG, ctrl);
    }
}
#undef MASKBITS

/* move to OS layer */
static void
savePciDrvBusState(BusAccPtr ptr)
{
    int bus = ptr->busdep.pci.bus;

    ptr->busdep.pci.save.control =
	(*pciBusInfo[bus]->funcs->pciControlBridge)(bus, 0, 0);
    /* Allow master aborts to complete normally on this bus */
    (*pciBusInfo[bus]->funcs->pciControlBridge)(bus,
						PCI_PCI_BRIDGE_MASTER_ABORT_EN,
						0);
}

/* move to OS layer */
static void
restorePciDrvBusState(BusAccPtr ptr)
{
    int bus = ptr->busdep.pci.bus;

    (*pciBusInfo[bus]->funcs->pciControlBridge)(bus, (CARD16)(-1),
					        ptr->busdep.pci.save.control);
}


static void
disablePciBios(PCITAG tag)
{
    pciSetBitsLong(tag, PCI_CMD_BIOS_REG, PCI_CMD_BIOS_ENABLE, 0);
}

/* ????? */
static void
correctPciSize(memType base, memType oldsize, memType newsize,
	       unsigned long type)
{
    pciConfigPtr pcrp, *pcrpp;
    pciVideoPtr pvp, *pvpp;
    CARD32 *basep;
    int i;
    int old_bits = 0, new_bits = 0;

    if (oldsize + 1) while (oldsize & 1) {
	old_bits ++;
	oldsize >>= 1;
    }
    if (newsize + 1) while (newsize & 1) {
	new_bits ++;
	newsize >>= 1;
    }
    
    for (pcrpp = xf86PciInfo, pcrp = *pcrpp; pcrp; pcrp = *++(pcrpp)) {
	
	/* Only process devices with type 0 headers */
	if ((pcrp->pci_header_type & 0x7f) != 0)
	    continue;

	basep = &pcrp->pci_base0;
	for (i = 0; i < 6; i++) {
	    if (basep[i] && (pcrp->basesize[i] == old_bits)) {
		if ((((type & ResPhysMask) == ResIo) &&
		     PCI_MAP_IS_IO(basep[i]) &&
		     B2I(pcrp->tag,PCIGETIO(basep[i]) == base)) ||
		    (((type & ResPhysMask) == ResMem) &&
		     PCI_MAP_IS_MEM(basep[i]) &&
		     (((!PCI_MAP_IS64BITMEM(basep[i])) &&
		       (B2M(pcrp->tag,PCIGETMEMORY(basep[i])) == base))
#if defined(LONG64) || defined(WORD64)
		      ||
		      (B2M(pcrp->tag,PCIGETMEMORY64(basep[i])) == base)
#else
		      ||
		      (!basep[i+1]
		       && (B2M(pcrp->tag,PCIGETMEMORY(basep[i])) == base))
#endif 
		     ))) {
		    pcrp->basesize[i] = new_bits;
		    break;	/* to next device */
		}
	    }
	    if (PCI_MAP_IS64BITMEM(basep[i])) i++;
	}
    }

    if (xf86PciVideoInfo) {
	for (pvpp = xf86PciVideoInfo, pvp = *pvpp; pvp; pvp = *(++pvpp)) {

	    for (i = 0; i < 6; i++) {
		if (pvp->size[i] == old_bits) {
		    if ((((type & ResPhysMask) == ResIo) && pvp->ioBase[i]
			 && (B2I(TAG(pvp),pvp->ioBase[i]) == base)) || 
			(((type & ResPhysMask) == ResMem) && pvp->memBase[i] 
			  && (B2M(TAG(pvp),pvp->memBase[i]) == base))) {
			pvp->size[i] = new_bits;
			break;	/* to next device */
		    }
		}
	    }
	}
    }
}

/* ????? */
static void
removeOverlapsWithBridges(int busIndex, resPtr target)
{
    PciBusPtr pbp;
    resPtr tmp,bridgeRes = NULL;
    resRange range;

    if (!target)
	return;
    
    if (!ResCanOverlap(&target->val))
	return;

    range = target->val;
    
    for (pbp=xf86PciBus; pbp; pbp = pbp->next) {
	if (pbp->primary == busIndex) {
	    tmp = xf86DupResList(pbp->preferred_io);
	    bridgeRes = xf86JoinResLists(tmp,bridgeRes);
	    tmp = xf86DupResList(pbp->preferred_mem);
	    bridgeRes = xf86JoinResLists(tmp,bridgeRes);
	    tmp = xf86DupResList(pbp->preferred_pmem);
	    bridgeRes = xf86JoinResLists(tmp,bridgeRes);
	}
    }
    
    RemoveOverlaps(target, bridgeRes, TRUE, TRUE);
    if (range.rEnd > target->block_end) {
	correctPciSize(range.rBegin, range.rEnd - range.rBegin,
		       target->block_end - target->block_begin,
		       target->res_type);
	xf86MsgVerb(X_INFO, 3,
	    "PCI %s resource overlap reduced 0x%08lx from 0x%08lx to 0x%08lx\n",
	    ((target->res_type & ResPhysMask) == ResMem) ?  "Memory" : "I/O",
	    range.rBegin, range.rEnd, target->block_end);
    }
    xf86FreeResList(bridgeRes);
}
    
/* ????? */
static void
xf86GetPciRes(resPtr *activeRes, resPtr *inactiveRes)
{
    pciConfigPtr pcrp, *pcrpp;
    pciVideoPtr pvp, *pvpp;
    CARD32 *basep;
    int i;
    resPtr pRes, tmp;
    resRange range;
    long resMisc;

    if (activeRes)
	*activeRes = NULL;
    if (inactiveRes)
	*inactiveRes = NULL;

    if (!activeRes || !inactiveRes || !xf86PciInfo)
	return;

    if (xf86PciVideoInfo)
	for (pvpp = xf86PciVideoInfo, pvp = *pvpp; pvp; pvp = *(++pvpp)) {
	    resPtr *res;

	    if (PCINONSYSTEMCLASSES(pvp->class, pvp->subclass)) 
		resMisc = ResBios;
	    else 
		resMisc = 0;
	    
	    if (((pciConfigPtr)pvp->thisCard)->pci_command
		& (PCI_CMD_IO_ENABLE | PCI_CMD_MEM_ENABLE))
		res = activeRes;
	    else
		res = inactiveRes;
	    
	    if (!pvp->validSize)
		resMisc |= ResEstimated;
	    
	    for (i = 0; i < 6; i++) {
		if (pvp->ioBase[i] &&
		    (pvp->ioBase[i] < (memType)(-1 << pvp->size[i]))) {
		    PV_I_RANGE(range,pvp,i,ResExcIoBlock | resMisc);
		    tmp = xf86AddResToList(NULL, &range, -1);
		    removeOverlapsWithBridges(pvp->bus,tmp);
		    *res = xf86JoinResLists(tmp,*res);
		} else if (pvp->memBase[i] &&
		    (pvp->memBase[i] < (memType)(-1 << pvp->size[i]))) {
		    PV_M_RANGE(range, pvp,i, ResExcMemBlock | resMisc);
		    tmp = xf86AddResToList(NULL, &range, -1);
		    removeOverlapsWithBridges(pvp->bus,tmp);
		    *res = xf86JoinResLists(tmp,*res);
		}
	    }
	    /* FIXME!!!: Don't use BIOS resources for overlap
	     * checking but reserve them!
	     */
	    if (pvp->biosBase &&
		(pvp->biosBase < (memType)(-1 << pvp->biosSize))) {
		PV_B_RANGE(range, pvp, ResExcMemBlock | resMisc);
		tmp = xf86AddResToList(NULL, &range, -1);
		removeOverlapsWithBridges(pvp->bus,tmp);
		*res = xf86JoinResLists(tmp,*res);
	    }
	}

    for (pcrpp = xf86PciInfo, pcrp = *pcrpp; pcrp; pcrp = *++(pcrpp)) {
	resPtr *res;
	CARD8 baseclass, subclass;

	if (pcrp->listed_class & 0x0ffff) {
	    baseclass = pcrp->listed_class >> 8;
	    subclass = pcrp->listed_class;
	} else {
	    baseclass = pcrp->pci_base_class;
	    subclass = pcrp->pci_sub_class;
	}
	
	if (PCIINFOCLASSES(baseclass, subclass))
	    continue;
	
	/* Only process devices with type 0 headers */
	if ((pcrp->pci_header_type & 0x7f) != 0)
	    continue;

	if (!pcrp->minBasesize)
	    resMisc = ResEstimated;
	else
	    resMisc = 0;

	/*
	 * Allow resources allocated to host bridges to overlap.  Perhaps, this
	 * needs to be specific to AGP-capable chipsets.  AGP "memory"
	 * sometimes gets allocated within the range routed to the AGP bus.
	 */
	if ((baseclass == PCI_CLASS_BRIDGE) &&
	    (subclass == PCI_SUBCLASS_BRIDGE_HOST))
	    resMisc |= ResOverlap;
	
	basep = &pcrp->pci_base0;
	for (i = 0; i < 6; i++) {
	    if (basep[i]) {
	        if (PCI_MAP_IS_IO(basep[i])) {
		    if (pcrp->pci_command & PCI_CMD_IO_ENABLE)
			res = activeRes;
		    else
			res = inactiveRes;
		    P_I_RANGE(range, pcrp->tag, PCIGETIO(basep[i]),
			      pcrp->basesize[i], ResExcIoBlock | resMisc)
		} else if (!PCI_MAP_IS64BITMEM(basep[i])) {
		    if (pcrp->pci_command & PCI_CMD_MEM_ENABLE)
			res = activeRes;
		    else
			res = inactiveRes;
		    P_M_RANGE(range, pcrp->tag, PCIGETMEMORY(basep[i]),
			      pcrp->basesize[i], ResExcMemBlock | resMisc)
		} else {
		    i++;
#if defined(LONG64) || defined(WORD64)
		    P_M_RANGE(range,pcrp->tag,PCIGETMEMORY64(basep[i - 1]),
			      pcrp->basesize[i - 1], ResExcMemBlock | resMisc)
#else
		    if (basep[i])
		      continue;
		    P_M_RANGE(range, pcrp->tag, PCIGETMEMORY(basep[i - 1]),
			      pcrp->basesize[i - 1], ResExcMemBlock | resMisc)
#endif
		    if (pcrp->pci_command & PCI_CMD_MEM_ENABLE)
			res = activeRes;
		    else
			res = inactiveRes;
		}
		if (range.rBegin) { /* catch cases where PCI base is unset */
		    tmp = xf86AddResToList(NULL, &range, -1);
		    removeOverlapsWithBridges(pcrp->busnum,tmp);
		    *res = xf86JoinResLists(tmp,*res);
		}
	    }
	}

        /* Ignore disabled non-video ROMs */
	if ((pcrp->pci_command & PCI_CMD_MEM_ENABLE) &&
	    (pcrp->pci_baserom & PCI_MAP_ROM_DECODE_ENABLE)) {
	    P_M_RANGE(range,pcrp->tag,PCIGETROM(pcrp->pci_baserom),
		  pcrp->basesize[6], ResExcMemBlock | resMisc);
	    if (range.rBegin) {
		tmp = xf86AddResToList(NULL, &range, -1);
		removeOverlapsWithBridges(pcrp->busnum, tmp);
		*activeRes = xf86JoinResLists(tmp, *activeRes);
	    }
	}
    }

    if (*activeRes) {
	xf86MsgVerb(X_INFO, 3, "Active PCI resource ranges:\n");
	xf86PrintResList(3, *activeRes);
    }
    if (*inactiveRes) {
	xf86MsgVerb(X_INFO, 3, "Inactive PCI resource ranges:\n");
	xf86PrintResList(3, *inactiveRes);
    }

    /*
     * Adjust ranges based on the assumption that there are no real
     * overlaps in the PCI base allocations.  This assumption should be
     * reasonable in most cases.  It may be possible to refine the
     * approximated PCI base sizes by considering bus mapping information
     * from PCI-PCI bridges.
     */

    if (*activeRes) {
	/* Check for overlaps */
	for (pRes = *activeRes; pRes; pRes = pRes->next) {
	    if (ResCanOverlap(&pRes->val)) {
		range = pRes->val;

		RemoveOverlaps(pRes, *activeRes, TRUE, TRUE);
		RemoveOverlaps(pRes, *inactiveRes, TRUE, 
		    (xf86Info.estimateSizesAggressively > 0));
		
		if (range.rEnd > pRes->block_end) {
		    correctPciSize(range.rBegin, range.rEnd - range.rBegin,
				   pRes->block_end - pRes->block_begin,
				   pRes->res_type);
		    xf86MsgVerb(X_INFO, 3,
				"PCI %s resource overlap reduced 0x%08lx"
				" from 0x%08lx to 0x%08lx\n",
				((pRes->res_type & ResPhysMask) == ResMem) ?
				 "Memory" : "I/O",
				range.rBegin, range.rEnd, pRes->block_end);
		}
	    }
	}
	xf86MsgVerb(X_INFO, 3,
	    "Active PCI resource ranges after removing overlaps:\n");
	xf86PrintResList(3, *activeRes);
    }

    if (*inactiveRes) {
	/* Check for overlaps */
	for (pRes = *inactiveRes; pRes; pRes = pRes->next) {
	    if (ResCanOverlap(&pRes->val)) {
		range = pRes->val;

		RemoveOverlaps(pRes, *activeRes, TRUE,
		    (xf86Info.estimateSizesAggressively > 1));
		RemoveOverlaps(pRes, *inactiveRes, TRUE,
		    (xf86Info.estimateSizesAggressively > 1));
		
		if (range.rEnd > pRes->block_end) {
		    correctPciSize(range.rBegin, range.rEnd - range.rBegin,
				   pRes->block_end - pRes->block_begin,
				   pRes->res_type);
		    xf86MsgVerb(X_INFO, 3,
				"PCI %s resource overlap reduced 0x%08lx"
				" from 0x%08lx to 0x%08lx\n",
				((pRes->res_type & ResPhysMask) == ResMem) ?
				 "Memory" : "I/O",
				range.rBegin, range.rEnd, pRes->block_end);
		}
		
	    }
	}
	xf86MsgVerb(X_INFO, 3,
	    "Inactive PCI resource ranges after removing overlaps:\n");
	xf86PrintResList(3, *inactiveRes);
    }
}

resPtr
ResourceBrokerInitPci(resPtr *osRes)
{
    resPtr activeRes, inactiveRes;
    resPtr tmp;
    
    /* Get bus-specific system resources (PCI) */
    xf86GetPciRes(&activeRes, &inactiveRes);

    /*
     * Adjust OS-reported resource ranges based on the assumption that there
     * are no overlaps with the PCI base allocations.  This should be a good
     * assumption because writes to PCI address space won't be routed directly
     * to host memory.
     */

    for (tmp = *osRes; tmp; tmp = tmp->next) 
	RemoveOverlaps(tmp, activeRes, FALSE, TRUE);

    xf86MsgVerb(X_INFO, 3, "OS-reported resource ranges after removing"
		" overlaps with PCI:\n");
    xf86PrintResList(3, *osRes);

    pciAvoidRes = xf86AddRangesToList(pciAvoidRes,PciAvoid,-1);
    for (tmp = pciAvoidRes; tmp; tmp = tmp->next) 
	RemoveOverlaps(tmp, activeRes, FALSE, TRUE);
    tmp = xf86DupResList(*osRes);
    pciAvoidRes = xf86JoinResLists(pciAvoidRes,tmp);
    
    return (xf86JoinResLists(activeRes,inactiveRes));
}


/*
 * PCI Resource modification
 */
static Bool
fixPciResource(int prt, memType alignment, pciVideoPtr pvp, unsigned long type)
{
    int  res_n;
    memType *p_base;
    int *p_size;
    unsigned char p_type;
    resPtr AccTmp = NULL;
    resPtr orgAcc = NULL;
    resPtr *pAcc = &AccTmp;
    resPtr avoid = NULL;
    resRange range;
    resPtr resSize = NULL;
    resPtr w_tmp, w = NULL, w_2nd = NULL;
    PCITAG tag;
    PciBusPtr pbp = xf86PciBus;
    pciConfigPtr pcp;
    resPtr tmp;
    
    if (!pvp) return FALSE;
    tag = pciTag(pvp->bus,pvp->device,pvp->func);
    pcp = pvp->thisCard;

    type &= ResAccMask;
    if (!type) type = ResShared;
    if (prt < 6) {
	if (pvp->memBase[prt]) {
	    type |= ResMem;
	    res_n = prt;
	    p_base = &(pvp->memBase[res_n]);
	    p_size = &(pvp->size[res_n]);
	    p_type = pvp->type[res_n];
	    if (!PCI_MAP_IS64BITMEM(pvp->type[res_n])) {
	      PCI_M_RANGE(range,tag,0,0xffffffff,ResExcMemBlock);
	      resSize = xf86AddResToList(resSize,&range,-1);
	    }
	} else if (pvp->ioBase[prt]){
	    type |= ResIo;
	    res_n = prt;
	    p_base = &(pvp->ioBase[res_n]);
	    p_size = &(pvp->size[res_n]);
	    p_type = pvp->type[res_n];
	    PCI_I_RANGE(range, tag, 0, 0xffffffff, ResExcIoBlock);
	    resSize = xf86AddResToList(resSize, &range, -1);
	} else return FALSE;
    } else if (prt == 6) {
	type |= ResMem;
	res_n = 0xff;	/* special flag for bios rom */
	p_base = &(pvp->biosBase);
	p_size = &(pvp->biosSize);
	/* XXX This should also include the PCI_MAP_MEMORY_TYPE_MASK part */
	p_type = 0;
	PCI_M_RANGE(range,tag,0,0xffffffff,ResExcMemBlock);
	resSize = xf86AddResToList(resSize,&range,-1);
    } else return FALSE;

    if (! *p_base) return FALSE;
    
    type |= (range.type & ResDomain) | ResBlock;
    
    /* setup avoid: PciAvoid is bus range: convert later */
    avoid = xf86DupResList(pciAvoidRes);

    while (pbp) {
	if (pbp->secondary == pvp->bus) {
	    if ((type & ResPhysMask) == ResMem) {
		if (((p_type & PCI_MAP_MEMORY_CACHABLE)
#if 0 /*EE*/
		     || (res_n == 0xff)/* bios should also be prefetchable */
#endif
		     )) {
		    if (pbp->preferred_pmem)
			w = xf86FindIntersectOfLists(pbp->preferred_pmem,
						     ResRange);
		    else if (pbp->pmem)
			w = xf86FindIntersectOfLists(pbp->pmem,ResRange);
		    
		    if (pbp->preferred_mem) 
			w_2nd = xf86FindIntersectOfLists(pbp->preferred_mem,
							 ResRange);
		    else if (pbp->mem) 
			w_2nd = xf86FindIntersectOfLists(pbp->mem,
							 ResRange);
		} else {
		    if (pbp->preferred_mem)
			w = xf86FindIntersectOfLists(pbp->preferred_mem,
						     ResRange);
		    else if (pbp->mem)
			w = xf86FindIntersectOfLists(pbp->mem,ResRange);
		}
	    } else {
		if (pbp->preferred_io) 
		    w = xf86FindIntersectOfLists(pbp->preferred_io,ResRange);
		if (pbp->io) 
		    w = xf86FindIntersectOfLists(pbp->io,ResRange);
	    }
	} else if (pbp->primary == pvp->bus) {
	    if ((type & ResPhysMask) == ResMem) {
		tmp = xf86DupResList(pbp->preferred_pmem);
		avoid = xf86JoinResLists(avoid, tmp);
		tmp = xf86DupResList(pbp->preferred_mem);
		avoid = xf86JoinResLists(avoid, tmp);
	    } else {
		tmp = xf86DupResList(pbp->preferred_io);
		avoid = xf86JoinResLists(avoid, tmp);
	    }
	}	
	pbp = pbp->next;
    }
    
    /* convert bus based entries in avoid list to host base */
    pciConvertListToHost(pvp->bus,pvp->device,pvp->func, avoid);
    
    if (!w)
	w = xf86DupResList(ResRange);
    xf86MsgVerb(X_INFO, 3, "window:\n");
    xf86PrintResList(3, w);
    xf86MsgVerb(X_INFO, 3, "resSize:\n");
    xf86PrintResList(3, resSize);
    
    if (resSize) {
	w_tmp = w;
	w = xf86FindIntersectOfLists(w,resSize);
	xf86FreeResList(w_tmp);
	if (w_2nd) {
	    w_tmp = w_2nd;
	    w_2nd = xf86FindIntersectOfLists(w_2nd,resSize);
	    xf86FreeResList(w_tmp);
	}
	xf86FreeResList(resSize);
    }
    xf86MsgVerb(X_INFO, 3, "window fixed:\n");
    xf86PrintResList(3, w);

    if (!alignment)
	alignment = (1 << (*p_size)) - 1;
    
    /* Access list holds bios resources -- remove this one */
#ifdef NOTYET
    AccTmp = xf86DupResList(Acc);
    while ((*pAcc)) {
	if ((((*pAcc)->res_type & (type & ~ResAccMask))
	     == (type & ~ResAccMask))
	    && ((*pAcc)->block_begin == (B2H(tag,(*p_base),type)))
	    && ((*pAcc)->block_end == (B2H(tag,
					   (*p_base)+SIZE(*p_size),type)))) {
	    resPtr acc_tmp = (*pAcc)->next;
	    xfree((*pAcc));
	    (*pAcc) = acc_tmp;
	    break;
	} else
	    pAcc = &((*pAcc)->next);
    }
    /* check if we really need to fix anything */
    P_X_RANGE(range,tag,(*p_base),(*p_base) + SIZE((*p_size)),type);
    if (!ChkConflict(&range,avoid,SETUP)
	&& !ChkConflict(&range,AccTmp,SETUP)
	&& ((B2H(tag,(*p_base),type) & PCI_SIZE(type,tag,alignment)
	     == range->block_begin)
	&& ((xf86IsSubsetOf(range,w)
	    || (w_2nd && xf86IsSubsetOf(range,w_2n))))) {
#ifdef DEBUG
	    ErrorF("nothing to fix\n");
#endif
	xf86FreeResList(AccTmp);
	xf86FreeResList(w);
	xf86FreeResList(w_2nd);
	xf86FreeResList(avoid);
	return TRUE;
    }
#ifdef DEBUG
	ErrorF("removing old resource\n");
#endif
    orgAcc = Acc;
    Acc = AccTmp;
#else
    orgAcc = xf86DupResList(Acc);
    pAcc = &Acc;
    while (*pAcc) {
	if ((((*pAcc)->res_type & (ResTypeMask|ResExtMask)) ==
	     (type & ~ResAccMask))
	    && ((*pAcc)->block_begin == B2H(tag,(*p_base),type))
	    && ((*pAcc)->block_end == B2H(tag,(*p_base) + SIZE(*p_size),
					  type))) {
#ifdef DEBUG
	    ErrorF("removing old resource\n");
#endif
	    tmp = *pAcc;
	    *pAcc = (*pAcc)->next;
	    tmp->next = NULL;
	    xf86FreeResList(tmp);
	    break;
	} else
	    pAcc = &((*pAcc)->next);
    }
#endif
    
#ifdef DEBUG
    ErrorF("base: 0x%lx alignment: 0x%lx host alignment: 0x%lx size[bit]: 0x%x\n",
	   (*p_base),alignment,PCI_SIZE(type,tag,alignment),(*p_size));
    xf86MsgVerb(X_INFO, 3, "window:\n");
    xf86PrintResList(3, w);
    if (w_2nd)
	xf86MsgVerb(X_INFO, 3, "2nd window:\n");
    xf86PrintResList(3, w_2nd);
    xf86ErrorFVerb(3,"avoid:\n");
    xf86PrintResList(3,avoid);
#endif
    w_tmp = w;
    while (w) {
	if ((type & ResTypeMask) == (w->res_type & ResTypeMask)) {
#ifdef DEBUG
	    ErrorF("block_begin: 0x%lx block_end: 0x%lx\n",w->block_begin,
		   w->block_end);
#endif
	    range = xf86GetBlock(type,PCI_SIZE(type,tag,alignment + 1),
				 w->block_begin, w->block_end,
				 PCI_SIZE(type,tag,alignment),avoid);
	    if (range.type != ResEnd)
		break;
	}
	w = w->next;
    }
    xf86FreeResList(w_tmp);
    /* if unsuccessful and memory prefetchable try non-prefetchable */
    if (range.type == ResEnd && w_2nd) {
	w_tmp = w_2nd;
	while (w_2nd) {
	    if ((type & ResTypeMask) == (w_2nd->res_type & ResTypeMask)) {
#ifdef DEBUG
	    ErrorF("block_begin: 0x%lx block_end: 0x%lx\n",w_2nd->block_begin,
		   w_2nd->block_end);
#endif
	    range = xf86GetBlock(type,PCI_SIZE(type,tag,alignment + 1),
				 w_2nd->block_begin, w_2nd->block_end,
				 PCI_SIZE(type,tag,alignment),avoid);
		if (range.type != ResEnd)
		    break;
	    }
	w_2nd = w_2nd->next;
	}
	xf86FreeResList(w_tmp);
    }
    xf86FreeResList(avoid);

    if (range.type == ResEnd) {
	xf86MsgVerb(X_ERROR,3,"Cannot find a replacement memory range\n");
	xf86FreeResList(Acc);
	Acc = orgAcc;
	return FALSE;
    }
    xf86FreeResList(orgAcc);
#ifdef DEBUG
    ErrorF("begin: 0x%lx, end: 0x%lx\n",range.a,range.b);
#endif
    
    (*p_size) = 0;
    while (alignment >> (*p_size))
	(*p_size)++;
    (*p_base) = H2B(tag,range.rBegin,type);
#ifdef DEBUG
    ErrorF("New PCI res %i base: 0x%lx, size: 0x%lx, type %s\n",
	   res_n,(*p_base),(1 << (*p_size)),
	   ((type & ResPhysMask) == ResMem) ? "Mem" : "Io");
#endif
    if (res_n != 0xff) {
	if ((type & ResPhysMask) == ResMem)
	    pvp->memBase[prt] = range.rBegin;
	else
	    pvp->ioBase[prt] = range.rBegin;
	((CARD32 *)(&(pcp->pci_base0)))[res_n] =
	    (CARD32)(*p_base) | (CARD32)(p_type);
	pciWriteLong(tag, PCI_CMD_BASE_REG + res_n * sizeof(CARD32),
		     ((CARD32 *)(&(pcp->pci_base0)))[res_n]);
	if (PCI_MAP_IS64BITMEM(p_type)) {
#if defined(LONG64) || defined(WORD64)
	    ((CARD32 *)(&(pcp->pci_base0)))[res_n + 1] =
		(CARD32)(*p_base >> 32);
	    pciWriteLong(tag, PCI_CMD_BASE_REG + (res_n + 1) * sizeof(CARD32),
	    		 ((CARD32 *)(&(pcp->pci_base0)))[res_n + 1]);
#else
	    ((CARD32 *)(&(pcp->pci_base0)))[res_n + 1] = 0;
	    pciWriteLong(tag, PCI_CMD_BASE_REG + (res_n + 1) * sizeof(CARD32),
			 0);
#endif
	}
    } else {
	pvp->biosBase = range.rBegin;
	pcp->pci_baserom = (pciReadLong(tag,PCI_CMD_BIOS_REG) & 0x01) |
	    (CARD32)(*p_base);
	pciWriteLong(tag, PCI_CMD_BIOS_REG, pcp->pci_baserom);
    }
    /* @@@ fake BIOS allocated resource */
    range.type |= ResBios;
    Acc = xf86AddResToList(Acc, &range,-1);
    
    return TRUE;
    
}

Bool
xf86FixPciResource(int entityIndex, int prt, memType alignment,
		   unsigned long type)
{
    pciVideoPtr pvp = xf86GetPciInfoForEntity(entityIndex);
    return fixPciResource(prt, alignment, pvp, type);
}

resPtr
xf86ReallocatePciResources(int entityIndex, resPtr pRes)
{
    pciVideoPtr pvp = xf86GetPciInfoForEntity(entityIndex);
    resPtr pBad = NULL,pResTmp;
    unsigned int prt = 0;
    int i;
    
    if (!pvp) return pRes;

    while (pRes) {
	switch (pRes->res_type & ResPhysMask) {
	case ResMem:
	    if (pRes->block_begin == B2M(TAG(pvp),pvp->biosBase) &&
		pRes->block_end == B2M(TAG(pvp),pvp->biosBase
				       + SIZE(pvp->biosSize)))
		prt = 6;
	    else for (i = 0 ; i < 6; i++) 
		if ((pRes->block_begin == B2M(TAG(pvp),pvp->memBase[i]))
		    && (pRes->block_end == B2M(TAG(pvp),pvp->memBase[i]
					      + SIZE(pvp->size[i])))) {
		    prt = i;
		    break;
		}
	    break;
	case ResIo:
	    for (i = 0 ; i < 6; i++) 
		if (pRes->block_begin == B2I(TAG(pvp),pvp->ioBase[i])
		    && pRes->block_end == B2I(TAG(pvp),pvp->ioBase[i]
		    + SIZE(pvp->size[i]))) {
		    prt = i;
		    break;
		}
	    break;
	}

	if (!prt) return pRes;

	pResTmp = pRes->next;
	if (! fixPciResource(prt, 0, pvp, pRes->res_type)) {
	    pRes->next = pBad;
	    pBad = pRes;
	} else
	    xfree(pRes);
	
	pRes = pResTmp;
    }
    return pBad;
}

/*
 * BIOS releated
 */
memType
getValidBIOSBase(PCITAG tag, int num)
{
    pciVideoPtr pvp = NULL;
    PciBusPtr pbp;
    resPtr m = NULL;
    resPtr tmp, avoid, mem = NULL;
    resRange range;
    memType ret;
    int n = 0;
    int i;
    CARD32 biosSize, alignment;

    if (!xf86PciVideoInfo) return 0;
    
    while ((pvp = xf86PciVideoInfo[n++])) {
	if (pciTag(pvp->bus,pvp->device,pvp->func) == tag)
	    break;
    }
    if (!pvp) return 0;

    biosSize = pvp->biosSize;
    alignment = (1 << biosSize) - 1;
    if (biosSize > 24)
	biosSize = 24;

    switch ((romBaseSource)num) {
    case ROM_BASE_PRESET:
	return 0; /* This should not happen */
    case ROM_BASE_BIOS:
	/* In some cases the BIOS base register contains the size mask */
	if ((memType)(-1 << biosSize) == PCIGETROM(pvp->biosBase))
	    return 0;
	/* Make sure we don't conflict with our own mem resources */
	for (i = 0; i < 6; i++) {
	    if (!pvp->memBase[i])
		continue;
	    P_M_RANGE(range,TAG(pvp),pvp->memBase[i],pvp->size[i],
		      ResExcMemBlock);
	    mem = xf86AddResToList(mem,&range,-1);
	}
	P_M_RANGE(range, TAG(pvp),pvp->biosBase,biosSize,ResExcMemBlock);
	ret = pvp->biosBase;
	break;
    case ROM_BASE_MEM0:
    case ROM_BASE_MEM1:
    case ROM_BASE_MEM2:
    case ROM_BASE_MEM3:
    case ROM_BASE_MEM4:
    case ROM_BASE_MEM5:
	if (!pvp->memBase[num] || (pvp->size[num] < biosSize))
	    return 0;
	P_M_RANGE(range, TAG(pvp),pvp->memBase[num],biosSize,
		  ResExcMemBlock);
	ret = pvp->memBase[num];
	break;
    case ROM_BASE_FIND:
	ret = 0;
	break;
    default:
	return 0; /* This should not happen */
    }

    /* Now find the ranges for validation */
    avoid = xf86DupResList(pciAvoidRes);
    pbp = xf86PciBus;
    while (pbp) {
	if (pbp->secondary == pvp->bus) {
	    if (pbp->preferred_pmem)
		tmp = xf86DupResList(pbp->preferred_pmem);
	    else
		tmp = xf86DupResList(pbp->pmem);
	    m = xf86JoinResLists(m,tmp);
	    if (pbp->preferred_mem)
		tmp = xf86DupResList(pbp->preferred_mem);
	    else
		tmp = xf86DupResList(pbp->mem);
	    m = xf86JoinResLists(m,tmp);
	    tmp = m;
	    while (tmp) {
		tmp->block_end = min(tmp->block_end,PCI_MEM32_LENGTH_MAX);
		tmp = tmp->next;
	    }
	} else if ((pbp->primary == pvp->bus) &&
		   (pbp->secondary >= 0) &&
		   (pbp->primary != pbp->secondary)) {
	    tmp = xf86DupResList(pbp->preferred_pmem);
	    avoid = xf86JoinResLists(avoid, tmp);
	    tmp = xf86DupResList(pbp->pmem);
	    avoid = xf86JoinResLists(avoid, tmp);
	    tmp = xf86DupResList(pbp->preferred_mem);
	    avoid = xf86JoinResLists(avoid, tmp);
	    tmp = xf86DupResList(pbp->mem);
	    avoid = xf86JoinResLists(avoid, tmp);
	}
	pbp = pbp->next;
    }	
    pciConvertListToHost(pvp->bus,pvp->device,pvp->func, avoid);
    if (mem)
	pciConvertListToHost(pvp->bus,pvp->device,pvp->func, mem);

    if (!ret) {
	/* Return a possible window */
	while (m) {
	    range = xf86GetBlock(RANGE_TYPE(ResExcMemBlock, xf86GetPciDomain(tag)),
				 PCI_SIZE(ResMem, TAG(pvp), 1 << biosSize),
				 m->block_begin, m->block_end,
				 PCI_SIZE(ResMem, TAG(pvp), alignment), 
				 avoid);
	    if (range.type != ResEnd) {
		ret =  M2B(TAG(pvp), range.rBase);
		break;
	    }
	    m = m->next;
	}
    } else {
#if !defined(__ia64__) /* on ia64, trust the kernel, don't look for overlaps */
	if (!xf86IsSubsetOf(range, m) || 
	    ChkConflict(&range, avoid, SETUP) 
	    || (mem && ChkConflict(&range, mem, SETUP))) 
	    ret = 0;
#endif 
    }

    xf86FreeResList(avoid);
    xf86FreeResList(m);
    return ret;
}

/*
 * xf86Bus.c interface
 */

void
xf86PciProbe(void)
{
    /*
     * Initialise the pcidata entry points.
     */
#ifdef XFree86LOADER
    xf86SetupPciIds = (ScanPciSetupProcPtr)LoaderSymbol("ScanPciSetupPciIds");
    xf86ClosePciIds = (ScanPciCloseProcPtr)LoaderSymbol("ScanPciClosePciIds");
    xf86FindPciNamesByDevice =
	(ScanPciFindByDeviceProcPtr)LoaderSymbol("ScanPciFindPciNamesByDevice");
    xf86FindPciNamesBySubsys =
	(ScanPciFindBySubsysProcPtr)LoaderSymbol("ScanPciFindPciNamesBySubsys");
    xf86FindPciClassBySubsys =
	(ScanPciFindClassBySubsysProcPtr)LoaderSymbol("ScanPciFindPciClassBySubsys");
    xf86FindPciClassByDevice =
	(ScanPciFindClassByDeviceProcPtr)LoaderSymbol("ScanPciFindPciClassByDevice");
#else
    xf86SetupPciIds = ScanPciSetupPciIds;
    xf86ClosePciIds = ScanPciClosePciIds;
    xf86FindPciNamesByDevice = ScanPciFindPciNamesByDevice;
    xf86FindPciNamesBySubsys = ScanPciFindPciNamesBySubsys;
    xf86FindPciClassBySubsys = ScanPciFindPciClassBySubsys;
    xf86FindPciClassByDevice = ScanPciFindPciClassByDevice;
#endif

    if (!xf86SetupPciIds())
	FatalError("xf86SetupPciIds() failed\n");

    FindPCIVideoInfo();
}

static void alignBridgeRanges(PciBusPtr PciBusBase, PciBusPtr primary);

static void
printBridgeInfo(PciBusPtr PciBus) 
{
    char primary[8], secondary[8], subordinate[8], brbus[8];

    xf86FormatPciBusNumber(PciBus->primary, primary);
    xf86FormatPciBusNumber(PciBus->secondary, secondary);
    xf86FormatPciBusNumber(PciBus->subordinate, subordinate);
    xf86FormatPciBusNumber(PciBus->brbus, brbus);

    xf86MsgVerb(X_INFO, 3, "Bus %s: bridge is at (%s:%d:%d), (%s,%s,%s),"
		" BCTRL: 0x%04x (VGA_EN is %s)\n",
		secondary, brbus, PciBus->brdev, PciBus->brfunc,
		primary, secondary, subordinate, PciBus->brcontrol,
		(PciBus->brcontrol & PCI_PCI_BRIDGE_VGA_EN) ?
		 "set" : "cleared");
    if (PciBus->preferred_io) {
	xf86MsgVerb(X_INFO, 3,
		    "Bus %s I/O range:\n", secondary);
	xf86PrintResList(3, PciBus->preferred_io);
    }
    if (PciBus->preferred_mem) {
	xf86MsgVerb(X_INFO, 3,
		    "Bus %s non-prefetchable memory range:\n", secondary);
	xf86PrintResList(3, PciBus->preferred_mem);
    }
    if (PciBus->preferred_pmem) {
	xf86MsgVerb(X_INFO, 3,
		    "Bus %s prefetchable memory range:\n", secondary);
	xf86PrintResList(3, PciBus->preferred_pmem);
    }
}

static PciBusPtr
xf86GetPciBridgeInfo(void)
{
    const pciConfigPtr *pcrpp;
    pciConfigPtr pcrp;
    pciBusInfo_t *pBusInfo;
    resRange range;
    PciBusPtr PciBus, PciBusBase = NULL;
    PciBusPtr *pnPciBus = &PciBusBase;
    int MaxBus = 0;
    int i, domain;
    int primary, secondary, subordinate;
    memType base, limit;

    resPtr pciBusAccWindows = xf86PciBusAccWindowsFromOS();

    if (xf86PciInfo == NULL)
	return NULL;

    /* Add each bridge */
    for (pcrpp = xf86PciInfo, pcrp = *pcrpp; pcrp; pcrp = *(++pcrpp)) {
	if (pcrp->busnum > MaxBus)
	    MaxBus = pcrp->busnum;
	if ((pcrp->pci_base_class == PCI_CLASS_BRIDGE) ||
	    (((pcrp->listed_class >> 8) & 0xff) == PCI_CLASS_BRIDGE)) {
	    int sub_class;
	    sub_class = (pcrp->listed_class & 0xffff) ?
		(pcrp->listed_class & 0xff) : pcrp->pci_sub_class;
	    domain = xf86GetPciDomain(pcrp->tag);

	    switch (sub_class) {
	    case PCI_SUBCLASS_BRIDGE_PCI:
		/* something fishy about the header? If so: just ignore! */
		if ((pcrp->pci_header_type & 0x7f) != 0x01) {
		    xf86MsgVerb(X_WARNING, 3, "PCI-PCI bridge at %x:%x:%x has"
				" unexpected header:  0x%x",
				pcrp->busnum, pcrp->devnum,
				pcrp->funcnum, pcrp->pci_header_type);
		    break;
		}

		domain = pcrp->busnum & 0x0000FF00;
		primary = pcrp->busnum;
		secondary = domain | pcrp->pci_secondary_bus_number;
		subordinate = domain | pcrp->pci_subordinate_bus_number;

		/* Is this the correct bridge? If not, ignore it */
		pBusInfo = pcrp->businfo;
		if (pBusInfo && (pcrp != pBusInfo->bridge)) {
		    xf86MsgVerb(X_WARNING, 3, "PCI bridge mismatch for bus %x:"
				" %x:%x:%x and %x:%x:%x\n", secondary,
				pcrp->busnum, pcrp->devnum, pcrp->funcnum,
				pBusInfo->bridge->busnum,
				pBusInfo->bridge->devnum,
				pBusInfo->bridge->funcnum);
		    break;
		}

		if (pBusInfo && pBusInfo->funcs->pciGetBridgeBuses)
		    (*pBusInfo->funcs->pciGetBridgeBuses)(secondary,
							   &primary,
							   &secondary,
							   &subordinate);

		if (!pcrp->fakeDevice && (primary >= secondary)) {
		    xf86MsgVerb(X_WARNING, 3, "Misconfigured PCI bridge"
				" %x:%x:%x (%x,%x)\n",
				pcrp->busnum, pcrp->devnum, pcrp->funcnum,
				primary, secondary);
		    break;
		}
		
		*pnPciBus = PciBus = xnfcalloc(1, sizeof(PciBusRec));
		pnPciBus = &PciBus->next;

		PciBus->primary = primary;
		PciBus->secondary = secondary;
		PciBus->subordinate = subordinate;

		PciBus->brbus = pcrp->busnum;
		PciBus->brdev = pcrp->devnum;
		PciBus->brfunc = pcrp->funcnum;

		PciBus->subclass = sub_class;
		PciBus->interface = pcrp->pci_prog_if;

		if (pBusInfo && pBusInfo->funcs->pciControlBridge)
		    PciBus->brcontrol =
			(*pBusInfo->funcs->pciControlBridge)(secondary, 0, 0);
		else
		    PciBus->brcontrol = pcrp->pci_bridge_control;

		if (pBusInfo && pBusInfo->funcs->pciGetBridgeResources) {
		    (*pBusInfo->funcs->pciGetBridgeResources)(secondary,
			(pointer *)&PciBus->preferred_io,
			(pointer *)&PciBus->preferred_mem,
			(pointer *)&PciBus->preferred_pmem);
		    break;
		}

		if ((pcrp->pci_command & PCI_CMD_IO_ENABLE) &&
		    (pcrp->pci_upper_io_base || pcrp->pci_io_base ||
		     pcrp->pci_upper_io_limit || pcrp->pci_io_limit)) {
		    base = (pcrp->pci_upper_io_base << 16) |
			((pcrp->pci_io_base & 0xf0u) << 8);
		    limit = (pcrp->pci_upper_io_limit << 16) |
			((pcrp->pci_io_limit & 0xf0u) << 8) | 0x0fff;
		    /*
		     * Deal with bridge ISA mode (256 wide ranges spaced 1K
		     * apart, but only in the first 64K).
		     */
		    if (pcrp->pci_bridge_control & PCI_PCI_BRIDGE_ISA_EN) {
			while ((base <= (CARD16)(-1)) && (base <= limit)) {
			    PCI_I_RANGE(range, pcrp->tag,
				base, base + (CARD8)(-1),
				ResIo | ResBlock | ResExclusive);
			    PciBus->preferred_io =
				xf86AddResToList(PciBus->preferred_io,
						 &range, -1);
			    base += 0x0400;
			}
		    }
		    if (base <= limit) {
			PCI_I_RANGE(range, pcrp->tag, base, limit,
			    ResIo | ResBlock | ResExclusive);
			PciBus->preferred_io =
			    xf86AddResToList(PciBus->preferred_io, &range, -1);
		    }
		}
		if (pcrp->pci_command & PCI_CMD_MEM_ENABLE) {
		  /*
		   * The P2P spec requires these next two, but some bridges
		   * don't comply.  Err on the side of caution, making the not
		   * so bold assumption that no bridge would ever re-route the
		   * bottom megabyte.
		   */
		  if (pcrp->pci_mem_base || pcrp->pci_mem_limit) {
                    base = pcrp->pci_mem_base & 0xfff0u;
                    limit = pcrp->pci_mem_limit & 0xfff0u;
		    if (base <= limit) {
			PCI_M_RANGE(range, pcrp->tag,
				    base << 16, (limit << 16) | 0x0fffff,
				    ResMem | ResBlock | ResExclusive);
			PciBus->preferred_mem =
			    xf86AddResToList(PciBus->preferred_mem, &range, -1);
		    }
		  }

		  if (pcrp->pci_prefetch_mem_base ||
		      pcrp->pci_prefetch_mem_limit ||
		      pcrp->pci_prefetch_upper_mem_base ||
		      pcrp->pci_prefetch_upper_mem_limit) {
                    base = pcrp->pci_prefetch_mem_base & 0xfff0u;
                    limit = pcrp->pci_prefetch_mem_limit & 0xfff0u;
#if defined(LONG64) || defined(WORD64)
		    base |= (memType)pcrp->pci_prefetch_upper_mem_base << 16;
		    limit |= (memType)pcrp->pci_prefetch_upper_mem_limit << 16;
#endif
		    if (base <= limit) {
			PCI_M_RANGE(range, pcrp->tag,
				    base << 16, (limit << 16) | 0xfffff,
				    ResMem | ResBlock | ResExclusive);
			PciBus->preferred_pmem =
			    xf86AddResToList(PciBus->preferred_pmem,
					     &range, -1);
		    }
		  }
		}
		break;

	    case PCI_SUBCLASS_BRIDGE_CARDBUS:
		/* something fishy about the header? If so: just ignore! */
		if ((pcrp->pci_header_type & 0x7f) != 0x02) {
		    xf86MsgVerb(X_WARNING, 3, "PCI-CardBus bridge at %x:%x:%x"
				" has unexpected header:  0x%x",
				pcrp->busnum, pcrp->devnum,
				pcrp->funcnum, pcrp->pci_header_type);
		    break;
		}

		domain = pcrp->busnum & 0x0000FF00;
		primary = pcrp->busnum;
		secondary = domain | pcrp->pci_cb_cardbus_bus_number;
		subordinate = domain | pcrp->pci_subordinate_bus_number;

		/* Is this the correct bridge?  If not, ignore it */
		pBusInfo = pcrp->businfo;
		if (pBusInfo && (pcrp != pBusInfo->bridge)) {
		    xf86MsgVerb(X_WARNING, 3, "CardBus bridge mismatch for bus"
				" %x: %x:%x:%x and %x:%x:%x\n", secondary,
				pcrp->busnum, pcrp->devnum, pcrp->funcnum,
				pBusInfo->bridge->busnum,
				pBusInfo->bridge->devnum,
				pBusInfo->bridge->funcnum);
		    break;
		}

		if (pBusInfo && pBusInfo->funcs->pciGetBridgeBuses)
		    (*pBusInfo->funcs->pciGetBridgeBuses)(secondary,
							   &primary,
							   &secondary,
							   &subordinate);

		if (primary >= secondary) {
		    if (pcrp->pci_cb_cardbus_bus_number != 0)
		        xf86MsgVerb(X_WARNING, 3, "Misconfigured CardBus"
				    " bridge %x:%x:%x (%x,%x)\n",
				    pcrp->busnum, pcrp->devnum, pcrp->funcnum,
				    primary, secondary);
		    break;
		}

		*pnPciBus = PciBus = xnfcalloc(1, sizeof(PciBusRec));
		pnPciBus = &PciBus->next;

		PciBus->primary = primary;
		PciBus->secondary = secondary;
		PciBus->subordinate = subordinate;

		PciBus->brbus = pcrp->busnum;
		PciBus->brdev = pcrp->devnum;
		PciBus->brfunc = pcrp->funcnum;

		PciBus->subclass = sub_class;
		PciBus->interface = pcrp->pci_prog_if;

		if (pBusInfo && pBusInfo->funcs->pciControlBridge)
		    PciBus->brcontrol =
			(*pBusInfo->funcs->pciControlBridge)(secondary, 0, 0);
		else
		    PciBus->brcontrol = pcrp->pci_bridge_control;

		if (pBusInfo && pBusInfo->funcs->pciGetBridgeResources) {
		    (*pBusInfo->funcs->pciGetBridgeResources)(secondary,
			(pointer *)&PciBus->preferred_io,
			(pointer *)&PciBus->preferred_mem,
			(pointer *)&PciBus->preferred_pmem);
		    break;
		}

		if (pcrp->pci_command & PCI_CMD_IO_ENABLE) {
		    if (pcrp->pci_cb_iobase0) {
			base = PCI_CB_IOBASE(pcrp->pci_cb_iobase0);
			limit = PCI_CB_IOLIMIT(pcrp->pci_cb_iolimit0);

			/*
			 * Deal with bridge ISA mode (256-wide ranges spaced 1K
			 * apart (start to start), but only in the first 64K).
			 */
			if (pcrp->pci_bridge_control & PCI_PCI_BRIDGE_ISA_EN) {
			    while ((base <= (CARD16)(-1)) &&
				   (base <= limit)) {
				PCI_I_RANGE(range, pcrp->tag,
					    base, base + (CARD8)(-1),
					    ResIo | ResBlock | ResExclusive);
				PciBus->preferred_io =
				    xf86AddResToList(PciBus->preferred_io,
						     &range, -1);
				base += 0x0400;
			    }
			}

			if (base <= limit) {
			    PCI_I_RANGE(range, pcrp->tag, base, limit,
					ResIo | ResBlock | ResExclusive);
			    PciBus->preferred_io =
				xf86AddResToList(PciBus->preferred_io,
						 &range, -1);
			}
		    }

		    if (pcrp->pci_cb_iobase1) {
			base = PCI_CB_IOBASE(pcrp->pci_cb_iobase1);
			limit = PCI_CB_IOLIMIT(pcrp->pci_cb_iolimit1);

			/*
			 * Deal with bridge ISA mode (256-wide ranges spaced 1K
			 * apart (start to start), but only in the first 64K).
			 */
			if (pcrp->pci_bridge_control & PCI_PCI_BRIDGE_ISA_EN) {
			    while ((base <= (CARD16)(-1)) &&
				   (base <= limit)) {
				PCI_I_RANGE(range, pcrp->tag,
					    base, base + (CARD8)(-1),
					    ResIo | ResBlock | ResExclusive);
				PciBus->preferred_io =
				    xf86AddResToList(PciBus->preferred_io,
						     &range, -1);
				base += 0x0400;
			    }
			}

			if (base <= limit) {
			    PCI_I_RANGE(range, pcrp->tag, base, limit,
					ResIo | ResBlock | ResExclusive);
			    PciBus->preferred_io =
				xf86AddResToList(PciBus->preferred_io,
						 &range, -1);
			}
		    }
		}

		if (pcrp->pci_command & PCI_CMD_MEM_ENABLE) {
		    if ((pcrp->pci_cb_membase0) &&
			(pcrp->pci_cb_membase0 <= pcrp->pci_cb_memlimit0)) {
			PCI_M_RANGE(range, pcrp->tag,
				    pcrp->pci_cb_membase0 & ~0x0fff,
				    pcrp->pci_cb_memlimit0 | 0x0fff,
				    ResMem | ResBlock | ResExclusive);
			if (pcrp->pci_bridge_control &
			    PCI_CB_BRIDGE_CTL_PREFETCH_MEM0)
			    PciBus->preferred_pmem =
				xf86AddResToList(PciBus->preferred_pmem,
						 &range, -1);
			else
			    PciBus->preferred_mem =
				xf86AddResToList(PciBus->preferred_mem,
						 &range, -1);
		    }
		    if ((pcrp->pci_cb_membase1) &&
			(pcrp->pci_cb_membase1 <= pcrp->pci_cb_memlimit1)) {
			PCI_M_RANGE(range, pcrp->tag,
				    pcrp->pci_cb_membase1 & ~0x0fff,
				    pcrp->pci_cb_memlimit1 | 0x0fff,
				    ResMem | ResBlock | ResExclusive);
			if (pcrp->pci_bridge_control &
			    PCI_CB_BRIDGE_CTL_PREFETCH_MEM1)
			    PciBus->preferred_pmem =
				xf86AddResToList(PciBus->preferred_pmem,
						 &range, -1);
			else
			    PciBus->preferred_mem =
				xf86AddResToList(PciBus->preferred_mem,
						 &range, -1);
		    }
		}

		break;

	    case PCI_SUBCLASS_BRIDGE_ISA:
	    case PCI_SUBCLASS_BRIDGE_EISA:
	    case PCI_SUBCLASS_BRIDGE_MC:
		*pnPciBus = PciBus = xnfcalloc(1, sizeof(PciBusRec));
		pnPciBus = &PciBus->next;
		PciBus->primary = pcrp->busnum;
		PciBus->secondary = PciBus->subordinate = -1;
		PciBus->brbus = pcrp->busnum;
		PciBus->brdev = pcrp->devnum;
		PciBus->brfunc = pcrp->funcnum;
		PciBus->subclass = sub_class;
		PciBus->brcontrol = PCI_PCI_BRIDGE_VGA_EN;
		break;

	    case PCI_SUBCLASS_BRIDGE_HOST:
		/* Is this the correct bridge?  If not, ignore bus info */
		pBusInfo = pcrp->businfo;

		if (!pBusInfo || pBusInfo == HOST_NO_BUS)
		    break;

		secondary = 0;
		/* Find "secondary" bus segment */
		while (pBusInfo != pciBusInfo[secondary])
			secondary++;
		if (pcrp != pBusInfo->bridge) {
		    xf86MsgVerb(X_WARNING, 3, "Host bridge mismatch for"
				" bus %x: %x:%x:%x and %x:%x:%x\n",
				pBusInfo->primary_bus,
				pcrp->busnum, pcrp->devnum, pcrp->funcnum,
				pBusInfo->bridge->busnum,
				pBusInfo->bridge->devnum,
				pBusInfo->bridge->funcnum);
		    pBusInfo = NULL;
		}

		*pnPciBus = PciBus = xnfcalloc(1, sizeof(PciBusRec));
		pnPciBus = &PciBus->next;


		PciBus->primary = PciBus->secondary = secondary;
		PciBus->subordinate = pciNumBuses - 1;

		if (pBusInfo->funcs->pciGetBridgeBuses)
		    (*pBusInfo->funcs->pciGetBridgeBuses)
		        (secondary,
			   &PciBus->primary,
			   &PciBus->secondary,
			   &PciBus->subordinate);

		PciBus->brbus = pcrp->busnum;
		PciBus->brdev = pcrp->devnum;
		PciBus->brfunc = pcrp->funcnum;

		PciBus->subclass = sub_class;

		if (pBusInfo && pBusInfo->funcs->pciControlBridge)
		    PciBus->brcontrol =
			(*pBusInfo->funcs->pciControlBridge)(secondary, 0, 0);
		else
		    PciBus->brcontrol = PCI_PCI_BRIDGE_VGA_EN;

		if (pBusInfo && pBusInfo->funcs->pciGetBridgeResources) {
		    (*pBusInfo->funcs->pciGetBridgeResources)
			(secondary,
			 (pointer *)&PciBus->preferred_io,
			 (pointer *)&PciBus->preferred_mem,
			 (pointer *)&PciBus->preferred_pmem);
		    break;
		}

		PciBus->preferred_io =
		    xf86ExtractTypeFromList(pciBusAccWindows,
					    RANGE_TYPE(ResIo, domain));
		PciBus->preferred_mem =
		    xf86ExtractTypeFromList(pciBusAccWindows,
					    RANGE_TYPE(ResMem, domain));
		PciBus->preferred_pmem =
		    xf86ExtractTypeFromList(pciBusAccWindows,
					    RANGE_TYPE(ResMem, domain));
		break;

	    default:
		break;
	    }
	}
    }
    for (i = 0; i <= MaxBus; i++) { /* find PCI buses not attached to bridge */
	if (!pciBusInfo[i])
	    continue;
	for (PciBus = PciBusBase; PciBus; PciBus = PciBus->next)
	    if (PciBus->secondary == i) break;
	if (!PciBus) {  /* We assume it's behind a HOST-PCI bridge */
	    /*
	     * Find the 'smallest' free HOST-PCI bridge, where 'small' is in
	     * the order of pciTag().
	     */
	    PCITAG minTag = 0xFFFFFFFF, tag;
	    PciBusPtr PciBusFound = NULL;
	    for (PciBus = PciBusBase; PciBus; PciBus = PciBus->next)
		if ((PciBus->subclass == PCI_SUBCLASS_BRIDGE_HOST) &&
		    (PciBus->secondary == -1) &&
		    ((tag = pciTag(PciBus->brbus,PciBus->brdev,PciBus->brfunc))
		     < minTag) )  {
		    minTag = tag;
		    PciBusFound = PciBus;
		}
	    if (PciBusFound)
		PciBusFound->secondary = i;
	    else {  /* if nothing found it may not be visible: create new */
		/* Find a device on this bus */
		domain = 0;
		for (pcrpp = xf86PciInfo;  (pcrp = *pcrpp);  pcrpp++) {
		    if (pcrp->busnum == i) {
			domain = xf86GetPciDomain(pcrp->tag);
			break;
		    }
		}
		*pnPciBus = PciBus = xnfcalloc(1, sizeof(PciBusRec));
		pnPciBus = &PciBus->next;
		PciBus->primary = PciBus->secondary = i;
		PciBus->subclass = PCI_SUBCLASS_BRIDGE_HOST;
		PciBus->brcontrol = PCI_PCI_BRIDGE_VGA_EN;
		PciBus->preferred_io =
		    xf86ExtractTypeFromList(pciBusAccWindows,
					    RANGE_TYPE(ResIo, domain));
		PciBus->preferred_mem =
		    xf86ExtractTypeFromList(pciBusAccWindows,
					    RANGE_TYPE(ResMem, domain));
		PciBus->preferred_pmem =
		    xf86ExtractTypeFromList(pciBusAccWindows,
					    RANGE_TYPE(ResMem, domain));
	    }
	}
    }

    for (PciBus = PciBusBase; PciBus; PciBus = PciBus->next) {
	if (PciBus->primary == PciBus->secondary) {
	    alignBridgeRanges(PciBusBase, PciBus);
	}
    }

    for (PciBus = PciBusBase; PciBus; PciBus = PciBus->next) {
	switch (PciBus->subclass) {
	    case PCI_SUBCLASS_BRIDGE_PCI:
		if (PciBus->interface == PCI_IF_BRIDGE_PCI_SUBTRACTIVE)
		    xf86MsgVerb(X_INFO, 3, "Subtractive PCI-to-PCI bridge:\n");
		else
		    xf86MsgVerb(X_INFO, 3, "PCI-to-PCI bridge:\n");
		break;
	    case PCI_SUBCLASS_BRIDGE_CARDBUS:
		xf86MsgVerb(X_INFO, 3, "PCI-to-CardBus bridge:\n");
		break;
	    case PCI_SUBCLASS_BRIDGE_HOST:
		xf86MsgVerb(X_INFO, 3, "Host-to-PCI bridge:\n");
		break;
	    case PCI_SUBCLASS_BRIDGE_ISA:
		xf86MsgVerb(X_INFO, 3, "PCI-to-ISA bridge:\n");
		break;
	    case PCI_SUBCLASS_BRIDGE_EISA:
		xf86MsgVerb(X_INFO, 3, "PCI-to-EISA bridge:\n");
		break;
	    case PCI_SUBCLASS_BRIDGE_MC:
		xf86MsgVerb(X_INFO, 3, "PCI-to-MCA bridge:\n");
		break;
	    default:
		break;
	}
	printBridgeInfo(PciBus);
    }
    xf86FreeResList(pciBusAccWindows);
    return PciBusBase;
}

static void
alignBridgeRanges(PciBusPtr PciBusBase, PciBusPtr primary)
{
    PciBusPtr PciBus;

    for (PciBus = PciBusBase; PciBus; PciBus = PciBus->next) {
	if ((PciBus != primary) && (PciBus->primary != -1)
	    && (PciBus->primary == primary->secondary)) {
	    resPtr tmp;
	    tmp = xf86FindIntersectOfLists(primary->preferred_io,
					   PciBus->preferred_io);
	    xf86FreeResList(PciBus->preferred_io);
	    PciBus->preferred_io = tmp;
	    tmp = xf86FindIntersectOfLists(primary->preferred_pmem,
					   PciBus->preferred_pmem);
	    xf86FreeResList(PciBus->preferred_pmem);
	    PciBus->preferred_pmem = tmp;
	    tmp = xf86FindIntersectOfLists(primary->preferred_mem,
					   PciBus->preferred_mem);
	    xf86FreeResList(PciBus->preferred_mem);
	    PciBus->preferred_mem = tmp;

	    /* Deal with subtractive decoding */
	    switch (PciBus->subclass) {
	    case PCI_SUBCLASS_BRIDGE_PCI:
		if (PciBus->interface != PCI_IF_BRIDGE_PCI_SUBTRACTIVE)
		    break;
		/* Fall through */
#if 0	/* Not yet */
	    case PCI_SUBCLASS_BRIDGE_ISA:
	    case PCI_SUBCLASS_BRIDGE_EISA:
	    case PCI_SUBCLASS_BRIDGE_MC:
#endif
		if (!(PciBus->io = primary->io))
		    PciBus->io = primary->preferred_io;
		if (!(PciBus->mem = primary->mem))
		    PciBus->mem = primary->preferred_mem;
		if (!(PciBus->pmem = primary->pmem))
		    PciBus->pmem = primary->preferred_pmem;
	    default:
		break;
	    }

	    alignBridgeRanges(PciBusBase, PciBus);
	}
    }
}

void
ValidatePci(void)
{
    pciVideoPtr pvp, pvp1;
    PciBusPtr pbp;
    pciConfigPtr pcrp, *pcrpp;
    CARD32 *basep;
    resPtr Sys;
    resRange range;
    int n = 0, m, i;

    if (!xf86PciVideoInfo) return;

    /*
     * Mark all pciInfoRecs that need to be validated. These are
     * the ones which have been assigned to a screen.
     */
    Sys = xf86DupResList(osRes);
    /* Only validate graphics devices in use */
    for (i=0; i<xf86NumScreens; i++) {
	for (m = 0; m < xf86Screens[i]->numEntities; m++)
	    if ((pvp = xf86GetPciInfoForEntity(xf86Screens[i]->entityList[m])))
		pvp->validate = TRUE;
    }
    
    /*
     * Collect all background PCI resources we need to validate against.
     * These are all resources which don't belong to PCINONSYSTEMCLASSES
     * and which have not been assigned to an entity.
     */
    /* First get the PCIINFOCLASSES */
    m = 0;
    while ((pvp = xf86PciVideoInfo[m++])) {
	/* is it a PCINONSYSTEMCLASS? */
	if (PCINONSYSTEMCLASSES(pvp->class, pvp->subclass))
	    continue;
	/* has it an Entity assigned to it? */
	for (i=0; i<xf86NumEntities; i++) {
	    EntityPtr p = xf86Entities[i];
	    if (p->busType != BUS_PCI)
		continue;
	    if (p->pciBusId.bus == pvp->bus
		&& p->pciBusId.device == pvp->device
		&& p->pciBusId.func == pvp->func)
		break;
	}
	if (i != xf86NumEntities) /* found an Entity for this one */
	    continue;
	
	for (i = 0; i<6; i++) {
	    if (pvp->ioBase[i]) {
		PV_I_RANGE(range,pvp,i,ResExcIoBlock);
		Sys = xf86AddResToList(Sys,&range,-1);
	    } else if (pvp->memBase[i]) {
		PV_M_RANGE(range,pvp,i,ResExcMemBlock);
		Sys = xf86AddResToList(Sys,&range,-1);
	    }
	}
    }
    for (pcrpp = xf86PciInfo, pcrp = *pcrpp; pcrp; pcrp = *++(pcrpp)) {

	/* These were handled above */
	if (PCIINFOCLASSES(pcrp->pci_base_class, pcrp->pci_sub_class))
	    continue;
	
	if ((pcrp->pci_header_type & 0x7f) ||
	    !(pcrp->pci_command & (PCI_CMD_IO_ENABLE | PCI_CMD_MEM_ENABLE)))
	    continue;

	basep = &pcrp->pci_base0;
	for (i = 0; i < 6; i++) {
	    if (basep[i]) {
		if (PCI_MAP_IS_IO(basep[i]))  {
		    if (!(pcrp->pci_command & PCI_CMD_IO_ENABLE))
			continue;
		    P_I_RANGE(range, pcrp->tag, PCIGETIO(basep[i]),
			      pcrp->basesize[i], ResExcIoBlock)
		} else if (!PCI_MAP_IS64BITMEM(basep[i])) {
		    if (!(pcrp->pci_command & PCI_CMD_MEM_ENABLE))
			continue;
		    P_M_RANGE(range, pcrp->tag, PCIGETMEMORY(basep[i]),
			      pcrp->basesize[i], ResExcMemBlock)
		} else {
		    i++;
		    if (!(pcrp->pci_command & PCI_CMD_MEM_ENABLE))
			continue;
#if defined(LONG64) || defined(WORD64)
		    P_M_RANGE(range, pcrp->tag, PCIGETMEMORY64(basep[i-1]),
			      pcrp->basesize[i-1], ResExcMemBlock)
#else
		    if (basep[i])
		        continue;
		    P_M_RANGE(range, pcrp->tag, PCIGETMEMORY(basep[i-1]),
			      pcrp->basesize[i-1], ResExcMemBlock)
#endif
		} 
		Sys = xf86AddResToList(Sys, &range, -1);
	    }
	}
	if ((pcrp->pci_baserom) &&
	    (pcrp->pci_command & PCI_CMD_MEM_ENABLE) &&
	    (pcrp->pci_baserom & PCI_MAP_ROM_DECODE_ENABLE)) {
	    P_M_RANGE(range,pcrp->tag,PCIGETROM(pcrp->pci_baserom),
		      pcrp->basesize[6],ResExcMemBlock);
	    Sys = xf86AddResToList(Sys, &range, -1);
	}
    }
#ifdef DEBUG
    xf86MsgVerb(X_INFO, 3,"Sys:\n");
    xf86PrintResList(3,Sys);
#endif

    /*
     * The order the video devices are listed in is
     * just right: the lower buses come first.
     * This way we attempt to fix a conflict of
     * a lower bus device with a higher bus device
     * where we have more room to find different
     * resources.
     */
    while ((pvp = xf86PciVideoInfo[n++])) {
	resPtr res_mp = NULL, res_m_io = NULL;
	resPtr NonSys;
	resPtr tmp, avoid = NULL;

	if (!pvp->validate) continue;
	NonSys = xf86DupResList(Sys);
	m = n;
	while ((pvp1 = xf86PciVideoInfo[m++])) {
	    if (!pvp1->validate) continue;
	    for (i = 0; i<6; i++) {
		if (pvp1->ioBase[i]) {
		    PV_I_RANGE(range,pvp1,i,ResExcIoBlock);
		    NonSys = xf86AddResToList(NonSys,&range,-1);
		} else if (pvp1->memBase[i]) {
		    PV_M_RANGE(range,pvp1,i,ResExcMemBlock);
		    NonSys = xf86AddResToList(NonSys,&range,-1);
		}
	    }
	}
#ifdef DEBUG
	xf86MsgVerb(X_INFO, 3,"NonSys:\n");
	xf86PrintResList(3,NonSys);
#endif
	pbp = xf86PciBus;
	while (pbp) {
	    if (pbp->secondary == pvp->bus) {
		if (pbp->preferred_pmem) {
		    /* keep prefetchable separate */
		    res_mp =
			xf86FindIntersectOfLists(pbp->preferred_pmem, ResRange);
		}
		if (pbp->pmem) {
		    res_mp = xf86FindIntersectOfLists(pbp->pmem, ResRange);
		}
		if (pbp->preferred_mem) {
		    res_m_io =
			xf86FindIntersectOfLists(pbp->preferred_mem, ResRange);
		}
		if (pbp->mem) {
		    res_m_io = xf86FindIntersectOfLists(pbp->mem, ResRange);
		}
		if (pbp->preferred_io) {
		    res_m_io = xf86JoinResLists(res_m_io,
			xf86FindIntersectOfLists(pbp->preferred_io, ResRange));
		}
		if (pbp->io) {
		    res_m_io = xf86JoinResLists(res_m_io,
			xf86FindIntersectOfLists(pbp->preferred_io, ResRange));
		}
	    } else if ((pbp->primary == pvp->bus) &&
		       (pbp->secondary >= 0) &&
		       (pbp->primary != pbp->secondary)) {
		tmp = xf86DupResList(pbp->preferred_pmem);
		avoid = xf86JoinResLists(avoid, tmp);
		tmp = xf86DupResList(pbp->preferred_mem);
		avoid = xf86JoinResLists(avoid, tmp);
		tmp = xf86DupResList(pbp->preferred_io);
		avoid = xf86JoinResLists(avoid, tmp);
	    }
	    pbp = pbp->next;
	}
	if (res_m_io == NULL)
	   res_m_io = xf86DupResList(ResRange);

	pciConvertListToHost(pvp->bus,pvp->device,pvp->func, avoid);

#ifdef DEBUG
	xf86MsgVerb(X_INFO, 3,"avoid:\n");
	xf86PrintResList(3,avoid);
	xf86MsgVerb(X_INFO, 3,"prefetchable Memory:\n");
	xf86PrintResList(3,res_mp);
	xf86MsgVerb(X_INFO, 3,"MEM/IO:\n");
	xf86PrintResList(3,res_m_io);
#endif
	for (i = 0; i < 6; i++) {
	    int j;
	    resPtr own = NULL;
	    for (j = i+1; j < 6; j++) {
		if (pvp->ioBase[j]) {
		    PV_I_RANGE(range,pvp,j,ResExcIoBlock);
		    own = xf86AddResToList(own,&range,-1);
		} else if (pvp->memBase[j]) {
		    PV_M_RANGE(range,pvp,j,ResExcMemBlock);
		    own = xf86AddResToList(own,&range,-1);
		}
	    }
#ifdef DEBUG
	    xf86MsgVerb(X_INFO, 3, "own:\n");
	    xf86PrintResList(3, own);
#endif
	    if (pvp->ioBase[i]) {
		PV_I_RANGE(range,pvp,i,ResExcIoBlock);
		if (xf86IsSubsetOf(range,res_m_io)
		    && ! ChkConflict(&range,own,SETUP)
		    && ! ChkConflict(&range,avoid,SETUP)
		    && ! ChkConflict(&range,NonSys,SETUP)) {
		    xf86FreeResList(own);
		    continue;
		}
		xf86MsgVerb(X_WARNING, 0,
			"****INVALID IO ALLOCATION**** b: 0x%lx e: 0x%lx "
			"correcting\a\n", range.rBegin,range.rEnd);
#ifdef DEBUG
		sleep(2);
#endif
		fixPciResource(i, 0, pvp, range.type);
	    } else if (pvp->memBase[i]) {
		PV_M_RANGE(range,pvp,i,ResExcMemBlock);
		if (pvp->type[i] & PCI_MAP_MEMORY_CACHABLE) {
		    if (xf86IsSubsetOf(range,res_mp)
			&& ! ChkConflict(&range,own,SETUP)
			&& ! ChkConflict(&range,avoid,SETUP)
			&& ! ChkConflict(&range,NonSys,SETUP)) {
		        xf86FreeResList(own);
			continue;
		    }
		}
		if (xf86IsSubsetOf(range,res_m_io)
		    && ! ChkConflict(&range,own,SETUP)
		    && ! ChkConflict(&range,avoid,SETUP)
		    && ! ChkConflict(&range,NonSys,SETUP)) {
		    xf86FreeResList(own);
		    continue;
		}
		xf86MsgVerb(X_WARNING, 0,
			"****INVALID MEM ALLOCATION**** b: 0x%lx e: 0x%lx "
			"correcting\a\n", range.rBegin,range.rEnd);
		if (ChkConflict(&range,own,SETUP)) {
		    xf86MsgVerb(X_INFO,3,"own\n");
		    xf86PrintResList(3,own);
		}
		if (ChkConflict(&range,avoid,SETUP)) {
		    xf86MsgVerb(X_INFO,3,"avoid\n");
		    xf86PrintResList(3,avoid);
		}
		if (ChkConflict(&range,NonSys,SETUP)) {
		    xf86MsgVerb(X_INFO,3,"NonSys\n");
		    xf86PrintResList(3,NonSys);
		}

#ifdef DEBUG
		sleep(2);
#endif
		fixPciResource(i, 0, pvp, range.type);
	    }
	    xf86FreeResList(own);
	}
	xf86FreeResList(avoid);
	xf86FreeResList(NonSys);
	xf86FreeResList(res_mp);
	xf86FreeResList(res_m_io);
    }
    xf86FreeResList(Sys);
}
    
resList
GetImplicitPciResources(int entityIndex)
{
    pciVideoPtr pvp;
    int i;
    resList list = NULL;
    int num = 0;
    
    if (! (pvp = xf86GetPciInfoForEntity(entityIndex))) return NULL;

    for (i = 0; i < 6; i++) {
	if (pvp->ioBase[i]) {
	    list = xnfrealloc(list,sizeof(resRange) * (++num));
	    PV_I_RANGE(list[num - 1],pvp,i,ResShrIoBlock | ResBios); 
	} else if (pvp->memBase[i]) {
	    list = xnfrealloc(list,sizeof(resRange) * (++num));
	    PV_M_RANGE(list[num - 1],pvp,i,ResShrMemBlock | ResBios);
	}
    }
#if 0
    if (pvp->biosBase) {
	list = xnfrealloc(list,sizeof(resRange) * (++num));
	PV_B_RANGE(list[num - 1],pvp,ResShrMemBlock | ResBios);
    }
#endif
    list = xnfrealloc(list,sizeof(resRange) * (++num));
    list[num - 1].type = ResEnd;
    
    return list;
}

void
initPciState(void)
{
    int i = 0;
    int j = 0;
    pciVideoPtr pvp; 
    pciAccPtr pcaccp;

    if (xf86PciAccInfo != NULL)
	return;
  
    if (xf86PciVideoInfo == NULL)
	return;

    while ((pvp = xf86PciVideoInfo[i]) != NULL) {
  	i++;
  	    j++;
  	    xf86PciAccInfo = xnfrealloc(xf86PciAccInfo,
  					sizeof(pciAccPtr) * (j + 1));
  	    xf86PciAccInfo[j] = NULL;
  	    pcaccp = xf86PciAccInfo[j - 1] = xnfalloc(sizeof(pciAccRec));
	    pcaccp->busnum = pvp->bus; 
 	    pcaccp->devnum = pvp->device; 
 	    pcaccp->funcnum = pvp->func;
 	    pcaccp->arg.tag = pciTag(pvp->bus, pvp->device, pvp->func);
  	    pcaccp->ioAccess.AccessDisable = pciIoAccessDisable;
  	    pcaccp->ioAccess.AccessEnable = pciIoAccessEnable;
  	    pcaccp->ioAccess.arg = &pcaccp->arg;
	    pcaccp->io_memAccess.AccessDisable = pciIo_MemAccessDisable;
	    pcaccp->io_memAccess.AccessEnable = pciIo_MemAccessEnable;
	    pcaccp->io_memAccess.arg = &pcaccp->arg;
	    pcaccp->memAccess.AccessDisable = pciMemAccessDisable;
	    pcaccp->memAccess.AccessEnable = pciMemAccessEnable;
	    pcaccp->memAccess.arg = &pcaccp->arg;
 	    if (PCISHAREDIOCLASSES(pvp->class, pvp->subclass))
 		pcaccp->ctrl = TRUE;
 	    else
 		pcaccp->ctrl = FALSE;
 	    savePciState(pcaccp->arg.tag, &pcaccp->save);
	    pcaccp->arg.ctrl = pcaccp->save.command;
    }
}

/*
 * initPciBusState() - fill out the BusAccRec for a PCI bus.
 * Theory: each bus is associated with one bridge connecting it
 * to its parent bus. The address of a bridge is therefore stored
 * in the BusAccRec of the bus it connects to. Each bus can
 * have several bridges connecting secondary buses to it. Only one
 * of these bridges can be open. Therefore the status of a bridge
 * associated with a bus is stored in the BusAccRec of the parent
 * the bridge connects to. The first member of the structure is
 * a pointer to a function that open access to this bus. This function
 * receives a pointer to the structure itself as argument. This
 * design should be common to BusAccRecs of any type of buses we
 * support. The remeinder of the structure is bus type specific.
 * In this case it contains a pointer to the structure of the
 * parent bus. Thus enabling access to a specific bus is simple:
 * 1. Close any bridge going to secondary buses.
 * 2. Climb down the ladder and enable any bridge on buses
 *    on the path from the CPU to this bus.
 */
 
void
initPciBusState(void)
{
    BusAccPtr pbap, pbap_tmp;
    PciBusPtr pbp = xf86PciBus;
    pciBusInfo_t *pBusInfo;

    while (pbp) {
	pbap = xnfcalloc(1,sizeof(BusAccRec));
	pbap->busdep.pci.bus = pbp->secondary;
	pbap->busdep.pci.primary_bus = pbp->primary;
	pbap->busdep_type = BUS_PCI;
	pbap->busdep.pci.acc = PCITAG_SPECIAL;

	if ((pbp->secondary >= 0) && (pbp->secondary < pciNumBuses) &&
	    (pBusInfo = pciBusInfo[pbp->secondary]) &&
	    pBusInfo->funcs->pciControlBridge) {
	    pbap->type = BUS_PCI;
	    pbap->save_f = savePciDrvBusState;
	    pbap->restore_f = restorePciDrvBusState;
	    pbap->set_f = pciSetBusAccess;
	    pbap->enable_f = pciDrvBusAccessEnable;
	    pbap->disable_f = pciDrvBusAccessDisable;
	    savePciDrvBusState(pbap);
	} else switch (pbp->subclass) {
	case PCI_SUBCLASS_BRIDGE_HOST:
	    pbap->type = BUS_PCI;
	    pbap->set_f = pciSetBusAccess;
	    break;
	case PCI_SUBCLASS_BRIDGE_PCI:
	case PCI_SUBCLASS_BRIDGE_CARDBUS:
	    pbap->type = BUS_PCI;
	    pbap->save_f = savePciBusState;
	    pbap->restore_f = restorePciBusState;
	    pbap->set_f = pciSetBusAccess;
	    pbap->enable_f = pciBusAccessEnable;
	    pbap->disable_f = pciBusAccessDisable;
	    pbap->busdep.pci.acc = pciTag(pbp->brbus,pbp->brdev,pbp->brfunc);
	    savePciBusState(pbap);
	    break;
	case PCI_SUBCLASS_BRIDGE_ISA:
	case PCI_SUBCLASS_BRIDGE_EISA:
	case PCI_SUBCLASS_BRIDGE_MC:
	    pbap->type = BUS_ISA;
	    pbap->set_f = pciSetBusAccess;
	    break;
	}
	pbap->next = xf86BusAccInfo;
	xf86BusAccInfo = pbap;
	pbp = pbp->next;
    }

    pbap = xf86BusAccInfo;

    while (pbap) {
	pbap->primary = NULL;
	if (pbap->busdep_type == BUS_PCI
	    && pbap->busdep.pci.primary_bus > -1) {
	    pbap_tmp = xf86BusAccInfo;
	    while (pbap_tmp) {
		if (pbap_tmp->busdep_type == BUS_PCI &&
		    pbap_tmp->busdep.pci.bus == pbap->busdep.pci.primary_bus) {
		    /* Don't create loops */
		    if (pbap == pbap_tmp)
			break;
		    pbap->primary = pbap_tmp;
		    break;
		}
		pbap_tmp = pbap_tmp->next;
	    }
	}
	pbap = pbap->next;
    }
}

void 
PciStateEnter(void)
{
    pciAccPtr paccp;
    int i = 0;
    
    if (xf86PciAccInfo == NULL) 
	return;

    while ((paccp = xf86PciAccInfo[i]) != NULL) {
	i++;
 	if (!paccp->ctrl)
 	    continue;
	savePciState(paccp->arg.tag, &paccp->save);
	restorePciState(paccp->arg.tag, &paccp->restore);
	paccp->arg.ctrl = paccp->restore.command;
    }
}

void
PciBusStateEnter(void)
{
    BusAccPtr pbap = xf86BusAccInfo;

    while (pbap) {
	if (pbap->save_f)
	    pbap->save_f(pbap);
	pbap = pbap->next;
    }
}

void 
PciStateLeave(void)
{
    pciAccPtr paccp;
    int i = 0;

    if (xf86PciAccInfo == NULL) 
	return;

    while ((paccp = xf86PciAccInfo[i]) != NULL) {
	i++;
	if (!paccp->ctrl)
	    continue;
	savePciState(paccp->arg.tag, &paccp->restore);
	restorePciState(paccp->arg.tag, &paccp->save);
    }
}

void
PciBusStateLeave(void)
{
    BusAccPtr pbap = xf86BusAccInfo;

    while (pbap) {
	if (pbap->restore_f)
	    pbap->restore_f(pbap);
	pbap = pbap->next;
    }
}

void 
DisablePciAccess(void)
{
    int i = 0;
    pciAccPtr paccp;
    if (xf86PciAccInfo == NULL)
	return;

    while ((paccp = xf86PciAccInfo[i]) != NULL) {
	i++;
	if (!paccp->ctrl) /* disable devices that are under control initially*/
	    continue;
	pciIo_MemAccessDisable(paccp->io_memAccess.arg);
    }
}

void
DisablePciBusAccess(void)
{
    BusAccPtr pbap = xf86BusAccInfo;

    while (pbap) {
	if (pbap->disable_f)
	    pbap->disable_f(pbap);
	if (pbap->primary)
	    pbap->primary->current = NULL;
	pbap = pbap->next;
    }
}

/*
 * Public functions
 */

Bool
xf86IsPciDevPresent(int bus, int dev, int func)
{
    int i = 0;
    pciConfigPtr pcp;
    
    while ((pcp = xf86PciInfo[i]) != NULL) {
	if ((pcp->busnum == bus)
	    && (pcp->devnum == dev)
	    && (pcp->funcnum == func))
	    return TRUE;
	i++;
    }
    return FALSE;
}

/*
 * If the slot requested is already in use, return -1.
 * Otherwise, claim the slot for the screen requesting it.
 */

int
xf86ClaimPciSlot(int bus, int device, int func, DriverPtr drvp,
		 int chipset, GDevPtr dev, Bool active)
{
    EntityPtr p = NULL;
    pciAccPtr *ppaccp = xf86PciAccInfo;
    BusAccPtr pbap = xf86BusAccInfo;
    
    int num;
    
    if (xf86CheckPciSlot(bus, device, func)) {
	num = xf86AllocateEntity();
	p = xf86Entities[num];
	p->driver = drvp;
	p->chipset = chipset;
	p->busType = BUS_PCI;
	p->pciBusId.bus = bus;
	p->pciBusId.device = device;
	p->pciBusId.func = func;
	p->active = active;
	p->inUse = FALSE;
	if (dev)
            xf86AddDevToEntity(num, dev);
	/* Here we initialize the access structure */
	p->access = xnfcalloc(1,sizeof(EntityAccessRec));
	while (ppaccp && *ppaccp) {
	    if ((*ppaccp)->busnum == bus
		&& (*ppaccp)->devnum == device
		&& (*ppaccp)->funcnum == func) {
		p->access->fallback = &(*ppaccp)->io_memAccess;
		p->access->pAccess = &(*ppaccp)->io_memAccess;
 		(*ppaccp)->ctrl = TRUE; /* mark control if not already */
		break;
	    }
	    ppaccp++;
	}
	if (!ppaccp || !*ppaccp) {
	    p->access->fallback = &AccessNULL;
	    p->access->pAccess = &AccessNULL;
	}
	
	p->busAcc = NULL;
	while (pbap) {
	    if (pbap->type == BUS_PCI && pbap->busdep.pci.bus == bus)
		p->busAcc = pbap;
	    pbap = pbap->next;
	}
	fixPciSizeInfo(num);

	/* in case bios is enabled disable it */
	disablePciBios(pciTag(bus,device,func));
	pciSlotClaimed = TRUE;

	if (active) {
	    /* Map in this domain's I/O space */
	   p->domainIO = xf86MapDomainIO(-1, VIDMEM_MMIO,
					 pciTag(bus, device, func), 0, 1);
	}
	
 	return num;
    } else
 	return -1;
}

/*
 * Get xf86PciVideoInfo for a driver.
 */
pciVideoPtr *
xf86GetPciVideoInfo(void)
{
    return xf86PciVideoInfo;
}

/* --- Used by ATI driver, but also more generally useful */

/*
 * Get the full xf86scanpci data.
 */
pciConfigPtr *
xf86GetPciConfigInfo(void)
{
    return xf86PciInfo;
}

/*
 * Enable a device and route VGA to it.  This is intended for a driver's
 * Probe(), before creating EntityRec's.  Only one device can be thus enabled
 * at any one time, and should be disabled when the driver is done with it.
 *
 * The following special calls are also available:
 *
 * pvp == NULL && rt == NONE    disable previously enabled device
 * pvp != NULL && rt == NONE    ensure device is disabled
 * pvp == NULL && rt != NONE    disable >all< subsequent calls to this function
 *                              (done from xf86PostProbe())
 * The last combination has been removed! To do this cleanly we have
 * to implement stages and need to test at each stage dependent function
 * if it is allowed to execute.
 *
 * The device represented by pvp may not have been previously claimed.
 */
void
xf86SetPciVideo(pciVideoPtr pvp, resType rt)
{
    static BusAccPtr pbap = NULL;
    static xf86AccessPtr pAcc = NULL;
    static Bool DoneProbes = FALSE;
    pciAccPtr pcaccp;
    int i;

    if (DoneProbes)
	return;

    /* Disable previous access */
    if (pAcc) {
	if (pAcc->AccessDisable)
	    (*pAcc->AccessDisable)(pAcc->arg);
	pAcc = NULL;
    }
    if (pbap) {
	while (pbap->primary) {
	    if (pbap->disable_f)
		(*pbap->disable_f)(pbap);
	    pbap->primary->current = NULL;
	    pbap = pbap->primary;
	}
	pbap = NULL;
    }

    /* Check for xf86PostProbe's magic combo */
    if (!pvp) {
	if (rt != NONE)
	    DoneProbes = TRUE;
	return;
    }

    /* Validate device */
    if (!xf86PciVideoInfo || !xf86PciAccInfo || !xf86BusAccInfo)
	return;

    for (i = 0; pvp != xf86PciVideoInfo[i]; i++)
	if (!xf86PciVideoInfo[i])
	    return;

    /* Ignore request for claimed adapters */
    if (!xf86CheckPciSlot(pvp->bus, pvp->device, pvp->func))
	return;

    /* Find pciAccRec structure */
    for (i = 0; ; i++) {
	if (!(pcaccp = xf86PciAccInfo[i]))
	    return;
	if ((pvp->bus == pcaccp->busnum) &&
	    (pvp->device == pcaccp->devnum) &&
	    (pvp->func == pcaccp->funcnum))
	    break;
    }

    if (rt == NONE) {
	/* This is a call to ensure the adapter is disabled */
	if (pcaccp->io_memAccess.AccessDisable)
	    (*pcaccp->io_memAccess.AccessDisable)(pcaccp->io_memAccess.arg);
	return;
    }

    /* Find BusAccRec structure */
    for (pbap = xf86BusAccInfo; ; pbap = pbap->next) {
	if (!pbap)
	    return;
	if (pvp->bus == pbap->busdep.pci.bus)
	    break;
    }

    /* Route VGA */
    if (pbap->set_f)
	(*pbap->set_f)(pbap);

    /* Enable device */
    switch (rt) {
    case IO:
	pAcc = &pcaccp->ioAccess;
	break;
    case MEM_IO:
	pAcc = &pcaccp->io_memAccess;
	break;
    case MEM:
	pAcc = &pcaccp->memAccess;
	break;
    default:	/* no compiler noise */
	break;
    }

    if (pAcc && pAcc->AccessEnable)
	(*pAcc->AccessEnable)(pAcc->arg);
}

/*
 * Parse a BUS ID string, and return the PCI bus parameters if it was
 * in the correct format for a PCI bus id.
 */

Bool
xf86ParsePciBusString(const char *busID, int *bus, int *device, int *func)
{
    /*
     * The format is assumed to be "bus[@domain]:device[:func]", where domain,
     * bus, device and func are decimal integers.  domain and func may be
     * omitted and assumed to be zero, although doing this isn't encouraged.
     */

    char *p, *s, *d;
    const char *id;
    int i;

    if (StringToBusType(busID, &id) != BUS_PCI)
	return FALSE;

    s = xstrdup(id);
    p = strtok(s, ":");
    if (p == NULL || *p == 0) {
	xfree(s);
	return FALSE;
    }
    d = strpbrk(p, "@");
    if (d != NULL) {
	*(d++) = 0;
	for (i = 0; d[i] != 0; i++) {
	    if (!isdigit(d[i])) {
		xfree(s);
		return FALSE;
	    }
	}
    }
    for (i = 0; p[i] != 0; i++) {
	if (!isdigit(p[i])) {
	    xfree(s);
	    return FALSE;
	}
    }
    *bus = atoi(p);
    if (d != NULL && *d != 0)
	*bus += atoi(d) << 8;
    p = strtok(NULL, ":");
    if (p == NULL || *p == 0) {
	xfree(s);
	return FALSE;
    }
    for (i = 0; p[i] != 0; i++) {
	if (!isdigit(p[i])) {
	    xfree(s);
	    return FALSE;
	}
    }
    *device = atoi(p);
    *func = 0;
    p = strtok(NULL, ":");
    if (p == NULL || *p == 0) {
	xfree(s);
	return TRUE;
    }
    for (i = 0; p[i] != 0; i++) {
	if (!isdigit(p[i])) {
	    xfree(s);
	    return FALSE;
	}
    }
    *func = atoi(p);
    xfree(s);
    return TRUE;
}

/*
 * Compare a BUS ID string with a PCI bus id.  Return TRUE if they match.
 */

Bool
xf86ComparePciBusString(const char *busID, int bus, int device, int func)
{
    int ibus, idevice, ifunc;

    if (xf86ParsePciBusString(busID, &ibus, &idevice, &ifunc)) {
	return bus == ibus && device == idevice && func == ifunc;
    } else {
	return FALSE;
    }
}

/*
 * xf86IsPrimaryPci() -- return TRUE if primary device
 * is PCI and bus, dev and func numbers match.
 */
 
Bool
xf86IsPrimaryPci(pciVideoPtr pPci)
{
    if (primaryBus.type != BUS_PCI) return FALSE;
    return (pPci->bus == primaryBus.id.pci.bus &&
	    pPci->device == primaryBus.id.pci.device &&
	    pPci->func == primaryBus.id.pci.func);
}

/*
 * xf86CheckPciGAType() -- return type of PCI graphics adapter.
 */
int
xf86CheckPciGAType(pciVideoPtr pPci)
{
    int i = 0;
    pciConfigPtr pcp;
    
    while ((pcp = xf86PciInfo[i]) != NULL) { 
	if (pPci->bus == pcp->busnum && pPci->device == pcp->devnum
	    && pPci->func == pcp->funcnum) {
	    if (pcp->pci_base_class == PCI_CLASS_PREHISTORIC &&
		pcp->pci_sub_class == PCI_SUBCLASS_PREHISTORIC_VGA)
		return PCI_CHIP_VGA ;
	    if (pcp->pci_base_class == PCI_CLASS_DISPLAY &&
		pcp->pci_sub_class == PCI_SUBCLASS_DISPLAY_VGA) {
		if (pcp->pci_prog_if == 0)
		    return PCI_CHIP_VGA ; 
		if (pcp->pci_prog_if == 1)
		    return PCI_CHIP_8514;
	    }
	    return -1;
	}
    i++;
    }
    return -1;
}

/*
 * xf86GetPciInfoForEntity() -- Get the pciVideoRec of entity.
 */
pciVideoPtr
xf86GetPciInfoForEntity(int entityIndex)
{
    pciVideoPtr *ppPci;
    EntityPtr p;
    
    if (entityIndex >= xf86NumEntities)
	return NULL;

    p = xf86Entities[entityIndex];
    if (p->busType != BUS_PCI)
	return NULL;
    
    for (ppPci = xf86PciVideoInfo; *ppPci != NULL; ppPci++) {
	if (p->pciBusId.bus == (*ppPci)->bus &&
	    p->pciBusId.device == (*ppPci)->device &&
	    p->pciBusId.func == (*ppPci)->func) 
	    return (*ppPci);
    }
    return NULL;
}

int
xf86GetPciEntity(int bus, int dev, int func)
{
    int i;
    
    for (i = 0; i < xf86NumEntities; i++) {
	EntityPtr p = xf86Entities[i];
	if (p->busType != BUS_PCI) continue;
	
	if (p->pciBusId.bus == bus &&
	    p->pciBusId.device == dev &&
	    p->pciBusId.func == func) 
	    return i;
    }
    return -1;
}

/*
 * xf86CheckPciMemBase() checks that the memory base value matches one of the
 * PCI base address register values for the given PCI device.
 */
Bool
xf86CheckPciMemBase(pciVideoPtr pPci, memType base)
{
    int i;

    for (i = 0; i < 6; i++)
	if (base == pPci->memBase[i])
	    return TRUE;
    return FALSE;
}

/*
 * Check if the slot requested is free.  If it is already in use, return FALSE.
 */

Bool
xf86CheckPciSlot(int bus, int device, int func)
{
    int i;
    EntityPtr p;

    for (i = 0; i < xf86NumEntities; i++) {
	p = xf86Entities[i];
	/* Check if this PCI slot is taken */
	if (p->busType == BUS_PCI && p->pciBusId.bus == bus &&
	    p->pciBusId.device == device && p->pciBusId.func == func)
	    return FALSE;
    }
    
    return TRUE;
}


/*
 * This used to load the scanpci module.  The pcidata module is now used
 * (which the server always loads early).  The main difference between the
 * two modules is size, and the scanpci module should only ever be loaded
 * when the X server is run with the -scanpci flag.
 *
 * To make sure that the required information is present in the pcidata
 * module, add a PCI_VENDOR_* macro for the relevant vendor to xf86PciInfo.h,
 * and add the class override data to ../etc/extrapci.ids.
 */

static void
getPciClassFlags(pciConfigPtr *pcrpp)
{
    pciConfigPtr pcrp;
    int i = 0;

    if (!pcrpp)
	return;
    while ((pcrp = pcrpp[i])) {
	if (!(pcrp->listed_class =
		xf86FindPciClassBySubsys(pcrp->pci_subsys_vendor,
					 pcrp->pci_subsys_card))) {
	    pcrp->listed_class =
		xf86FindPciClassByDevice(pcrp->pci_vendor, pcrp->pci_device);
	}
	i++;
    }
}

/*
 * xf86FindPciVendorDevice() xf86FindPciClass(): These functions
 * are meant to be used by the pci bios emulation. Some bioses
 * need to see if there are _other_ chips of the same type around
 * so by setting pvp_exclude one pci device can be explicitely
 * _excluded if required.
 */
pciVideoPtr
xf86FindPciDeviceVendor(CARD16 vendorID, CARD16 deviceID,
			char n, pciVideoPtr pvp_exclude)
{
    pciVideoPtr pvp, *ppvp;
    n++;

    for (ppvp = xf86PciVideoInfo, pvp =*ppvp; pvp ; pvp = *(++ppvp)) {
	if (pvp == pvp_exclude) continue;
	if ((pvp->vendor == vendorID) && (pvp->chipType == deviceID)) {
	    if (!(--n)) break;
	}
    }
    return pvp;
}

pciVideoPtr
xf86FindPciClass(CARD8 intf, CARD8 subClass, CARD16 class,
		 char n, pciVideoPtr pvp_exclude)
{
    pciVideoPtr pvp, *ppvp;
    n++;
    
    for (ppvp = xf86PciVideoInfo, pvp =*ppvp; pvp ; pvp = *(++ppvp)) {
	if (pvp == pvp_exclude) continue;
	if ((pvp->interface == intf) && (pvp->subclass == subClass)
	    && (pvp->class == class)) {
	    if (!(--n)) break;
	}
    }
    return pvp;
}

/*
 * This attempts to detect a multi-device card and sets up a list
 * of pci tags of the devices of this card. On some of these
 * cards the BIOS is not visible from all chipsets. We therefore
 * need to use the BIOS from a chipset where it is visible.
 * We do the following heuristics:
 * If we detect only identical pci devices on a bus we assume it's
 * a multi-device card. This assumption isn't true always, however.
 * One might just use identical cards on a bus. We therefore don't
 * detect this situation when we set up the PCI video info. Instead
 * we wait until an attempt to read the BIOS fails.
 */
int
pciTestMultiDeviceCard(int bus, int dev, int func, PCITAG** pTag)
{
  pciConfigPtr *ppcrp = xf86PciInfo;
  pciConfigPtr pcrp = NULL;
  int i,j;
  Bool multicard = FALSE;
  Bool multifunc = FALSE;
  char str[256];
  char *str1;
  
  str1 = str;
  if (!pTag) 
    return 0;

  *pTag = NULL;
 
  for (i=0; i < 8; i++) {
    j = 0;

    while (ppcrp[j]) {
      if (ppcrp[j]->busnum == bus && ppcrp[j]->funcnum == i) {
	pcrp = ppcrp[j];
	break;
      }
      j++;
    }

    if (!pcrp) return 0;

    /* 
     * we check all functions here: since multifunc devices need
     * to implement func 0 we catch all devices on the bus when
     * i = 0
     */
    if (pcrp->pci_header_type &0x80) 
	multifunc = TRUE;
    
    j = 0;
    
    while (ppcrp[j]) {
      if (ppcrp[j]->busnum == bus && ppcrp[j]->funcnum == i
	  && ppcrp[j]->devnum != pcrp->devnum) {
	/* don't test subsys ID here. It might be set by POST 
	   - however some cards might not have been POSTed */
	if (ppcrp[j]->pci_device_vendor != pcrp->pci_device_vendor 
	    || ppcrp[j]->pci_header_type != pcrp->pci_header_type ) 
	  return 0;
	else
	  multicard = TRUE;
      }
      j++;
    }
    if (!multifunc)
      break;
  }

  if (!multicard) 
    return 0;

  j = 0;
  i = 0;
  while (ppcrp[i]) {
    if (ppcrp[i]->busnum == bus && ppcrp[i]->funcnum == func) {
      str1 += sprintf(str1,"[%x:%x:%x]",ppcrp[i]->busnum,
		      ppcrp[i]->devnum,ppcrp[i]->funcnum);
      *pTag = xnfrealloc(*pTag,sizeof(PCITAG) * (j + 1));
      (*pTag)[j++] = pciTag(ppcrp[i]->busnum,
			      ppcrp[i]->devnum,ppcrp[i]->funcnum);
    }
    i++;
  }
  xf86MsgVerb(X_INFO,3,"Multi Device Card detected: %s\n",str);
  return j;
}

static void
pciTagConvertRange2Host(PCITAG tag, resRange *pRange)
{
    if (!(pRange->type & ResBus))
	return;

    switch(pRange->type & ResPhysMask) {
    case ResMem:
	switch(pRange->type & ResExtMask) {
	case ResBlock:
	    pRange->rBegin = pciBusAddrToHostAddr(tag,PCI_MEM, pRange->rBegin);
	    pRange->rEnd = pciBusAddrToHostAddr(tag,PCI_MEM, pRange->rEnd);
	    break;
	case ResSparse:
	    pRange->rBase = pciBusAddrToHostAddr(tag,PCI_MEM_SPARSE_BASE,
						  pRange->rBegin);
	    pRange->rMask = pciBusAddrToHostAddr(tag,PCI_MEM_SPARSE_MASK,
						pRange->rEnd);
	    break;
	}
	break;
    case ResIo:
	switch(pRange->type & ResExtMask) {
	case ResBlock:
	    pRange->rBegin = pciBusAddrToHostAddr(tag,PCI_IO, pRange->rBegin);
	    pRange->rEnd = pciBusAddrToHostAddr(tag,PCI_IO, pRange->rEnd);
	    break;
	case ResSparse:
	    pRange->rBase = pciBusAddrToHostAddr(tag,PCI_IO_SPARSE_BASE
						  , pRange->rBegin);
	    pRange->rMask = pciBusAddrToHostAddr(tag,PCI_IO_SPARSE_MASK
						, pRange->rEnd);
	    break;
	}
	break;
    }

    /* Set domain number */
    pRange->type &= ~(ResDomain | ResBus);
    pRange->type |= xf86GetPciDomain(tag) << 24;
}

static void
pciConvertListToHost(int bus, int dev, int func, resPtr list)
{
    PCITAG tag = pciTag(bus,dev,func);
    while (list) {
	pciTagConvertRange2Host(tag, &list->val);
	list = list->next;
    }
}

static void
updateAccessInfoStatusControlInfo(PCITAG tag, CARD32 ctrl)
{
    int i;

    if (!xf86PciAccInfo)
	return;
    
    for (i = 0; xf86PciAccInfo[i] != NULL; i++) {
	if (xf86PciAccInfo[i]->arg.tag == tag)
	    xf86PciAccInfo[i]->arg.ctrl = ctrl;
    }
}

void
pciConvertRange2Host(int entityIndex, resRange *pRange)
{
    PCITAG tag;
    pciVideoPtr pvp;

    pvp = xf86GetPciInfoForEntity(entityIndex);
    if (!pvp) return;
    tag = TAG(pvp);
    pciTagConvertRange2Host(tag, pRange);
}


#ifdef INCLUDE_DEPRECATED
void
xf86EnablePciBusMaster(pciVideoPtr pPci, Bool enable)
{
    CARD32 temp;
    PCITAG tag;

    if (!pPci) return;

    tag = pciTag(pPci->bus, pPci->device, pPci->func);
    temp = pciReadLong(tag, PCI_CMD_STAT_REG);
    if (enable) {
	updateAccessInfoStatusControlInfo(tag, temp | PCI_CMD_MASTER_ENABLE);
	pciWriteLong(tag, PCI_CMD_STAT_REG, temp | PCI_CMD_MASTER_ENABLE);
    } else {
	updateAccessInfoStatusControlInfo(tag, temp & ~PCI_CMD_MASTER_ENABLE);
	pciWriteLong(tag, PCI_CMD_STAT_REG, temp & ~PCI_CMD_MASTER_ENABLE);
    }
}
#endif /* INCLUDE_DEPRECATED */