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

Copyright 2001 VA Linux Systems Inc., Fremont, California.
Copyright © 2002 by David Dawes

All Rights Reserved.

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
on the rights to use, copy, modify, merge, publish, distribute, sub
license, and/or sell copies of the Software, and to permit persons to whom
the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice (including the next
paragraph) shall be included in all copies or substantial portions of the
Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL
THE COPYRIGHT HOLDERS AND/OR THEIR SUPPLIERS 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.

**************************************************************************/

/*
 * Reformatted with GNU indent (2.2.8), using the following options:
 *
 *    -bad -bap -c41 -cd0 -ncdb -ci6 -cli0 -cp0 -ncs -d0 -di3 -i3 -ip3 -l78
 *    -lp -npcs -psl -sob -ss -br -ce -sc -hnl
 *
 * This provides a good match with the original i810 code and preferred
 * XFree86 formatting conventions.
 *
 * When editing this driver, please follow the existing formatting, and edit
 * with <TAB> characters expanded at 8-column intervals.
 */

/*
 * Authors: Jeff Hartmann <jhartmann@valinux.com>
 *          Abraham van der Merwe <abraham@2d3d.co.za>
 *          David Dawes <dawes@xfree86.org>
 *          Alan Hourihane <alanh@tungstengraphics.com>
 */

/*
 * Mode handling is based on the VESA driver written by:
 * Paulo César Pereira de Andrade <pcpa@conectiva.com.br>
 */

/*
 * Changes:
 *
 *    23/08/2001 Abraham van der Merwe <abraham@2d3d.co.za>
 *        - Fixed display timing bug (mode information for some
 *          modes were not initialized correctly)
 *        - Added workarounds for GTT corruptions (I don't adjust
 *          the pitches for 1280x and 1600x modes so we don't
 *          need extra memory)
 *        - The code will now default to 60Hz if LFP is connected
 *        - Added different refresh rate setting code to work
 *          around 0x4f02 BIOS bug
 *        - BIOS workaround for some mode sets (I use legacy BIOS
 *          calls for setting those)
 *        - Removed 0x4f04, 0x01 (save state) BIOS call which causes
 *          LFP to malfunction (do some house keeping and restore
 *          modes ourselves instead - not perfect, but at least the
 *          LFP is working now)
 *        - Several other smaller bug fixes
 *
 *    06/09/2001 Abraham van der Merwe <abraham@2d3d.co.za>
 *        - Preliminary local memory support (works without agpgart)
 *        - DGA fixes (the code were still using i810 mode sets, etc.)
 *        - agpgart fixes
 *
 *    18/09/2001
 *        - Proper local memory support (should work correctly now
 *          with/without agpgart module)
 *        - more agpgart fixes
 *        - got rid of incorrect GTT adjustments
 *
 *    09/10/2001
 *        - Changed the DPRINTF() variadic macro to an ANSI C compatible
 *          version
 *
 *    10/10/2001
 *        - Fixed DPRINTF_stub(). I forgot the __...__ macros in there
 *          instead of the function arguments :P
 *        - Added a workaround for the 1600x1200 bug (Text mode corrupts
 *          when you exit from any 1600x1200 mode and 1280x1024@85Hz. I
 *          suspect this is a BIOS bug (hence the 1280x1024@85Hz case)).
 *          For now I'm switching to 800x600@60Hz then to 80x25 text mode
 *          and then restoring the registers - very ugly indeed.
 *
 *    15/10/2001
 *        - Improved 1600x1200 mode set workaround. The previous workaround
 *          was causing mode set problems later on.
 *
 *    18/10/2001
 *        - Fixed a bug in I830BIOSLeaveVT() which caused a bug when you
 *          switched VT's
 */
/*
 *    07/2002 David Dawes
 *        - Add Intel(R) 855GM/852GM support.
 */
/*
 *    07/2002 David Dawes
 *        - Cleanup code formatting.
 *        - Improve VESA mode selection, and fix refresh rate selection.
 *        - Don't duplicate functions provided in 4.2 vbe modules.
 *        - Don't duplicate functions provided in the vgahw module.
 *        - Rewrite memory allocation.
 *        - Rewrite initialisation and save/restore state handling.
 *        - Decouple the i810 support from i830 and later.
 *        - Remove various unnecessary hacks and workarounds.
 *        - Fix an 845G problem with the ring buffer not in pre-allocated
 *          memory.
 *        - Fix screen blanking.
 *        - Clear the screen at startup so you don't see the previous session.
 *        - Fix some HW cursor glitches, and turn HW cursor off at VT switch
 *          and exit.
 *
 *    08/2002 Keith Whitwell
 *        - Fix DRI initialisation.
 *
 *
 *    08/2002 Alan Hourihane and David Dawes
 *        - Add XVideo support.
 *
 *
 *    10/2002 David Dawes
 *        - Add Intel(R) 865G support.
 *
 *
 *    01/2004 Alan Hourihane
 *        - Add Intel(R) 915G support.
 *        - Add Dual Head and Clone capabilities.
 *        - Add lid status checking
 *        - Fix Xvideo with high-res LFP's
 *        - Add ARGB HW cursor support
 *
 *    05/2005 Alan Hourihane
 *        - Add Intel(R) 945G support.
 *
 *    09/2005 Alan Hourihane
 *        - Add Intel(R) 945GM support.
 *
 *    10/2005 Alan Hourihane, Keith Whitwell, Brian Paul
 *        - Added Rotation support
 *
 *    12/2005 Alan Hourihane, Keith Whitwell
 *        - Add Intel(R) 965G support.
 */

#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

#ifndef PRINT_MODE_INFO
#define PRINT_MODE_INFO 0
#endif

#include <assert.h>
#include <string.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>

#include "xf86.h"
#include "xf86_OSproc.h"
#include "xf86Resources.h"
#include "xf86RAC.h"
#include "xf86cmap.h"
#include "compiler.h"
#include "mibstore.h"
#include "vgaHW.h"
#include "mipointer.h"
#include "micmap.h"
#include "shadowfb.h"
#include <X11/extensions/randr.h>
#include "fb.h"
#include "miscstruct.h"
#include "dixstruct.h"
#include "xf86xv.h"
#include <X11/extensions/Xv.h>
#include "vbe.h"
#include "shadow.h"
#include "i830.h"
#include "i830_display.h"
#include "i830_debug.h"
#include "i830_bios.h"
#include "i830_video.h"
#if HAVE_SYS_MMAN_H && HAVE_MPROTECT
#include <sys/mman.h>
#endif

#ifdef INTEL_XVMC
#define _INTEL_XVMC_SERVER_
#include "i830_hwmc.h"
#endif

#ifdef XF86DRI
#include "dri.h"
#include <sys/ioctl.h>
#include "i915_drm.h"
#endif

#ifdef I830_USE_EXA
const char *I830exaSymbols[] = {
    "exaGetVersion",
    "exaDriverInit",
    "exaDriverFini",
    "exaOffscreenAlloc",
    "exaOffscreenFree",
    "exaWaitSync",
    NULL
};
#endif

#define BIT(x) (1 << (x))
#define MAX(a,b) ((a) > (b) ? (a) : (b))
#define NB_OF(x) (sizeof (x) / sizeof (*x))

/* *INDENT-OFF* */
static SymTabRec I830Chipsets[] = {
   {PCI_CHIP_I830_M,		"i830"},
   {PCI_CHIP_845_G,		"845G"},
   {PCI_CHIP_I855_GM,		"852GM/855GM"},
   {PCI_CHIP_I865_G,		"865G"},
   {PCI_CHIP_I915_G,		"915G"},
   {PCI_CHIP_E7221_G,		"E7221 (i915)"},
   {PCI_CHIP_I915_GM,		"915GM"},
   {PCI_CHIP_I945_G,		"945G"},
   {PCI_CHIP_I945_GM,		"945GM"},
   {PCI_CHIP_I945_GME,		"945GME"},
   {PCI_CHIP_I965_G,		"965G"},
   {PCI_CHIP_G35_G,		"G35"},
   {PCI_CHIP_I965_Q,		"965Q"},
   {PCI_CHIP_I946_GZ,		"946GZ"},
   {PCI_CHIP_I965_GM,		"965GM"},
   {PCI_CHIP_I965_GME,		"965GME/GLE"},
   {PCI_CHIP_G33_G,		"G33"},
   {PCI_CHIP_Q35_G,		"Q35"},
   {PCI_CHIP_Q33_G,		"Q33"},
   {PCI_CHIP_GM45_GM,		"Mobile Intel® GM45 Express Chipset"},
   {PCI_CHIP_IGD_E_G,		"Intel Integrated Graphics Device"},
   {PCI_CHIP_G45_G,		"G45/G43"},
   {PCI_CHIP_Q45_G,		"Q45/Q43"},
   {-1,				NULL}
};

static PciChipsets I830PciChipsets[] = {
   {PCI_CHIP_I830_M,		PCI_CHIP_I830_M,	RES_SHARED_VGA},
   {PCI_CHIP_845_G,		PCI_CHIP_845_G,		RES_SHARED_VGA},
   {PCI_CHIP_I855_GM,		PCI_CHIP_I855_GM,	RES_SHARED_VGA},
   {PCI_CHIP_I865_G,		PCI_CHIP_I865_G,	RES_SHARED_VGA},
   {PCI_CHIP_I915_G,		PCI_CHIP_I915_G,	RES_SHARED_VGA},
   {PCI_CHIP_E7221_G,		PCI_CHIP_E7221_G,	RES_SHARED_VGA},
   {PCI_CHIP_I915_GM,		PCI_CHIP_I915_GM,	RES_SHARED_VGA},
   {PCI_CHIP_I945_G,		PCI_CHIP_I945_G,	RES_SHARED_VGA},
   {PCI_CHIP_I945_GM,		PCI_CHIP_I945_GM,	RES_SHARED_VGA},
   {PCI_CHIP_I945_GME,		PCI_CHIP_I945_GME,	RES_SHARED_VGA},
   {PCI_CHIP_I965_G,		PCI_CHIP_I965_G,	RES_SHARED_VGA},
   {PCI_CHIP_G35_G,		PCI_CHIP_G35_G,		RES_SHARED_VGA},
   {PCI_CHIP_I965_Q,		PCI_CHIP_I965_Q,	RES_SHARED_VGA},
   {PCI_CHIP_I946_GZ,		PCI_CHIP_I946_GZ,	RES_SHARED_VGA},
   {PCI_CHIP_I965_GM,		PCI_CHIP_I965_GM,	RES_SHARED_VGA},
   {PCI_CHIP_I965_GME,		PCI_CHIP_I965_GME,	RES_SHARED_VGA},
   {PCI_CHIP_G33_G,		PCI_CHIP_G33_G,		RES_SHARED_VGA},
   {PCI_CHIP_Q35_G,		PCI_CHIP_Q35_G,		RES_SHARED_VGA},
   {PCI_CHIP_Q33_G,		PCI_CHIP_Q33_G,		RES_SHARED_VGA},
   {PCI_CHIP_GM45_GM,		PCI_CHIP_GM45_GM,	RES_SHARED_VGA},
   {PCI_CHIP_IGD_E_G,		PCI_CHIP_IGD_E_G,	RES_SHARED_VGA},
   {PCI_CHIP_G45_G,		PCI_CHIP_G45_G,		RES_SHARED_VGA},
   {PCI_CHIP_Q45_G,		PCI_CHIP_Q45_G,		RES_SHARED_VGA},
   {-1,				-1,			RES_UNDEFINED}
};

/*
 * Note: "ColorKey" is provided for compatibility with the i810 driver.
 * However, the correct option name is "VideoKey".  "ColorKey" usually
 * refers to the tranparency key for 8+24 overlays, not for video overlays.
 */

typedef enum {
   OPTION_ACCELMETHOD,
   OPTION_NOACCEL,
   OPTION_SW_CURSOR,
   OPTION_CACHE_LINES,
   OPTION_DRI,
   OPTION_PAGEFLIP,
   OPTION_XVIDEO,
   OPTION_VIDEO_KEY,
   OPTION_COLOR_KEY,
   OPTION_CHECKDEVICES,
   OPTION_MODEDEBUG,
   OPTION_LVDS24BITMODE,
   OPTION_FBC,
   OPTION_TILING,
#ifdef XF86DRI
   OPTION_INTELTEXPOOL,
#endif
   OPTION_LVDSFIXEDMODE,
   OPTION_TRIPLEBUFFER,
   OPTION_FORCEENABLEPIPEA,
#ifdef INTEL_XVMC
   OPTION_XVMC,
#endif
} I830Opts;

static OptionInfoRec I830Options[] = {
   {OPTION_ACCELMETHOD,	"AccelMethod",	OPTV_ANYSTR,	{0},	FALSE},
   {OPTION_NOACCEL,	"NoAccel",	OPTV_BOOLEAN,	{0},	FALSE},
   {OPTION_SW_CURSOR,	"SWcursor",	OPTV_BOOLEAN,	{0},	FALSE},
   {OPTION_CACHE_LINES,	"CacheLines",	OPTV_INTEGER,	{0},	FALSE},
   {OPTION_DRI,		"DRI",		OPTV_BOOLEAN,	{0},	TRUE},
   {OPTION_PAGEFLIP,	"PageFlip",	OPTV_BOOLEAN,	{0},	FALSE},
   {OPTION_XVIDEO,	"XVideo",	OPTV_BOOLEAN,	{0},	TRUE},
   {OPTION_COLOR_KEY,	"ColorKey",	OPTV_INTEGER,	{0},	FALSE},
   {OPTION_VIDEO_KEY,	"VideoKey",	OPTV_INTEGER,	{0},	FALSE},
   {OPTION_CHECKDEVICES, "CheckDevices",OPTV_BOOLEAN,	{0},	FALSE},
   {OPTION_MODEDEBUG,	"ModeDebug",	OPTV_BOOLEAN,	{0},	FALSE},
   {OPTION_LVDS24BITMODE, "LVDS24Bit",	OPTV_BOOLEAN,	{0},	FALSE},
   {OPTION_FBC,		"FramebufferCompression", OPTV_BOOLEAN, {0}, TRUE},
   {OPTION_TILING,	"Tiling",	OPTV_BOOLEAN,	{0},	TRUE},
#ifdef XF86DRI
   {OPTION_INTELTEXPOOL,"Legacy3D",     OPTV_BOOLEAN,	{0},	FALSE},
#endif
   {OPTION_LVDSFIXEDMODE, "LVDSFixedMode", OPTV_BOOLEAN,	{0},	FALSE},
   {OPTION_TRIPLEBUFFER, "TripleBuffer", OPTV_BOOLEAN,	{0},	FALSE},
   {OPTION_FORCEENABLEPIPEA, "ForceEnablePipeA", OPTV_BOOLEAN,	{0},	FALSE},
#ifdef INTEL_XVMC
   {OPTION_XVMC,	"XvMC",		OPTV_BOOLEAN,	{0},	TRUE},
#endif
   {-1,			NULL,		OPTV_NONE,	{0},	FALSE}
};
/* *INDENT-ON* */

const char *i830_output_type_names[] = {
   "Unused",
   "Analog",
   "DVO",
   "SDVO",
   "LVDS",
   "TVOUT",
};

static void i830AdjustFrame(int scrnIndex, int x, int y, int flags);
static Bool I830CloseScreen(int scrnIndex, ScreenPtr pScreen);
static Bool I830EnterVT(int scrnIndex, int flags);
static CARD32 I830CheckDevicesTimer(OsTimerPtr timer, CARD32 now, pointer arg);
static Bool SaveHWState(ScrnInfoPtr pScrn);
static Bool RestoreHWState(ScrnInfoPtr pScrn);

/* temporary */
extern void xf86SetCursor(ScreenPtr pScreen, CursorPtr pCurs, int x, int y);

#ifdef I830DEBUG
void
I830DPRINTF_stub(const char *filename, int line, const char *function,
		 const char *fmt, ...)
{
   va_list ap;

   ErrorF("\n##############################################\n"
	  "*** In function %s, on line %d, in file %s ***\n",
	  function, line, filename);
   va_start(ap, fmt);
   VErrorF(fmt, ap);
   va_end(ap);
   ErrorF("##############################################\n\n");
}
#else /* #ifdef I830DEBUG */
void
I830DPRINTF_stub(const char *filename, int line, const char *function,
		 const char *fmt, ...)
{
   /* do nothing */
}
#endif /* #ifdef I830DEBUG */

/* Export I830 options to i830 driver where necessary */
const OptionInfoRec *
I830AvailableOptions(int chipid, int busid)
{
   int i;

   for (i = 0; I830PciChipsets[i].PCIid > 0; i++) {
      if (chipid == I830PciChipsets[i].PCIid)
	 return I830Options;
   }
   return NULL;
}

static Bool
I830GetRec(ScrnInfoPtr pScrn)
{
   I830Ptr pI830;

   if (pScrn->driverPrivate)
      return TRUE;
   pI830 = pScrn->driverPrivate = xnfcalloc(sizeof(I830Rec), 1);
   return TRUE;
}

static void
I830FreeRec(ScrnInfoPtr pScrn)
{
   I830Ptr pI830;

   if (!pScrn)
      return;
   if (!pScrn->driverPrivate)
      return;

   pI830 = I830PTR(pScrn);

   xfree(pScrn->driverPrivate);
   pScrn->driverPrivate = NULL;
}

static void
I830ProbeDDC(ScrnInfoPtr pScrn, int index)
{
   vbeInfoPtr pVbe;

   /* The vbe module gets loaded in PreInit(), so no need to load it here. */

   pVbe = VBEInit(NULL, index);
   ConfiguredMonitor = vbeDoEDID(pVbe, NULL);
}

static int
I830DetectMemory(ScrnInfoPtr pScrn)
{
   I830Ptr pI830 = I830PTR(pScrn);
#if !XSERVER_LIBPCIACCESS
   PCITAG bridge;
#endif
   uint16_t gmch_ctrl;
   int memsize = 0, gtt_size;
   int range;
#if 0
   VbeInfoBlock *vbeInfo;
#endif

#if XSERVER_LIBPCIACCESS
   struct pci_device *bridge = intel_host_bridge ();
   pci_device_cfg_read_u16(bridge, & gmch_ctrl, I830_GMCH_CTRL);
#else
   bridge = pciTag(0, 0, 0);		/* This is always the host bridge */
   gmch_ctrl = pciReadWord(bridge, I830_GMCH_CTRL);
#endif

   if (IS_I965G(pI830)) {
      /* The 965 may have a GTT that is actually larger than is necessary
       * to cover the aperture, so check the hardware's reporting of the
       * GTT size.
       */
      switch (INREG(PGETBL_CTL) & PGETBL_SIZE_MASK) {
      case PGETBL_SIZE_512KB:
	 gtt_size = 512;
	 break;
      case PGETBL_SIZE_256KB:
	 gtt_size = 256;
	 break;
      case PGETBL_SIZE_128KB:
	 gtt_size = 128;
	 break;
      case PGETBL_SIZE_1MB:
	 gtt_size = 1024;
	 break;
      case PGETBL_SIZE_2MB:
	 gtt_size = 2048;
	 break;
      case PGETBL_SIZE_1_5MB:
	 gtt_size = 1024 + 512;
	 break;
      default:
	 FatalError("Unknown GTT size value: %08x\n", (int)INREG(PGETBL_CTL));
      }
   } else if (IS_G33CLASS(pI830)) {
      /* G33's GTT size is detect in GMCH_CTRL */
      switch (gmch_ctrl & G33_PGETBL_SIZE_MASK) {
      case G33_PGETBL_SIZE_1M:
	 gtt_size = 1024;
	 break;
      case G33_PGETBL_SIZE_2M:
	 gtt_size = 2048;
	 break;
      default:
	 FatalError("Unknown GTT size value: %08x\n",
		    (int)(gmch_ctrl & G33_PGETBL_SIZE_MASK));
      }
   } else {
      /* Older chipsets only had GTT appropriately sized for the aperture. */
      gtt_size = pI830->FbMapSize / (1024*1024);
   }

   xf86DrvMsg(pScrn->scrnIndex, X_INFO, "detected %d kB GTT.\n", gtt_size);

   /* The stolen memory has the GTT at the top, and the 4KB popup below that.
    * Everything else can be freely used by the graphics driver.
    */
   range = gtt_size + 4;

   /* new 4 series hardware has seperate GTT stolen with GFX stolen */
   if (IS_G4X(pI830))
       range = 0;

   if (IS_I85X(pI830) || IS_I865G(pI830) || IS_I9XX(pI830)) {
      switch (gmch_ctrl & I855_GMCH_GMS_MASK) {
      case I855_GMCH_GMS_STOLEN_1M:
	 memsize = MB(1) - KB(range);
	 break;
      case I855_GMCH_GMS_STOLEN_4M:
	 memsize = MB(4) - KB(range);
	 break;
      case I855_GMCH_GMS_STOLEN_8M:
	 memsize = MB(8) - KB(range);
	 break;
      case I855_GMCH_GMS_STOLEN_16M:
	 memsize = MB(16) - KB(range);
	 break;
      case I855_GMCH_GMS_STOLEN_32M:
	 memsize = MB(32) - KB(range);
	 break;
      case I915G_GMCH_GMS_STOLEN_48M:
	 if (IS_I9XX(pI830))
	    memsize = MB(48) - KB(range);
	 break;
      case I915G_GMCH_GMS_STOLEN_64M:
	 if (IS_I9XX(pI830))
	    memsize = MB(64) - KB(range);
	 break;
      case G33_GMCH_GMS_STOLEN_128M:
	 if (IS_I9XX(pI830))
	     memsize = MB(128) - KB(range);
	 break;
      case G33_GMCH_GMS_STOLEN_256M:
	 if (IS_I9XX(pI830))
	     memsize = MB(256) - KB(range);
	 break;
      case INTEL_GMCH_GMS_STOLEN_96M:
	 if (IS_I9XX(pI830))
	     memsize = MB(96) - KB(range);
	 break;
      case INTEL_GMCH_GMS_STOLEN_160M:
	 if (IS_I9XX(pI830))
	     memsize = MB(160) - KB(range);
	 break;
      case INTEL_GMCH_GMS_STOLEN_224M:
	 if (IS_I9XX(pI830))
	     memsize = MB(224) - KB(range);
	 break;
      case INTEL_GMCH_GMS_STOLEN_352M:
	 if (IS_I9XX(pI830))
	     memsize = MB(352) - KB(range);
	 break;
      }
   } else {
      switch (gmch_ctrl & I830_GMCH_GMS_MASK) {
      case I830_GMCH_GMS_STOLEN_512:
	 memsize = KB(512) - KB(range);
	 break;
      case I830_GMCH_GMS_STOLEN_1024:
	 memsize = MB(1) - KB(range);
	 break;
      case I830_GMCH_GMS_STOLEN_8192:
	 memsize = MB(8) - KB(range);
	 break;
      case I830_GMCH_GMS_LOCAL:
	 memsize = 0;
	 xf86DrvMsg(pScrn->scrnIndex, X_WARNING,
		    "Local memory found, but won't be used.\n");
	 break;
      }
   }

#if 0
   /* And 64KB page aligned */
   memsize &= ~0xFFFF;
#endif

   if (memsize > 0) {
      xf86DrvMsg(pScrn->scrnIndex, X_INFO,
		 "detected %d kB stolen memory.\n", memsize / 1024);
   } else {
      xf86DrvMsg(pScrn->scrnIndex, X_INFO, "no video memory detected.\n");
   }

   return memsize;
}

static Bool
I830MapMMIO(ScrnInfoPtr pScrn)
{
#if XSERVER_LIBPCIACCESS
   int err;
   struct pci_device *device;
#else
   int mmioFlags;
#endif
   I830Ptr pI830 = I830PTR(pScrn);

#if XSERVER_LIBPCIACCESS
   device = pI830->PciInfo;
   err = pci_device_map_range (device,
			       pI830->MMIOAddr,
			       I810_REG_SIZE,
			       PCI_DEV_MAP_FLAG_WRITABLE,
			       (void **) &pI830->MMIOBase);
   if (err) 
   {
      xf86DrvMsg (pScrn->scrnIndex, X_ERROR,
		  "Unable to map mmio range. %s (%d)\n",
		  strerror (err), err);
      return FALSE;
   }
#else

#if !defined(__alpha__)
   mmioFlags = VIDMEM_MMIO | VIDMEM_READSIDEEFFECT;
#else
   mmioFlags = VIDMEM_MMIO | VIDMEM_READSIDEEFFECT | VIDMEM_SPARSE;
#endif

   pI830->MMIOBase = xf86MapPciMem(pScrn->scrnIndex, mmioFlags,
				   pI830->PciTag,
				   pI830->MMIOAddr, I810_REG_SIZE);
   if (!pI830->MMIOBase)
      return FALSE;
#endif

   /* Set up the GTT mapping for the various places it has been moved over
    * time.
    */
   if (IS_I9XX(pI830)) {
      uint32_t gttaddr;

      if (IS_I965G(pI830)) 
      {
	 if (IS_GM45(pI830) || IS_G4X(pI830)) {
	     gttaddr = pI830->MMIOAddr + MB(2);
	     pI830->GTTMapSize = MB(2);
	 } else {
	     gttaddr = pI830->MMIOAddr + KB(512);
	     pI830->GTTMapSize = KB(512);
	 }
      }
      else
      {
	 gttaddr = I810_MEMBASE(pI830->PciInfo, 3) & 0xFFFFFF00;
	 pI830->GTTMapSize = pI830->FbMapSize / 1024;
      }
#if XSERVER_LIBPCIACCESS
      err = pci_device_map_range (device,
				  gttaddr, pI830->GTTMapSize,
				  PCI_DEV_MAP_FLAG_WRITABLE,
				  (void **) &pI830->GTTBase);
      if (err)
      {
	 xf86DrvMsg (pScrn->scrnIndex, X_ERROR,
		     "Unable to map GTT range. %s (%d)\n",
		     strerror (err), err);
	 return FALSE;
      }
#else
      pI830->GTTBase = xf86MapPciMem(pScrn->scrnIndex, mmioFlags,
				     pI830->PciTag,
				     gttaddr, pI830->GTTMapSize);
      if (pI830->GTTBase == NULL)
	 return FALSE;
#endif
   } else {
      /* The GTT aperture on i830 is write-only.  We could probably map the
       * actual physical pages that back it, but leave it alone for now.
       */
      pI830->GTTBase = NULL;
      pI830->GTTMapSize = 0;
   }

   return TRUE;
}

static Bool
I830MapMem(ScrnInfoPtr pScrn)
{
   I830Ptr pI830 = I830PTR(pScrn);
   long i;
#if XSERVER_LIBPCIACCESS
   struct pci_device *const device = pI830->PciInfo;
   int err;
#endif

   for (i = 2; i < pI830->FbMapSize; i <<= 1) ;
   pI830->FbMapSize = i;

   if (!I830MapMMIO(pScrn))
      return FALSE;

#if XSERVER_LIBPCIACCESS
   err = pci_device_map_range (device, pI830->LinearAddr, pI830->FbMapSize,
			       PCI_DEV_MAP_FLAG_WRITABLE | PCI_DEV_MAP_FLAG_WRITE_COMBINE,
			       (void **) &pI830->FbBase);
    if (err)
	return FALSE;
#else
   pI830->FbBase = xf86MapPciMem(pScrn->scrnIndex, VIDMEM_FRAMEBUFFER,
				 pI830->PciTag,
				 pI830->LinearAddr, pI830->FbMapSize);
   if (!pI830->FbBase)
      return FALSE;
#endif

   if (I830IsPrimary(pScrn) && pI830->LpRing->mem != NULL) {
      pI830->LpRing->virtual_start =
	 pI830->FbBase + pI830->LpRing->mem->offset;
   }

   return TRUE;
}

static void
I830UnmapMMIO(ScrnInfoPtr pScrn)
{
   I830Ptr pI830 = I830PTR(pScrn);

#if XSERVER_LIBPCIACCESS
   pci_device_unmap_range (pI830->PciInfo, pI830->MMIOBase, I810_REG_SIZE);
#else
   xf86UnMapVidMem(pScrn->scrnIndex, (pointer) pI830->MMIOBase,
		   I810_REG_SIZE);
#endif
   pI830->MMIOBase = NULL;

   if (IS_I9XX(pI830)) {
#if XSERVER_LIBPCIACCESS
      pci_device_unmap_range (pI830->PciInfo, pI830->GTTBase, pI830->GTTMapSize);
#else
      xf86UnMapVidMem(pScrn->scrnIndex, pI830->GTTBase, pI830->GTTMapSize);
#endif
      pI830->GTTBase = NULL;
   }
}

static Bool
I830UnmapMem(ScrnInfoPtr pScrn)
{
   I830Ptr pI830 = I830PTR(pScrn);

#if XSERVER_LIBPCIACCESS
   pci_device_unmap_range (pI830->PciInfo, pI830->FbBase, pI830->FbMapSize);
#else
   xf86UnMapVidMem(pScrn->scrnIndex, (pointer) pI830->FbBase,
		   pI830->FbMapSize);
#endif
   pI830->FbBase = NULL;
   I830UnmapMMIO(pScrn);
   return TRUE;
}

static void
I830LoadPalette(ScrnInfoPtr pScrn, int numColors, int *indices,
		LOCO * colors, VisualPtr pVisual)
{
   xf86CrtcConfigPtr   xf86_config = XF86_CRTC_CONFIG_PTR(pScrn);
   int i,j, index;
   int p;
   uint16_t lut_r[256], lut_g[256], lut_b[256];

   DPRINTF(PFX, "I830LoadPalette: numColors: %d\n", numColors);

   for(p = 0; p < xf86_config->num_crtc; p++) {
      xf86CrtcPtr	   crtc = xf86_config->crtc[p];
      I830CrtcPrivatePtr   intel_crtc = crtc->driver_private;

      /* Initialize to the old lookup table values. */
      for (i = 0; i < 256; i++) {
	 lut_r[i] = intel_crtc->lut_r[i] << 8;
	 lut_g[i] = intel_crtc->lut_g[i] << 8;
	 lut_b[i] = intel_crtc->lut_b[i] << 8;
      }

      switch(pScrn->depth) {
      case 15:
	 for (i = 0; i < numColors; i++) {
	    index = indices[i];
	    for (j = 0; j < 8; j++) {
	       lut_r[index * 8 + j] = colors[index].red << 8;
	       lut_g[index * 8 + j] = colors[index].green << 8;
	       lut_b[index * 8 + j] = colors[index].blue << 8;
	    }
         }
	 break;
      case 16:
	 for (i = 0; i < numColors; i++) {
	    index = indices[i];

	    if (index <= 31) {
	       for (j = 0; j < 8; j++) {
		  lut_r[index * 8 + j] = colors[index].red << 8;
		  lut_b[index * 8 + j] = colors[index].blue << 8;
	       }
	    }

	    for (j = 0; j < 4; j++) {
	       lut_g[index * 4 + j] = colors[index].green << 8;
	    }
         }
        break;
      default:
	 for (i = 0; i < numColors; i++) {
	    index = indices[i];
	    lut_r[index] = colors[index].red << 8;
	    lut_g[index] = colors[index].green << 8;
	    lut_b[index] = colors[index].blue << 8;
	 }
	 break;
      }

      /* Make the change through RandR */
#ifdef RANDR_12_INTERFACE
      RRCrtcGammaSet(crtc->randr_crtc, lut_r, lut_g, lut_b);
#else
      crtc->funcs->gamma_set(crtc, lut_r, lut_g, lut_b, 256);
#endif
   }
}

static void
i830_update_front_offset(ScrnInfoPtr pScrn)
{
   ScreenPtr pScreen = pScrn->pScreen;
   I830Ptr pI830 = I830PTR(pScrn);

   /* Update buffer locations, which may have changed as a result of
    * i830_bind_all_memory().
    */
   pScrn->fbOffset = pI830->front_buffer->offset;

   /* If we are still in ScreenInit, there is no screen pixmap to be updated
    * yet.  We'll fix it up at CreateScreenResources.
    */
   if (!pI830->starting) {
      if (!pScreen->ModifyPixmapHeader(pScreen->GetScreenPixmap(pScreen),
				       -1, -1, -1, -1, -1,
				       (pointer)(pI830->FbBase +
						 pScrn->fbOffset)))
       FatalError("Couldn't adjust screen pixmap\n");
   }
}

/**
 * Adjust the screen pixmap for the current location of the front buffer.
 * This is done at EnterVT when buffers are bound as long as the resources
 * have already been created, but the first EnterVT happens before
 * CreateScreenResources.
 */
static Bool
i830CreateScreenResources(ScreenPtr pScreen)
{
   ScrnInfoPtr pScrn = xf86Screens[pScreen->myNum];
   I830Ptr pI830 = I830PTR(pScrn);

   pScreen->CreateScreenResources = pI830->CreateScreenResources;
   if (!(*pScreen->CreateScreenResources)(pScreen))
      return FALSE;

   i830_update_front_offset(pScrn);

   return TRUE;
}

int
i830_output_clones (ScrnInfoPtr pScrn, int type_mask)
{
    xf86CrtcConfigPtr	config = XF86_CRTC_CONFIG_PTR (pScrn);
    int			o;
    int			index_mask = 0;

    for (o = 0; o < config->num_output; o++)
    {
	xf86OutputPtr		output = config->output[o];
	I830OutputPrivatePtr	intel_output = output->driver_private;
	if (type_mask & (1 << intel_output->type))
	    index_mask |= (1 << o);
    }
    return index_mask;
}

/**
 * Set up the outputs according to what type of chip we are.
 *
 * Some outputs may not initialize, due to allocation failure or because a
 * controller chip isn't found.
 */
static void
I830SetupOutputs(ScrnInfoPtr pScrn)
{
   xf86CrtcConfigPtr	config = XF86_CRTC_CONFIG_PTR (pScrn);
   I830Ptr  pI830 = I830PTR(pScrn);
   int	    o, c;
   Bool	    lvds_detected = FALSE;

   /* everyone has at least a single analog output */
   i830_crt_init(pScrn);

   /* Set up integrated LVDS */
   if (IS_MOBILE(pI830) && !IS_I830(pI830))
      i830_lvds_init(pScrn);

   if (IS_I9XX(pI830)) {
      if (INREG(SDVOB) & SDVO_DETECTED) {
	 Bool found = i830_sdvo_init(pScrn, SDVOB);

	 if (!found && SUPPORTS_INTEGRATED_HDMI(pI830))
	    i830_hdmi_init(pScrn, SDVOB);
      }

      if (INREG(SDVOC) & SDVO_DETECTED) {
	 Bool found = i830_sdvo_init(pScrn, SDVOC);

	 if (!found && SUPPORTS_INTEGRATED_HDMI(pI830))
	    i830_hdmi_init(pScrn, SDVOC);
      }
   } else {
      i830_dvo_init(pScrn);
   }
   if (IS_I9XX(pI830) && IS_MOBILE(pI830))
      i830_tv_init(pScrn);
   
   for (o = 0; o < config->num_output; o++)
   {
      xf86OutputPtr	   output = config->output[o];
      I830OutputPrivatePtr intel_output = output->driver_private;
      int		   crtc_mask;

      if (intel_output->type == I830_OUTPUT_LVDS)
	  lvds_detected = TRUE;
      
      crtc_mask = 0;
      for (c = 0; c < config->num_crtc; c++)
      {
	 xf86CrtcPtr	      crtc = config->crtc[c];
	 I830CrtcPrivatePtr   intel_crtc = crtc->driver_private;

	 if (intel_output->pipe_mask & (1 << intel_crtc->pipe))
	    crtc_mask |= (1 << c);
      }
      output->possible_crtcs = crtc_mask;
      output->possible_clones = i830_output_clones (pScrn, intel_output->clone_mask);
   }
}

static void
i830_init_clock_gating(ScrnInfoPtr pScrn)
{
    I830Ptr pI830 = I830PTR(pScrn);

    /* Disable clock gating reported to work incorrectly according to the specs.
     */
    if (IS_GM45(pI830)) {
	OUTREG(RENCLK_GATE_D1, 0);
	OUTREG(RENCLK_GATE_D2, 0);
	OUTREG(RAMCLK_GATE_D, 0);
	OUTREG(DSPCLK_GATE_D, VRHUNIT_CLOCK_GATE_DISABLE |
	       OVRUNIT_CLOCK_GATE_DISABLE |
	       OVCUNIT_CLOCK_GATE_DISABLE);
    } else if (IS_I965GM(pI830)) {
	OUTREG(RENCLK_GATE_D1, I965_RCC_CLOCK_GATE_DISABLE);
	OUTREG(RENCLK_GATE_D2, 0);
	OUTREG(DSPCLK_GATE_D, 0);
	OUTREG(RAMCLK_GATE_D, 0);
	OUTREG16(DEUC, 0);
    } else if (IS_I965G(pI830)) {
	OUTREG(RENCLK_GATE_D1, I965_RCZ_CLOCK_GATE_DISABLE |
	       I965_RCC_CLOCK_GATE_DISABLE |
	       I965_RCPB_CLOCK_GATE_DISABLE |
	       I965_ISC_CLOCK_GATE_DISABLE |
	       I965_FBC_CLOCK_GATE_DISABLE);
	OUTREG(RENCLK_GATE_D2, 0);
    } else if (IS_I855(pI830) || IS_I865G(pI830)) {
	OUTREG(RENCLK_GATE_D1, SV_CLOCK_GATE_DISABLE);
    } else if (IS_I830(pI830)) {
	OUTREG(DSPCLK_GATE_D, OVRUNIT_CLOCK_GATE_DISABLE);
    }
}

static void
i830_init_bios_control(ScrnInfoPtr pScrn)
{
   I830Ptr pI830 = I830PTR(pScrn);

   /* Set "extended desktop" */
   OUTREG(SWF0, INREG(SWF0) | (1 << 21));

   /* Set "driver loaded",  "OS unknown", "APM 1.2" */
   OUTREG(SWF4, (INREG(SWF4) & ~((3 << 19) | (7 << 16))) |
		(1 << 23) | (2 << 16));
}

static int
I830LVDSPresent(ScrnInfoPtr pScrn)
{
   xf86CrtcConfigPtr config = XF86_CRTC_CONFIG_PTR (pScrn);
   int o, lvds_detected = FALSE;

   for (o = 0; o < config->num_output; o++) {
      xf86OutputPtr	   output = config->output[o];
      I830OutputPrivatePtr intel_output = output->driver_private;

      if (intel_output->type == I830_OUTPUT_LVDS)
	  lvds_detected = TRUE;
   }

   return lvds_detected;
}
/**
 * Setup the CRTCs
 */


static void 
I830PreInitDDC(ScrnInfoPtr pScrn)
{
   I830Ptr pI830 = I830PTR(pScrn);

   if (!xf86LoadSubModule(pScrn, "ddc")) {
      pI830->ddc2 = FALSE;
   } else {
      xf86LoaderReqSymLists(I810ddcSymbols, NULL);
      pI830->ddc2 = TRUE;
   }

   /* DDC can use I2C bus */
   /* Load I2C if we have the code to use it */
   if (pI830->ddc2) {
      if (xf86LoadSubModule(pScrn, "i2c")) {
	 xf86LoaderReqSymLists(I810i2cSymbols, NULL);

	 pI830->ddc2 = TRUE;
      } else {
	 pI830->ddc2 = FALSE;
      }
   }
}

static void
PreInitCleanup(ScrnInfoPtr pScrn)
{
   I830Ptr pI830 = I830PTR(pScrn);

   if (I830IsPrimary(pScrn)) {
      if (pI830->entityPrivate)
	 pI830->entityPrivate->pScrn_1 = NULL;
   } else {
      if (pI830->entityPrivate)
         pI830->entityPrivate->pScrn_2 = NULL;
   }
   if (pI830->MMIOBase)
      I830UnmapMMIO(pScrn);
   I830FreeRec(pScrn);
}

Bool
I830IsPrimary(ScrnInfoPtr pScrn)
{
   I830Ptr pI830 = I830PTR(pScrn);

   if (xf86IsEntityShared(pScrn->entityList[0])) {
	if (pI830->init == 0) return TRUE;
	else return FALSE;
   }

   return TRUE;
}

static Bool
i830_xf86crtc_resize (ScrnInfoPtr scrn, int width, int height)
{
    scrn->virtualX = width;
    scrn->virtualY = height;
    return TRUE;
}

static const xf86CrtcConfigFuncsRec i830_xf86crtc_config_funcs = {
    i830_xf86crtc_resize
};

#define HOTKEY_BIOS_SWITCH	0
#define HOTKEY_DRIVER_NOTIFY	1

/**
 * Controls the BIOS's behavior on hotkey switch.
 *
 * If the mode is HOTKEY_BIOS_SWITCH, the BIOS will be set to do a mode switch
 * on its own and update the state in the scratch register.
 * If the mode is HOTKEY_DRIVER_NOTIFY, the BIOS won't do a mode switch and
 * will just update the state to represent what it would have been switched to.
 */
static void
i830SetHotkeyControl(ScrnInfoPtr pScrn, int mode)
{
   I830Ptr pI830 = I830PTR(pScrn);
   uint8_t gr18;

   gr18 = pI830->readControl(pI830, GRX, 0x18);
   if (mode == HOTKEY_BIOS_SWITCH)
      gr18 &= ~HOTKEY_VBIOS_SWITCH_BLOCK;
   else
      gr18 |= HOTKEY_VBIOS_SWITCH_BLOCK;
   pI830->writeControl(pI830, GRX, 0x18, gr18);
}

static Bool
i830_detect_chipset(ScrnInfoPtr pScrn)
{
    I830Ptr pI830 = I830PTR(pScrn);
    MessageType from = X_PROBED;
    const char *chipname;
    uint32_t capid;
    int fb_bar, mmio_bar;

    switch (DEVICE_ID(pI830->PciInfo)) {
    case PCI_CHIP_I830_M:
	chipname = "830M";
	break;
    case PCI_CHIP_845_G:
	chipname = "845G";
	break;
    case PCI_CHIP_I855_GM:
	/* Check capid register to find the chipset variant */
#if XSERVER_LIBPCIACCESS
	pci_device_cfg_read_u32 (pI830->PciInfo, &capid, I85X_CAPID);
#else
	capid = pciReadLong (pI830->PciTag, I85X_CAPID);
#endif
	pI830->variant = (capid >> I85X_VARIANT_SHIFT) & I85X_VARIANT_MASK;
	switch (pI830->variant) {
	case I855_GM:
	    chipname = "855GM";
	    break;
	case I855_GME:
	    chipname = "855GME";
	    break;
	case I852_GM:
	    chipname = "852GM";
	    break;
	case I852_GME:
	    chipname = "852GME";
	    break;
	default:
	    xf86DrvMsg(pScrn->scrnIndex, X_INFO,
		       "Unknown 852GM/855GM variant: 0x%x)\n", pI830->variant);
	    chipname = "852GM/855GM (unknown variant)";
	    break;
	}
	break;
    case PCI_CHIP_I865_G:
	chipname = "865G";
	break;
    case PCI_CHIP_I915_G:
	chipname = "915G";
	break;
    case PCI_CHIP_E7221_G:
	chipname = "E7221 (i915)";
	break;
    case PCI_CHIP_I915_GM:
	chipname = "915GM";
	break;
    case PCI_CHIP_I945_G:
	chipname = "945G";
	break;
    case PCI_CHIP_I945_GM:
	chipname = "945GM";
	break;
    case PCI_CHIP_I945_GME:
	chipname = "945GME";
	break;
    case PCI_CHIP_I965_G:
	chipname = "965G";
	break;
    case PCI_CHIP_G35_G:
	chipname = "G35";
	break;
    case PCI_CHIP_I965_Q:
	chipname = "965Q";
	break;
    case PCI_CHIP_I946_GZ:
	chipname = "946GZ";
	break;
    case PCI_CHIP_I965_GM:
	chipname = "965GM";
	break;
    case PCI_CHIP_I965_GME:
	chipname = "965GME/GLE";
	break;
    case PCI_CHIP_G33_G:
	chipname = "G33";
	break;
    case PCI_CHIP_Q35_G:
	chipname = "Q35";
	break;
    case PCI_CHIP_Q33_G:
	chipname = "Q33";
	break;
    case PCI_CHIP_GM45_GM:
	chipname = "Mobile Intel® GM45 Express Chipset";
	break;
    case PCI_CHIP_IGD_E_G:
	chipname = "Intel Integrated Graphics Device";
	break;
    case PCI_CHIP_G45_G:
	chipname = "G45/G43";
	break;
    case PCI_CHIP_Q45_G:
	chipname = "Q45/Q43";
	break;
   default:
	chipname = "unknown chipset";
	break;
    }
    xf86DrvMsg(pScrn->scrnIndex, X_INFO,
	       "Integrated Graphics Chipset: Intel(R) %s\n", chipname);

    /* Set the Chipset and ChipRev, allowing config file entries to override. */
    if (pI830->pEnt->device->chipset && *pI830->pEnt->device->chipset) {
	pScrn->chipset = pI830->pEnt->device->chipset;
	from = X_CONFIG;
    } else if (pI830->pEnt->device->chipID >= 0) {
	pScrn->chipset = (char *)xf86TokenToString(I830Chipsets,
						   pI830->pEnt->device->chipID);
	from = X_CONFIG;
	xf86DrvMsg(pScrn->scrnIndex, X_CONFIG, "ChipID override: 0x%04X\n",
		   pI830->pEnt->device->chipID);
	DEVICE_ID(pI830->PciInfo) = pI830->pEnt->device->chipID;
    } else {
	from = X_PROBED;
	pScrn->chipset = (char *)xf86TokenToString(I830Chipsets,
						   DEVICE_ID(pI830->PciInfo));
    }

    if (pI830->pEnt->device->chipRev >= 0) {
	xf86DrvMsg(pScrn->scrnIndex, X_CONFIG, "ChipRev override: %d\n",
		   pI830->pEnt->device->chipRev);
    }

    xf86DrvMsg(pScrn->scrnIndex, from, "Chipset: \"%s\"\n",
	       (pScrn->chipset != NULL) ? pScrn->chipset : "Unknown i8xx");

    /* Now that we know the chipset, figure out the resource base addrs */
    if (IS_I9XX(pI830)) {
	fb_bar = 2;
	mmio_bar = 0;
    } else {
	fb_bar = 0;
	mmio_bar = 1;
    }

    if (pI830->pEnt->device->MemBase != 0) {
	pI830->LinearAddr = pI830->pEnt->device->MemBase;
	from = X_CONFIG;
    } else {
	pI830->LinearAddr = I810_MEMBASE (pI830->PciInfo, fb_bar);
	if (pI830->LinearAddr == 0) {
	    xf86DrvMsg(pScrn->scrnIndex, X_ERROR,
		       "No valid FB address in PCI config space\n");
	    PreInitCleanup(pScrn);
	    return FALSE;
	}
    }

    xf86DrvMsg(pScrn->scrnIndex, from, "Linear framebuffer at 0x%lX\n",
	       (unsigned long)pI830->LinearAddr);

    if (pI830->pEnt->device->IOBase != 0) {
	pI830->MMIOAddr = pI830->pEnt->device->IOBase;
	from = X_CONFIG;
    } else {
	pI830->MMIOAddr = I810_MEMBASE (pI830->PciInfo, mmio_bar);
	if (pI830->MMIOAddr == 0) {
	    xf86DrvMsg(pScrn->scrnIndex, X_ERROR,
		       "No valid MMIO address in PCI config space\n");
	    PreInitCleanup(pScrn);
	    return FALSE;
	}
    }

    xf86DrvMsg(pScrn->scrnIndex, from, "IO registers at addr 0x%lX\n",
	       (unsigned long)pI830->MMIOAddr);

    /* Now figure out mapsize on 8xx chips */
    if (IS_I830(pI830) || IS_845G(pI830)) {
#if XSERVER_LIBPCIACCESS
	uint16_t		gmch_ctrl;
	struct pci_device *bridge;

	bridge = intel_host_bridge ();
	pci_device_cfg_read_u16 (bridge, &gmch_ctrl, I830_GMCH_CTRL);
#else
	PCITAG bridge;
	uint16_t gmch_ctrl;

	bridge = pciTag(0, 0, 0);		/* This is always the host bridge */
	gmch_ctrl = pciReadWord(bridge, I830_GMCH_CTRL);
#endif
	if ((gmch_ctrl & I830_GMCH_MEM_MASK) == I830_GMCH_MEM_128M) {
	    pI830->FbMapSize = 0x8000000;
	} else {
	    pI830->FbMapSize = 0x4000000; /* 64MB - has this been tested ?? */
	}
    } else {
	if (IS_I9XX(pI830)) {
#if XSERVER_LIBPCIACCESS
	    pI830->FbMapSize = pI830->PciInfo->regions[fb_bar].size;
#else
	    pI830->FbMapSize = 1UL << pciGetBaseSize(pI830->PciTag, 2, TRUE,
						     NULL);
#endif
	} else {
	    /* 128MB aperture for later i8xx series. */
	    pI830->FbMapSize = 0x8000000;
	}
    }

    return TRUE;
}

static const char *accel_name[] = 
{
   "unspecified",
   "no",
   "XAA",
   "EXA",
   "UXA",
};

/**
 * This is called per zaphod head (so usually just once) to do initialization
 * before the Screen is created.
 *
 * This code generally covers probing, module loading, option handling
 * card mapping, and RandR setup.
 */
static Bool
I830PreInit(ScrnInfoPtr pScrn, int flags)
{
   xf86CrtcConfigPtr   xf86_config;
   vgaHWPtr hwp;
   I830Ptr pI830;
   MessageType from = X_PROBED;
   rgb defaultWeight = { 0, 0, 0 };
   EntityInfoPtr pEnt;
   I830EntPtr pI830Ent = NULL;					
   int flags24;
   int i;
   char *s;
   pointer pVBEModule = NULL;
   int num_pipe;
   int max_width, max_height;

   if (pScrn->numEntities != 1)
      return FALSE;

   /* Load int10 module */
   if (!xf86LoadSubModule(pScrn, "int10"))
      return FALSE;
   xf86LoaderReqSymLists(I810int10Symbols, NULL);

   /* Load vbe module */
   if (!(pVBEModule = xf86LoadSubModule(pScrn, "vbe")))
      return FALSE;
   xf86LoaderReqSymLists(I810vbeSymbols, NULL);

   pEnt = xf86GetEntityInfo(pScrn->entityList[0]);

   if (flags & PROBE_DETECT) {
      I830ProbeDDC(pScrn, pEnt->index);
      return TRUE;
   }

   /* The vgahw module should be loaded here when needed */
   if (!xf86LoadSubModule(pScrn, "vgahw"))
      return FALSE;
   xf86LoaderReqSymLists(I810vgahwSymbols, NULL);

   /* Allocate a vgaHWRec */
   if (!vgaHWGetHWRec(pScrn))
      return FALSE;

   /* Allocate driverPrivate */
   if (!I830GetRec(pScrn))
      return FALSE;

   pI830 = I830PTR(pScrn);
   pI830->SaveGeneration = -1;
   pI830->pEnt = pEnt;

   pScrn->displayWidth = 640; /* default it */

   if (pI830->pEnt->location.type != BUS_PCI)
      return FALSE;

   pI830->PciInfo = xf86GetPciInfoForEntity(pI830->pEnt->index);
#if !XSERVER_LIBPCIACCESS
   pI830->PciTag = pciTag(pI830->PciInfo->bus, pI830->PciInfo->device,
			  pI830->PciInfo->func);
#endif

    /* Allocate an entity private if necessary */
    if (xf86IsEntityShared(pScrn->entityList[0])) {
	pI830Ent = xf86GetEntityPrivate(pScrn->entityList[0],
					I830EntityIndex)->ptr;
        pI830->entityPrivate = pI830Ent;
    } else 
        pI830->entityPrivate = NULL;

   if (xf86RegisterResources(pI830->pEnt->index, NULL, ResNone)) {
      PreInitCleanup(pScrn);
      return FALSE;
   }

   if (xf86IsEntityShared(pScrn->entityList[0])) {
      if (xf86IsPrimInitDone(pScrn->entityList[0])) {
	 pI830->init = 1;

         if (!pI830Ent->pScrn_1) {
            xf86DrvMsg(pScrn->scrnIndex, X_ERROR,
 		 "Failed to setup second head due to primary head failure.\n");
	    return FALSE;
         }
      } else {
         xf86SetPrimInitDone(pScrn->entityList[0]);
	 pI830->init = 0;
      }
   }

   if (xf86IsEntityShared(pScrn->entityList[0])) {
      if (!I830IsPrimary(pScrn)) {
         pI830Ent->pScrn_2 = pScrn;
      } else {
         pI830Ent->pScrn_1 = pScrn;
         pI830Ent->pScrn_2 = NULL;
      }
   }

   pScrn->racMemFlags = RAC_FB | RAC_COLORMAP;
   pScrn->monitor = pScrn->confScreen->monitor;
   pScrn->progClock = TRUE;
   pScrn->rgbBits = 8;

   flags24 = Support32bppFb | PreferConvert24to32 | SupportConvert24to32;

   if (!xf86SetDepthBpp(pScrn, 0, 0, 0, flags24))
      return FALSE;

   switch (pScrn->depth) {
   case 8:
   case 15:
   case 16:
   case 24:
      break;
   default:
      xf86DrvMsg(pScrn->scrnIndex, X_ERROR,
		 "Given depth (%d) is not supported by I830 driver\n",
		 pScrn->depth);
      return FALSE;
   }
   xf86PrintDepthBpp(pScrn);

   if (!xf86SetWeight(pScrn, defaultWeight, defaultWeight))
      return FALSE;
   if (!xf86SetDefaultVisual(pScrn, -1))
      return FALSE;

   hwp = VGAHWPTR(pScrn);
   pI830->cpp = pScrn->bitsPerPixel / 8;

   pI830->preinit = TRUE;

   /* Process the options */
   xf86CollectOptions(pScrn, NULL);
   if (!(pI830->Options = xalloc(sizeof(I830Options))))
      return FALSE;
   memcpy(pI830->Options, I830Options, sizeof(I830Options));
   xf86ProcessOptions(pScrn->scrnIndex, pScrn->options, pI830->Options);

   if (xf86ReturnOptValBool(pI830->Options, OPTION_MODEDEBUG, FALSE)) {
      pI830->debug_modes = TRUE;
   } else {
      pI830->debug_modes = FALSE;
   }

   if (xf86ReturnOptValBool(pI830->Options, OPTION_LVDS24BITMODE, FALSE)) {
      pI830->lvds_24_bit_mode = TRUE;
   } else {
      pI830->lvds_24_bit_mode = FALSE;
   }

   if (xf86ReturnOptValBool(pI830->Options, OPTION_LVDSFIXEDMODE, TRUE)) {
      pI830->lvds_fixed_mode = TRUE;
   } else {
      pI830->lvds_fixed_mode = FALSE;
   }

   if (xf86ReturnOptValBool(pI830->Options, OPTION_FORCEENABLEPIPEA, FALSE))
       pI830->quirk_flag |= QUIRK_PIPEA_FORCE;

   /* We have to use PIO to probe, because we haven't mapped yet. */
   I830SetPIOAccess(pI830);

   if (!i830_detect_chipset(pScrn))
       return FALSE;

   /* check quirks */
   i830_fixup_devices(pScrn);

   /* Allocate an xf86CrtcConfig */
   xf86CrtcConfigInit (pScrn, &i830_xf86crtc_config_funcs);
   xf86_config = XF86_CRTC_CONFIG_PTR(pScrn);

   /* See i830_exa.c comments for why we limit the framebuffer size like this.
    */
   if (IS_I965G(pI830)) {
      max_width = 8192;
      max_height = 8192;
   } else {
      max_width = 2048;
      max_height = 2048;
   }
   xf86CrtcSetSizeRange (pScrn, 320, 200, max_width, max_height);

   /* Some of the probing needs MMIO access, so map it here. */
   I830MapMMIO(pScrn);

   if (pI830->debug_modes) {
      xf86DrvMsg(pScrn->scrnIndex, X_INFO, "Hardware state on X startup:\n");
      i830DumpRegs (pScrn);
   }

   i830TakeRegSnapshot(pScrn);

   if (DEVICE_ID(pI830->PciInfo) == PCI_CHIP_E7221_G)
      num_pipe = 1;
   else
   if (IS_MOBILE(pI830) || IS_I9XX(pI830))
      num_pipe = 2;
   else
      num_pipe = 1;
   xf86DrvMsg(pScrn->scrnIndex, X_INFO, "%d display pipe%s available.\n",
	      num_pipe, num_pipe > 1 ? "s" : "");

   if (xf86ReturnOptValBool(pI830->Options, OPTION_NOACCEL, FALSE)) {
      pI830->accel = ACCEL_NONE;
   }

   /*
    * The ugliness below:
    * If either XAA or EXA (exclusive) is compiled in, default to it.
    * 
    * If both are compiled in, and the user didn't specify noAccel, use the
    * config option AccelMethod to determine which to use, defaulting to EXA
    * if none is specified, or if the string was unrecognized.
    *
    * All this *could* go away if we removed XAA support from this driver,
    * for example. :)
    */
   if (pI830->accel == ACCEL_UNINIT) {
      pI830->accel = ACCEL_NONE;
#ifdef I830_USE_XAA
      pI830->accel = ACCEL_XAA;
#endif
#ifdef I830_USE_EXA
      pI830->accel = ACCEL_EXA;
#endif
#ifdef I830_USE_UXA
      pI830->accel = ACCEL_UXA;
#endif
#if I830_USE_XAA + I830_USE_EXA + I830_USE_UXA >= 2
       from = X_DEFAULT;
       if ((s = (char *)xf86GetOptValString(pI830->Options,
					    OPTION_ACCELMETHOD))) {
	   if (!xf86NameCmp(s, "EXA")) {
	       from = X_CONFIG;
	       pI830->accel = ACCEL_EXA;
	   }
	   else if (!xf86NameCmp(s, "XAA")) {
	       from = X_CONFIG;
	       pI830->accel = ACCEL_XAA;
	   }
	   else if (!xf86NameCmp(s, "UXA")) {
	       from = X_CONFIG;
	       pI830->accel = ACCEL_UXA;
	   }
       }
#endif
   }
   xf86DrvMsg(pScrn->scrnIndex, from, "Using %s acceleration\n",
	      accel_name[pI830->accel]);

   if (xf86ReturnOptValBool(pI830->Options, OPTION_SW_CURSOR, FALSE)) {
      pI830->SWCursor = TRUE;
   }

   pI830->directRenderingDisabled =
	!xf86ReturnOptValBool(pI830->Options, OPTION_DRI, TRUE);

#ifdef XF86DRI
   if (!pI830->directRenderingDisabled) {
      if (pI830->accel == ACCEL_NONE || pI830->SWCursor) {
	 xf86DrvMsg(pScrn->scrnIndex, X_CONFIG, "DRI is disabled because it "
		    "needs HW cursor and 2D acceleration.\n");
	 pI830->directRenderingDisabled = TRUE;
      } else if (pScrn->depth != 16 && pScrn->depth != 24) {
	 xf86DrvMsg(pScrn->scrnIndex, X_CONFIG, "DRI is disabled because it "
		    "runs only at depths 16 and 24.\n");
	 pI830->directRenderingDisabled = TRUE;
      }

      if (!pI830->directRenderingDisabled) {
	 pI830->allocate_classic_textures = TRUE;

	 from = X_PROBED;

#ifdef XF86DRI
	 if (!IS_I965G(pI830)) {
	    Bool tmp;

	    if (xf86GetOptValBool(pI830->Options,
				  OPTION_INTELTEXPOOL, &tmp)) {
	       from = X_CONFIG;
	       if (!tmp)
		  pI830->allocate_classic_textures = FALSE;
	    }
	 }
#endif
      }
   } 
   
#endif

   I830PreInitDDC(pScrn);
   for (i = 0; i < num_pipe; i++) {
       i830_crtc_init(pScrn, i);
   }
   I830SetupOutputs(pScrn);

   SaveHWState(pScrn);
   if (!xf86InitialConfiguration (pScrn, FALSE))
   {
      xf86DrvMsg(pScrn->scrnIndex, X_ERROR, "No valid modes.\n");
      RestoreHWState(pScrn);
      PreInitCleanup(pScrn);
      return FALSE;
   }
   RestoreHWState(pScrn);

   /* XXX This should go away, replaced by xf86Crtc.c support for it */
   pI830->rotation = RR_Rotate_0;

   /*
    * Let's setup the mobile systems to check the lid status
    */
   if (IS_MOBILE(pI830)) {
      pI830->checkDevices = TRUE;

      if (!xf86ReturnOptValBool(pI830->Options, OPTION_CHECKDEVICES, TRUE)) {
         pI830->checkDevices = FALSE;
         xf86DrvMsg(pScrn->scrnIndex, X_INFO, "Monitoring connected displays disabled\n");
      } else
      if (pI830->entityPrivate && !I830IsPrimary(pScrn) &&
          !I830PTR(pI830->entityPrivate->pScrn_1)->checkDevices) {
         /* If checklid is off, on the primary head, then 
          * turn it off on the secondary*/
         xf86DrvMsg(pScrn->scrnIndex, X_INFO, "Monitoring connected displays disabled\n");
         pI830->checkDevices = FALSE;
      } else
         xf86DrvMsg(pScrn->scrnIndex, X_INFO, "Monitoring connected displays enabled\n");
   } else
      pI830->checkDevices = FALSE;

   pI830->stolen_size = I830DetectMemory(pScrn);

   pI830->XvDisabled =
	!xf86ReturnOptValBool(pI830->Options, OPTION_XVIDEO, TRUE);

#ifdef I830_XV
   if (xf86GetOptValInteger(pI830->Options, OPTION_VIDEO_KEY,
			    &(pI830->colorKey))) {
      from = X_CONFIG;
   } else if (xf86GetOptValInteger(pI830->Options, OPTION_COLOR_KEY,
			    &(pI830->colorKey))) {
      from = X_CONFIG;
   } else {
      pI830->colorKey = (1 << pScrn->offset.red) |
			(1 << pScrn->offset.green) |
			(((pScrn->mask.blue >> pScrn->offset.blue) - 1) <<
			 pScrn->offset.blue);
      from = X_DEFAULT;
   }
   xf86DrvMsg(pScrn->scrnIndex, from, "video overlay key set to 0x%x\n",
	      pI830->colorKey);
#endif

#ifdef XF86DRI
   pI830->allowPageFlip = FALSE;
   from = (!pI830->directRenderingDisabled &&
	   xf86GetOptValBool(pI830->Options, OPTION_PAGEFLIP,
			     &pI830->allowPageFlip)) ? X_CONFIG : X_DEFAULT;

   xf86DrvMsg(pScrn->scrnIndex, from, "Will%s try to enable page flipping\n",
	      pI830->allowPageFlip ? "" : " not");
#endif

#ifdef XF86DRI
   pI830->TripleBuffer = FALSE;
   from =  (!pI830->directRenderingDisabled &&
	    xf86GetOptValBool(pI830->Options, OPTION_TRIPLEBUFFER,
			      &pI830->TripleBuffer)) ? X_CONFIG : X_DEFAULT;

   xf86DrvMsg(pScrn->scrnIndex, from, "Triple buffering %sabled\n",
	      pI830->TripleBuffer ? "en" : "dis");
#endif

#ifdef INTEL_XVMC
   pI830->XvMCEnabled = FALSE;
   from =  (!pI830->directRenderingDisabled &&
	    xf86GetOptValBool(pI830->Options, OPTION_XVMC,
			      &pI830->XvMCEnabled)) ? X_CONFIG : X_DEFAULT;
   xf86DrvMsg(pScrn->scrnIndex, from, "Intel XvMC decoder %sabled\n",
	   pI830->XvMCEnabled ? "en" : "dis");
#endif

   /*
    * If the driver can do gamma correction, it should call xf86SetGamma() here.
    */

   {
      Gamma zeros = { 0.0, 0.0, 0.0 };

      if (!xf86SetGamma(pScrn, zeros)) {
         PreInitCleanup(pScrn);
	 return FALSE;
      }
   }

   /* Check if the HW cursor needs physical address. */
   if (IS_MOBILE(pI830) || IS_I9XX(pI830))
      pI830->CursorNeedsPhysical = TRUE;
   else
      pI830->CursorNeedsPhysical = FALSE;

   if (IS_I965G(pI830) || IS_G33CLASS(pI830))
      pI830->CursorNeedsPhysical = FALSE;

   /*
    * XXX If we knew the pre-initialised GTT format for certain, we could
    * probably figure out the physical address even in the StolenOnly case.
    */
   if (!I830IsPrimary(pScrn)) {
        I830Ptr pI8301 = I830PTR(pI830->entityPrivate->pScrn_1);
	if (!pI8301->SWCursor) {
          xf86DrvMsg(pScrn->scrnIndex, X_PROBED,
		 "Using HW Cursor because it's enabled on primary head.\n");
          pI830->SWCursor = FALSE;
        }
   } else 
   if (pI830->StolenOnly && pI830->CursorNeedsPhysical && !pI830->SWCursor) {
      xf86DrvMsg(pScrn->scrnIndex, X_PROBED,
		 "HW Cursor disabled because it needs agpgart memory.\n");
      pI830->SWCursor = TRUE;
   }

   if (pScrn->modes == NULL) {
      xf86DrvMsg(pScrn->scrnIndex, X_ERROR, "No modes.\n");
      PreInitCleanup(pScrn);
      return FALSE;
   }
   pScrn->currentMode = pScrn->modes;

   if (!IS_I965G(pI830) && pScrn->virtualY > 2048) {
      xf86DrvMsg(pScrn->scrnIndex, X_ERROR, "Cannot support > 2048 vertical lines. disabling acceleration.\n");
      pI830->accel = ACCEL_NONE;
   }

   /* Set display resolution */
   xf86SetDpi(pScrn, 0, 0);

   /* Load the required sub modules */
   if (!xf86LoadSubModule(pScrn, "fb")) {
      PreInitCleanup(pScrn);
      return FALSE;
   }

   xf86LoaderReqSymLists(I810fbSymbols, NULL);

   switch (pI830->accel) {
#ifdef I830_USE_XAA
   case ACCEL_XAA:
      if (!xf86LoadSubModule(pScrn, "xaa")) {
	 PreInitCleanup(pScrn);
	 return FALSE;
      }
      xf86LoaderReqSymLists(I810xaaSymbols, NULL);
      break;
#endif

#ifdef I830_USE_EXA
   case ACCEL_EXA: {
      XF86ModReqInfo req;
      int errmaj, errmin;

      memset(&req, 0, sizeof(req));
      req.majorversion = 2;
#if EXA_VERSION_MINOR >= 2
      req.minorversion = 2;
#else
      req.minorversion = 1;
#endif
      if (!LoadSubModule(pScrn->module, "exa", NULL, NULL, NULL, &req,
		&errmaj, &errmin)) {
	 LoaderErrorMsg(NULL, "exa", errmaj, errmin);
	 PreInitCleanup(pScrn);
	 return FALSE;
      }
      xf86LoaderReqSymLists(I830exaSymbols, NULL);
      break;
   }
#endif
   default:
      break;
   }
   if (!pI830->SWCursor) {
      if (!xf86LoadSubModule(pScrn, "ramdac")) {
	 PreInitCleanup(pScrn);
	 return FALSE;
      }
      xf86LoaderReqSymLists(I810ramdacSymbols, NULL);
   }

   i830CompareRegsToSnapshot(pScrn, "After PreInit");

   I830UnmapMMIO(pScrn);

   /*  We won't be using the VGA access after the probe. */
   I830SetMMIOAccess(pI830);
   xf86SetOperatingState(resVgaIo, pI830->pEnt->index, ResUnusedOpr);
   xf86SetOperatingState(resVgaMem, pI830->pEnt->index, ResDisableOpr);

#if 0
   if (I830IsPrimary(pScrn)) {
      vbeFree(pI830->pVbe);
   }
   pI830->pVbe = NULL;
#endif

#if defined(XF86DRI)
   /* Load the dri module if requested. */
   if (xf86ReturnOptValBool(pI830->Options, OPTION_DRI, FALSE) &&
       !pI830->directRenderingDisabled) {
      if (xf86LoadSubModule(pScrn, "dri")) {
	 xf86LoaderReqSymLists(I810driSymbols, I810drmSymbols, NULL);
      }
   }
#endif

   pI830->preinit = FALSE;

   return TRUE;
}

/*
 * Reset registers that it doesn't make sense to save/restore to a sane state.
 * This is basically the ring buffer and fence registers.  Restoring these
 * doesn't make sense without restoring GTT mappings.  This is something that
 * whoever gets control next should do.
 */
static void
i830_stop_ring(ScrnInfoPtr pScrn, Bool flush)
{
   I830Ptr pI830 = I830PTR(pScrn);
   unsigned long temp;

   DPRINTF(PFX, "ResetState: flush is %s\n", BOOLTOSTRING(flush));

   if (!I830IsPrimary(pScrn)) return;

   if (pI830->entityPrivate)
      pI830->entityPrivate->RingRunning = 0;

   /* Flush the ring buffer (if enabled), then disable it. */
   if (pI830->accel != ACCEL_NONE) {
      temp = INREG(LP_RING + RING_LEN);
      if (temp & RING_VALID) {
	 i830_refresh_ring(pScrn);
	 i830_wait_ring_idle(pScrn);
      }

      OUTREG(LP_RING + RING_LEN, 0);
      OUTREG(LP_RING + RING_HEAD, 0);
      OUTREG(LP_RING + RING_TAIL, 0);
      OUTREG(LP_RING + RING_START, 0);
   }
}

static void
i830_start_ring(ScrnInfoPtr pScrn)
{
   I830Ptr pI830 = I830PTR(pScrn);
   unsigned int itemp;

   DPRINTF(PFX, "SetRingRegs\n");

   if (pI830->accel == ACCEL_NONE)
      return;

   if (!I830IsPrimary(pScrn)) return;

   if (pI830->entityPrivate)
      pI830->entityPrivate->RingRunning = 1;

   OUTREG(LP_RING + RING_LEN, 0);
   OUTREG(LP_RING + RING_TAIL, 0);
   OUTREG(LP_RING + RING_HEAD, 0);

   assert((pI830->LpRing->mem->offset & I830_RING_START_MASK) ==
	   pI830->LpRing->mem->offset);

   /* Don't care about the old value.  Reserved bits must be zero anyway. */
   itemp = pI830->LpRing->mem->offset;
   OUTREG(LP_RING + RING_START, itemp);

   if (((pI830->LpRing->mem->size - 4096) & I830_RING_NR_PAGES) !=
       pI830->LpRing->mem->size - 4096) {
      xf86DrvMsg(pScrn->scrnIndex, X_ERROR,
		 "I830SetRingRegs: Ring buffer size - 4096 (%lx) violates its "
		 "mask (%x)\n", pI830->LpRing->mem->size - 4096,
		 I830_RING_NR_PAGES);
   }
   /* Don't care about the old value.  Reserved bits must be zero anyway. */
   itemp = (pI830->LpRing->mem->size - 4096) & I830_RING_NR_PAGES;
   itemp |= (RING_NO_REPORT | RING_VALID);
   OUTREG(LP_RING + RING_LEN, itemp);
   i830_refresh_ring(pScrn);
}

void
i830_refresh_ring(ScrnInfoPtr pScrn)
{
   I830Ptr pI830 = I830PTR(pScrn);

   /* If we're reaching RefreshRing as a result of grabbing the DRI lock
    * before we've set up the ringbuffer, don't bother.
    */
   if (pI830->LpRing->mem == NULL)
       return;

   pI830->LpRing->head = INREG(LP_RING + RING_HEAD) & I830_HEAD_MASK;
   pI830->LpRing->tail = INREG(LP_RING + RING_TAIL);
   pI830->LpRing->space = pI830->LpRing->head - (pI830->LpRing->tail + 8);
   if (pI830->LpRing->space < 0)
      pI830->LpRing->space += pI830->LpRing->mem->size;
   i830MarkSync(pScrn);
}

enum pipe {
    PIPE_A = 0,
    PIPE_B,
};

static Bool
i830_pipe_enabled(I830Ptr pI830, enum pipe pipe)
{
    if (pipe == PIPE_A)
	return (INREG(PIPEACONF) & PIPEACONF_ENABLE);
    else
	return (INREG(PIPEBCONF) & PIPEBCONF_ENABLE);
}

static void
i830_save_palette(I830Ptr pI830, enum pipe pipe)
{
    int i;

    if (!i830_pipe_enabled(pI830, pipe))
	return;

    for(i= 0; i < 256; i++) {
	if (pipe == PIPE_A)
	    pI830->savePaletteA[i] = INREG(PALETTE_A + (i << 2));
	else
	    pI830->savePaletteB[i] = INREG(PALETTE_B + (i << 2));
    }
}

static void
i830_restore_palette(I830Ptr pI830, enum pipe pipe)
{
    int i;

    if (!i830_pipe_enabled(pI830, pipe))
	return;

    for(i= 0; i < 256; i++) {
	if (pipe == PIPE_A)
	    OUTREG(PALETTE_A + (i << 2), pI830->savePaletteA[i]);
	else
	    OUTREG(PALETTE_B + (i << 2), pI830->savePaletteB[i]);
    }
}

static Bool
SaveHWState(ScrnInfoPtr pScrn)
{
   xf86CrtcConfigPtr   xf86_config = XF86_CRTC_CONFIG_PTR(pScrn);
   I830Ptr pI830 = I830PTR(pScrn);
   vgaHWPtr hwp = VGAHWPTR(pScrn);
   vgaRegPtr vgaReg = &hwp->SavedReg;
   int i;

   if (pI830->fb_compression) {
       pI830->saveFBC_CFB_BASE = INREG(FBC_CFB_BASE);
       pI830->saveFBC_LL_BASE = INREG(FBC_LL_BASE);
       pI830->saveFBC_CONTROL2 = INREG(FBC_CONTROL2);
       pI830->saveFBC_CONTROL = INREG(FBC_CONTROL);
       pI830->saveFBC_FENCE_OFF = INREG(FBC_FENCE_OFF);
   }

   /* Save video mode information for native mode-setting. */
   if (!DSPARB_HWCONTROL(pI830))
       pI830->saveDSPARB = INREG(DSPARB);

   pI830->saveDSPACNTR = INREG(DSPACNTR);
   pI830->savePIPEACONF = INREG(PIPEACONF);
   pI830->savePIPEASRC = INREG(PIPEASRC);
   pI830->saveFPA0 = INREG(FPA0);
   pI830->saveFPA1 = INREG(FPA1);
   pI830->saveDPLL_A = INREG(DPLL_A);
   if (IS_I965G(pI830))
      pI830->saveDPLL_A_MD = INREG(DPLL_A_MD);
   pI830->saveHTOTAL_A = INREG(HTOTAL_A);
   pI830->saveHBLANK_A = INREG(HBLANK_A);
   pI830->saveHSYNC_A = INREG(HSYNC_A);
   pI830->saveVTOTAL_A = INREG(VTOTAL_A);
   pI830->saveVBLANK_A = INREG(VBLANK_A);
   pI830->saveVSYNC_A = INREG(VSYNC_A);
   pI830->saveBCLRPAT_A = INREG(BCLRPAT_A);
   pI830->saveDSPASTRIDE = INREG(DSPASTRIDE);
   pI830->saveDSPASIZE = INREG(DSPASIZE);
   pI830->saveDSPAPOS = INREG(DSPAPOS);
   pI830->saveDSPABASE = INREG(DSPABASE);

   i830_save_palette(pI830, PIPE_A);

   if(xf86_config->num_crtc == 2) {
      pI830->savePIPEBCONF = INREG(PIPEBCONF);
      pI830->savePIPEBSRC = INREG(PIPEBSRC);
      pI830->saveDSPBCNTR = INREG(DSPBCNTR);
      pI830->saveFPB0 = INREG(FPB0);
      pI830->saveFPB1 = INREG(FPB1);
      pI830->saveDPLL_B = INREG(DPLL_B);
      if (IS_I965G(pI830))
	 pI830->saveDPLL_B_MD = INREG(DPLL_B_MD);
      pI830->saveHTOTAL_B = INREG(HTOTAL_B);
      pI830->saveHBLANK_B = INREG(HBLANK_B);
      pI830->saveHSYNC_B = INREG(HSYNC_B);
      pI830->saveVTOTAL_B = INREG(VTOTAL_B);
      pI830->saveVBLANK_B = INREG(VBLANK_B);
      pI830->saveVSYNC_B = INREG(VSYNC_B);
      pI830->saveBCLRPAT_B = INREG(BCLRPAT_B);
      pI830->saveDSPBSTRIDE = INREG(DSPBSTRIDE);
      pI830->saveDSPBSIZE = INREG(DSPBSIZE);
      pI830->saveDSPBPOS = INREG(DSPBPOS);
      pI830->saveDSPBBASE = INREG(DSPBBASE);

      i830_save_palette(pI830, PIPE_B);
   }

   if (IS_I965G(pI830)) {
      pI830->saveDSPASURF = INREG(DSPASURF);
      pI830->saveDSPBSURF = INREG(DSPBSURF);
      pI830->saveDSPATILEOFF = INREG(DSPATILEOFF);
      pI830->saveDSPBTILEOFF = INREG(DSPBTILEOFF);
   }

   pI830->saveVCLK_DIVISOR_VGA0 = INREG(VCLK_DIVISOR_VGA0);
   pI830->saveVCLK_DIVISOR_VGA1 = INREG(VCLK_DIVISOR_VGA1);
   pI830->saveVCLK_POST_DIV = INREG(VCLK_POST_DIV);
   pI830->saveVGACNTRL = INREG(VGACNTRL);

   pI830->saveCURSOR_A_CONTROL = INREG(CURSOR_A_CONTROL);
   pI830->saveCURSOR_A_POSITION = INREG(CURSOR_A_POSITION);
   pI830->saveCURSOR_A_BASE = INREG(CURSOR_A_BASE);
   pI830->saveCURSOR_B_CONTROL = INREG(CURSOR_B_CONTROL);
   pI830->saveCURSOR_B_POSITION = INREG(CURSOR_B_POSITION);
   pI830->saveCURSOR_B_BASE = INREG(CURSOR_B_BASE);

   for(i = 0; i < 7; i++) {
      pI830->saveSWF[i] = INREG(SWF0 + (i << 2));
      pI830->saveSWF[i+7] = INREG(SWF00 + (i << 2));
   }
   pI830->saveSWF[14] = INREG(SWF30);
   pI830->saveSWF[15] = INREG(SWF31);
   pI830->saveSWF[16] = INREG(SWF32);

   pI830->saveDSPCLK_GATE_D = INREG(DSPCLK_GATE_D);
   pI830->saveRENCLK_GATE_D1 = INREG(RENCLK_GATE_D1);

   if (IS_I965G(pI830)) {
      pI830->saveRENCLK_GATE_D2 = INREG(RENCLK_GATE_D2);
      pI830->saveRAMCLK_GATE_D = INREG(RAMCLK_GATE_D);
   }

   if (IS_I965GM(pI830) || IS_GM45(pI830))
      pI830->savePWRCTXA = INREG(PWRCTXA);

   if (IS_MOBILE(pI830) && !IS_I830(pI830))
      pI830->saveLVDS = INREG(LVDS);
   pI830->savePFIT_CONTROL = INREG(PFIT_CONTROL);

   for (i = 0; i < xf86_config->num_output; i++) {
      xf86OutputPtr   output = xf86_config->output[i];
      if (output->funcs->save)
	 (*output->funcs->save) (output);
   }

   vgaHWUnlock(hwp);
   vgaHWSave(pScrn, vgaReg, VGA_SR_FONTS);

   return TRUE;
}

/* Wait for the PLL to settle down after programming */
static void
i830_dpll_settle(void)
{
    usleep(10000); /* 10 ms *should* be plenty */
}

static Bool
RestoreHWState(ScrnInfoPtr pScrn)
{
   xf86CrtcConfigPtr   xf86_config = XF86_CRTC_CONFIG_PTR(pScrn);
   I830Ptr pI830 = I830PTR(pScrn);
   vgaHWPtr hwp = VGAHWPTR(pScrn);
   vgaRegPtr vgaReg = &hwp->SavedReg;
   int i;

   DPRINTF(PFX, "RestoreHWState\n");

#ifdef XF86DRI
   I830DRISetVBlankInterrupt (pScrn, FALSE);
#endif
   /* Disable outputs */
   for (i = 0; i < xf86_config->num_output; i++) {
      xf86OutputPtr   output = xf86_config->output[i];
      output->funcs->dpms(output, DPMSModeOff);
   }
   i830WaitForVblank(pScrn);
   
   /* Disable pipes */
   for (i = 0; i < xf86_config->num_crtc; i++) {
      xf86CrtcPtr crtc = xf86_config->crtc[i];
      crtc->funcs->dpms(crtc, DPMSModeOff);
   }
   i830WaitForVblank(pScrn);

   if (IS_MOBILE(pI830) && !IS_I830(pI830))
      OUTREG(LVDS, pI830->saveLVDS);

   if (!IS_I830(pI830) && !IS_845G(pI830))
     OUTREG(PFIT_CONTROL, pI830->savePFIT_CONTROL);

   if (!DSPARB_HWCONTROL(pI830))
       OUTREG(DSPARB, pI830->saveDSPARB);

   OUTREG(DSPCLK_GATE_D, pI830->saveDSPCLK_GATE_D);
   OUTREG(RENCLK_GATE_D1, pI830->saveRENCLK_GATE_D1);

   if (IS_I965G(pI830)) {
      OUTREG(RENCLK_GATE_D2, pI830->saveRENCLK_GATE_D2);
      OUTREG(RAMCLK_GATE_D, pI830->saveRAMCLK_GATE_D);
   }

   if (IS_I965GM(pI830) || IS_GM45(pI830))
      OUTREG(PWRCTXA, pI830->savePWRCTXA);

   /*
    * Pipe regs
    * To restore the saved state, we first need to program the PLL regs,
    * followed by the pipe configuration and finally the display plane
    * configuration.  The VGA registers can program one, both or neither
    * of the PLL regs, depending on their VGA_MOD_DIS bit value.
    */

   /*
    * Since either or both pipes may use the VGA clocks, make sure the
    * regs are valid.
    */
   OUTREG(VCLK_DIVISOR_VGA0, pI830->saveVCLK_DIVISOR_VGA0);
   OUTREG(VCLK_DIVISOR_VGA1, pI830->saveVCLK_DIVISOR_VGA1);
   OUTREG(VCLK_POST_DIV, pI830->saveVCLK_POST_DIV);

   /* If the pipe A PLL is active, we can restore the pipe & plane config */
   if (pI830->saveDPLL_A & DPLL_VCO_ENABLE)
   {
      OUTREG(DPLL_A, pI830->saveDPLL_A & ~DPLL_VCO_ENABLE);
      usleep(150);
   }
   OUTREG(FPA0, pI830->saveFPA0);
   OUTREG(FPA1, pI830->saveFPA1);
   OUTREG(DPLL_A, pI830->saveDPLL_A);
   i830_dpll_settle();
   if (IS_I965G(pI830))
      OUTREG(DPLL_A_MD, pI830->saveDPLL_A_MD);
   else
      OUTREG(DPLL_A, pI830->saveDPLL_A);
   i830_dpll_settle();

   /* Restore mode config */
   OUTREG(HTOTAL_A, pI830->saveHTOTAL_A);
   OUTREG(HBLANK_A, pI830->saveHBLANK_A);
   OUTREG(HSYNC_A, pI830->saveHSYNC_A);
   OUTREG(VTOTAL_A, pI830->saveVTOTAL_A);
   OUTREG(VBLANK_A, pI830->saveVBLANK_A);
   OUTREG(VSYNC_A, pI830->saveVSYNC_A);
   OUTREG(BCLRPAT_A, pI830->saveBCLRPAT_A);
   
   OUTREG(DSPASTRIDE, pI830->saveDSPASTRIDE);
   OUTREG(DSPASIZE, pI830->saveDSPASIZE);
   OUTREG(DSPAPOS, pI830->saveDSPAPOS);
   OUTREG(PIPEASRC, pI830->savePIPEASRC);
   OUTREG(DSPABASE, pI830->saveDSPABASE);
   if (IS_I965G(pI830))
   {
      OUTREG(DSPASURF, pI830->saveDSPASURF);
      OUTREG(DSPATILEOFF, pI830->saveDSPATILEOFF);
   }

   OUTREG(PIPEACONF, pI830->savePIPEACONF);
   i830WaitForVblank(pScrn);

   /*
    * Program Pipe A's plane
    * The corresponding display plane may be disabled, and should only be
    * enabled if pipe A is actually on (otherwise we have a bug in the initial
    * state).
    */
   if ((pI830->saveDSPACNTR & DISPPLANE_SEL_PIPE_MASK) ==
       DISPPLANE_SEL_PIPE_A) {
       OUTREG(DSPACNTR, pI830->saveDSPACNTR);
       OUTREG(DSPABASE, INREG(DSPABASE));
       i830WaitForVblank(pScrn);
   }
   if ((pI830->saveDSPBCNTR & DISPPLANE_SEL_PIPE_MASK) ==
       DISPPLANE_SEL_PIPE_A) {
       OUTREG(DSPBCNTR, pI830->saveDSPBCNTR);
       OUTREG(DSPBBASE, INREG(DSPBBASE));
       i830WaitForVblank(pScrn);
   }

   /* See note about pipe programming above */
   if(xf86_config->num_crtc == 2) 
   {
      /* If the pipe B PLL is active, we can restore the pipe & plane config */
      if (pI830->saveDPLL_B & DPLL_VCO_ENABLE)
      {
	 OUTREG(DPLL_B, pI830->saveDPLL_B & ~DPLL_VCO_ENABLE);
	 usleep(150);
      }
      OUTREG(FPB0, pI830->saveFPB0);
      OUTREG(FPB1, pI830->saveFPB1);
      OUTREG(DPLL_B, pI830->saveDPLL_B);
      i830_dpll_settle();
      if (IS_I965G(pI830))
	 OUTREG(DPLL_B_MD, pI830->saveDPLL_B_MD);
      else
	 OUTREG(DPLL_B, pI830->saveDPLL_B);
      i830_dpll_settle();
   
      /* Restore mode config */
      OUTREG(HTOTAL_B, pI830->saveHTOTAL_B);
      OUTREG(HBLANK_B, pI830->saveHBLANK_B);
      OUTREG(HSYNC_B, pI830->saveHSYNC_B);
      OUTREG(VTOTAL_B, pI830->saveVTOTAL_B);
      OUTREG(VBLANK_B, pI830->saveVBLANK_B);
      OUTREG(VSYNC_B, pI830->saveVSYNC_B);
      OUTREG(BCLRPAT_B, pI830->saveBCLRPAT_B);
      OUTREG(DSPBSTRIDE, pI830->saveDSPBSTRIDE);
      OUTREG(DSPBSIZE, pI830->saveDSPBSIZE);
      OUTREG(DSPBPOS, pI830->saveDSPBPOS);
      OUTREG(PIPEBSRC, pI830->savePIPEBSRC);
      OUTREG(DSPBBASE, pI830->saveDSPBBASE);
      if (IS_I965G(pI830))
      {
	 OUTREG(DSPBSURF, pI830->saveDSPBSURF);
	 OUTREG(DSPBTILEOFF, pI830->saveDSPBTILEOFF);
      }

      OUTREG(PIPEBCONF, pI830->savePIPEBCONF);
      i830WaitForVblank(pScrn);

      /*
       * Program Pipe B's plane
       * Note that pipe B may be disabled, and in that case, the plane
       * should also be disabled or we must have had a bad initial state.
       */
      if ((pI830->saveDSPACNTR & DISPPLANE_SEL_PIPE_MASK) ==
	  DISPPLANE_SEL_PIPE_B) {
	  OUTREG(DSPACNTR, pI830->saveDSPACNTR);
	  OUTREG(DSPABASE, INREG(DSPABASE));
	  i830WaitForVblank(pScrn);
      }
      if ((pI830->saveDSPBCNTR & DISPPLANE_SEL_PIPE_MASK) ==
	  DISPPLANE_SEL_PIPE_B) {
	  OUTREG(DSPBCNTR, pI830->saveDSPBCNTR);
	  OUTREG(DSPBBASE, INREG(DSPBBASE));
	  i830WaitForVblank(pScrn);
      }
   }

   OUTREG(VGACNTRL, pI830->saveVGACNTRL);

   /*
    * Restore cursors
    * Even though the X cursor is hidden before we restore the hw state,
    * we probably only disabled one cursor plane.  If we're going from
    * e.g. plane b to plane a here in RestoreHWState, we need to restore
    * both cursor plane settings.
    */
   OUTREG(CURSOR_A_POSITION, pI830->saveCURSOR_A_POSITION);
   OUTREG(CURSOR_A_BASE, pI830->saveCURSOR_A_BASE);
   OUTREG(CURSOR_A_CONTROL, pI830->saveCURSOR_A_CONTROL);
   OUTREG(CURSOR_B_POSITION, pI830->saveCURSOR_B_POSITION);
   OUTREG(CURSOR_B_BASE, pI830->saveCURSOR_B_BASE);
   OUTREG(CURSOR_B_CONTROL, pI830->saveCURSOR_B_CONTROL);

   /* Restore outputs */
   for (i = 0; i < xf86_config->num_output; i++) {
      xf86OutputPtr   output = xf86_config->output[i];
      if (output->funcs->restore)
	 output->funcs->restore(output);
   }
    
   i830_restore_palette(pI830, PIPE_A);
   i830_restore_palette(pI830, PIPE_B);

   for(i = 0; i < 7; i++) {
      OUTREG(SWF0 + (i << 2), pI830->saveSWF[i]);
      OUTREG(SWF00 + (i << 2), pI830->saveSWF[i+7]);
   }

   OUTREG(SWF30, pI830->saveSWF[14]);
   OUTREG(SWF31, pI830->saveSWF[15]);
   OUTREG(SWF32, pI830->saveSWF[16]);

   if (pI830->fb_compression) {
       OUTREG(FBC_CFB_BASE, pI830->saveFBC_CFB_BASE);
       OUTREG(FBC_LL_BASE, pI830->saveFBC_LL_BASE);
       OUTREG(FBC_FENCE_OFF, pI830->saveFBC_FENCE_OFF);
       OUTREG(FBC_CONTROL2, pI830->saveFBC_CONTROL2);
       OUTREG(FBC_CONTROL, pI830->saveFBC_CONTROL);
   }

   /* Clear any FIFO underrun status that may have occurred normally */
   OUTREG(PIPEASTAT, INREG(PIPEASTAT) | FIFO_UNDERRUN);
   OUTREG(PIPEBSTAT, INREG(PIPEBSTAT) | FIFO_UNDERRUN);

   vgaHWRestore(pScrn, vgaReg, VGA_SR_FONTS);
   vgaHWLock(hwp);

   return TRUE;
}

static void
I830PointerMoved(int index, int x, int y)
{
   ScrnInfoPtr pScrn = xf86Screens[index];
   I830Ptr pI830 = I830PTR(pScrn);
   int newX = x, newY = y;

   switch (pI830->rotation) {
      case RR_Rotate_0:
         break;
      case RR_Rotate_90:
         newX = y;
         newY = pScrn->pScreen->width - x - 1;
         break;
      case RR_Rotate_180:
         newX = pScrn->pScreen->width - x - 1;
         newY = pScrn->pScreen->height - y - 1;
         break;
      case RR_Rotate_270:
         newX = pScrn->pScreen->height - y - 1;
         newY = x;
         break;
   }

   (*pI830->PointerMoved)(index, newX, newY);
}

static Bool
I830InitFBManager(
    ScreenPtr pScreen,  
    BoxPtr FullBox
){
   ScrnInfoPtr pScrn = xf86Screens[pScreen->myNum];
   RegionRec ScreenRegion;
   RegionRec FullRegion;
   BoxRec ScreenBox;
   Bool ret;

   ScreenBox.x1 = 0;
   ScreenBox.y1 = 0;
   ScreenBox.x2 = pScrn->displayWidth;
   if (pScrn->virtualX > pScrn->virtualY)
      ScreenBox.y2 = pScrn->virtualX;
   else
      ScreenBox.y2 = pScrn->virtualY;

   if((FullBox->x1 >  ScreenBox.x1) || (FullBox->y1 >  ScreenBox.y1) ||
      (FullBox->x2 <  ScreenBox.x2) || (FullBox->y2 <  ScreenBox.y2)) {
	return FALSE;   
   }

   if (FullBox->y2 < FullBox->y1) return FALSE;
   if (FullBox->x2 < FullBox->x2) return FALSE;

   REGION_INIT(pScreen, &ScreenRegion, &ScreenBox, 1); 
   REGION_INIT(pScreen, &FullRegion, FullBox, 1); 

   REGION_SUBTRACT(pScreen, &FullRegion, &FullRegion, &ScreenRegion);

   ret = xf86InitFBManagerRegion(pScreen, &FullRegion);

   REGION_UNINIT(pScreen, &ScreenRegion);
   REGION_UNINIT(pScreen, &FullRegion);
    
   return ret;
}

/**
 * Intialiazes the hardware for the 3D pipeline use in the 2D driver.
 *
 * Some state caching is performed to avoid redundant state emits.  This
 * function is also responsible for marking the state as clobbered for DRI
 * clients.
 */
void
IntelEmitInvarientState(ScrnInfoPtr pScrn)
{
   I830Ptr pI830 = I830PTR(pScrn);
   uint32_t ctx_addr;

   if (pI830->accel == ACCEL_NONE)
      return;

#ifdef XF86DRI
   if (pI830->directRenderingEnabled) {
      drmI830Sarea *sarea = DRIGetSAREAPrivate(pScrn->pScreen);

      /* Mark that the X Server was the last holder of the context */
      if (sarea)
	 sarea->ctxOwner = DRIGetContext(pScrn->pScreen);
   }
#endif

   /* If we've emitted our state since the last clobber by another client,
    * skip it.
    */
   if (*pI830->last_3d != LAST_3D_OTHER)
      return;

   ctx_addr = pI830->logical_context->offset;
   assert((pI830->logical_context->offset & 2047) == 0);
   {
      BEGIN_BATCH(2);
      OUT_BATCH(MI_SET_CONTEXT);
      OUT_BATCH(pI830->logical_context->offset |
		CTXT_NO_RESTORE |
		CTXT_PALETTE_SAVE_DISABLE | CTXT_PALETTE_RESTORE_DISABLE);
      ADVANCE_BATCH();
   }

   if (!IS_I965G(pI830))
   {
      if (IS_I9XX(pI830))
         I915EmitInvarientState(pScrn);
      else
         I830EmitInvarientState(pScrn);
   }
}

static void
I830BlockHandler(int i,
		 pointer blockData, pointer pTimeout, pointer pReadmask)
{
    ScreenPtr pScreen = screenInfo.screens[i];
    ScrnInfoPtr pScrn = xf86Screens[i];
    I830Ptr pI830 = I830PTR(pScrn);
    xf86CrtcConfigPtr xf86_config = XF86_CRTC_CONFIG_PTR(pScrn);

    pScreen->BlockHandler = pI830->BlockHandler;

    (*pScreen->BlockHandler) (i, blockData, pTimeout, pReadmask);

    pI830->BlockHandler = pScreen->BlockHandler;
    pScreen->BlockHandler = I830BlockHandler;

    if (pScrn->vtSema && pI830->accel != ACCEL_NONE) {
       /* Emit a flush of the rendering cache, or on the 965 and beyond
	* rendering results may not hit the framebuffer until significantly
	* later.
	*/
       if (pI830->accel != ACCEL_NONE && (pI830->need_mi_flush || pI830->batch_used))
	  I830EmitFlush(pScrn);

       /* Flush the batch, so that any rendering is executed in a timely
	* fashion.
	*/
       intel_batch_flush(pScrn);

       pI830->need_mi_flush = FALSE;
#ifdef XF86DRI
       drmCommandNone(pI830->drmSubFD, DRM_I915_GEM_THROTTLE);
#endif
    }

    /*
     * Check for FIFO underruns at block time (which amounts to just
     * periodically).  If this happens, it means our DSPARB or some other
     * memory arbitration setting is wrong for the current configuration
     * (except for mode setting, where it may occur naturally).
     * Check & ack the condition.
     */
    if (pScrn->vtSema && !DSPARB_HWCONTROL(pI830)) {
	if (xf86_config->crtc[0]->enabled &&
		(INREG(PIPEASTAT) & FIFO_UNDERRUN)) {
	    xf86DrvMsg(pScrn->scrnIndex, X_ERROR, "underrun on pipe A!\n");
	    OUTREG(PIPEASTAT, INREG(PIPEASTAT) | FIFO_UNDERRUN);
	}
	if (xf86_config->num_crtc > 1 &&
		xf86_config->crtc[1]->enabled &&
		(INREG(PIPEBSTAT) & FIFO_UNDERRUN)) {
	    xf86DrvMsg(pScrn->scrnIndex, X_ERROR, "underrun on pipe B!\n");
	    OUTREG(PIPEBSTAT, INREG(PIPEBSTAT) | FIFO_UNDERRUN);
	}
    }

    I830VideoBlockHandler(i, blockData, pTimeout, pReadmask);
}

static void
i830_fixup_mtrrs(ScrnInfoPtr pScrn)
{
#ifdef HAS_MTRR_SUPPORT
    I830Ptr pI830 = I830PTR(pScrn);
    int fd;
    struct mtrr_gentry gentry;
    struct mtrr_sentry sentry;

    if ( ( fd = open ("/proc/mtrr", O_RDONLY, 0) ) != -1 ) {
	for (gentry.regnum = 0; ioctl (fd, MTRRIOC_GET_ENTRY, &gentry) == 0;
		++gentry.regnum) {

	    if (gentry.size < 1) {
		/* DISABLED */
		continue;
	    }

	    /* Check the MTRR range is one we like and if not - remove it.
	     * The Xserver common layer will then setup the right range
	     * for us.
	     */
	    if (gentry.base == pI830->LinearAddr && 
		    gentry.size < pI830->FbMapSize) {

		xf86DrvMsg(pScrn->scrnIndex, X_INFO,
			"Removing bad MTRR range (base 0x%lx, size 0x%x)\n",
			gentry.base, gentry.size);

		sentry.base = gentry.base;
		sentry.size = gentry.size;
		sentry.type = gentry.type;

		if (ioctl (fd, MTRRIOC_DEL_ENTRY, &sentry) == -1) {
		    xf86DrvMsg(pScrn->scrnIndex, X_ERROR,
			    "Failed to remove bad MTRR range\n");
		}
	    }
	}
	close(fd);
    }
#endif
}

static Bool
i830_try_memory_allocation(ScrnInfoPtr pScrn)
{
    I830Ptr pI830 = I830PTR(pScrn);
    Bool tiled = pI830->tiling;
    Bool dri = pI830->directRenderingEnabled;

    xf86DrvMsg(pScrn->scrnIndex, X_INFO,
	    "Attempting memory allocation with %stiled buffers.\n",
	    tiled ? "" : "un");

    if (!i830_allocate_2d_memory(pScrn))
	goto failed;

    if (IS_I965GM(pI830) || IS_GM45(pI830))
	if (!i830_allocate_pwrctx(pScrn))
	    goto failed;

    if (dri && !i830_allocate_3d_memory(pScrn))
	goto failed;

    xf86DrvMsg(pScrn->scrnIndex, X_INFO, "%siled allocation successful.\n",
	    tiled ? "T" : "Unt");
    return TRUE;

failed:
    xf86DrvMsg(pScrn->scrnIndex, X_INFO, "%siled allocation failed.\n",
	    tiled ? "T" : "Unt");
    return FALSE;
}

/*
 * Try to allocate memory in several ways:
 *  1) If direct rendering is enabled, try to allocate enough memory for tiled
 *     surfaces by rounding up the display width to a tileable one.
 *  2) If that fails or the allocations themselves fail, try again with untiled
 *     allocations (if this works DRI will stay enabled).
 *  3) And if all else fails, disable DRI and try just 2D allocations.
 *  4) Give up and fail ScreenInit.
 */
static Bool
i830_memory_init(ScrnInfoPtr pScrn)
{
    I830Ptr pI830 = I830PTR(pScrn);
    int savedDisplayWidth = pScrn->displayWidth;
    int i;
    Bool tiled = FALSE;

    /*
     * Adjust the display width to allow for front buffer tiling if possible
     */
    if (pI830->tiling) {
	if (IS_I965G(pI830)) {
	    int tile_pixels = 512 / pI830->cpp;
	    pScrn->displayWidth = (pScrn->displayWidth + tile_pixels - 1) &
		~(tile_pixels - 1);
	    tiled = TRUE;
	} else {
	    /* Good pitches to allow tiling.  Don't care about pitches < 1024
	     * pixels.
	     */
	    static const int pitches[] = {
		1024,
		2048,
		4096,
		8192,
		0
	    };

	    for (i = 0; pitches[i] != 0; i++) {
		if (pitches[i] >= pScrn->displayWidth) {
		    pScrn->displayWidth = pitches[i];
		    tiled = TRUE;
		    break;
		}
	    }
	}
    }
    /* Set up our video memory allocator for the chosen videoRam */
    if (!i830_allocator_init(pScrn, 0, pScrn->videoRam * KB(1))) {
	xf86DrvMsg(pScrn->scrnIndex, X_ERROR,
		"Couldn't initialize video memory allocator\n");
	PreInitCleanup(pScrn);
	return FALSE;
    }

    xf86DrvMsg(pScrn->scrnIndex,
	    pI830->pEnt->device->videoRam ? X_CONFIG : X_DEFAULT,
	    "VideoRam: %d KB\n", pScrn->videoRam);

    if (xf86GetOptValInteger(pI830->Options, OPTION_CACHE_LINES,
		&(pI830->CacheLines))) {
	xf86DrvMsg(pScrn->scrnIndex, X_CONFIG, "Requested %d cache lines\n",
		pI830->CacheLines);
    } else {
	pI830->CacheLines = -1;
    }

    /* Tiled first if we got a good displayWidth */
    if (tiled) {
	if (i830_try_memory_allocation(pScrn))
	    return TRUE;
	else {
	    i830_reset_allocations(pScrn);
	    pI830->tiling = FALSE;
	}
    }

    /* If tiling fails we have to disable page flipping & FBC */
    pScrn->displayWidth = savedDisplayWidth;
    if (pI830->allowPageFlip)
	xf86DrvMsg(pScrn->scrnIndex, X_WARNING,
		"Couldn't allocate tiled memory, page flipping "
		"disabled\n");
    pI830->allowPageFlip = FALSE;
    if (pI830->fb_compression)
	xf86DrvMsg(pScrn->scrnIndex, X_WARNING,
		"Couldn't allocate tiled memory, fb compression "
		"disabled\n");
    pI830->fb_compression = FALSE;

    /* Try again, but leave DRI enabled */
    if (pI830->directRenderingEnabled) {
	if (i830_try_memory_allocation(pScrn))
	    return TRUE;
	else {
	    i830_reset_allocations(pScrn);
	    xf86DrvMsg(pScrn->scrnIndex, X_INFO, "Couldn't allocate 3D memory, "
		    "disabling DRI.\n");
	    pI830->directRenderingEnabled = FALSE;
	}
    }

    if (i830_try_memory_allocation(pScrn))
	return TRUE;

    return FALSE;
}

/**
 * Returns a cookie to be waited on.  This is just a stub implementation, and
 * should be hooked up to the emit/wait irq functions when available (DRI
 * enabled).
 */
static unsigned int
i830_fake_fence_emit(void *priv)
{
   static unsigned int fence = 0;

   /* Match DRM in not using half the range. The fake bufmgr relies on this. */
   if (++fence >= 0x8000000)
      fence = 1;

   return fence;
}

/**
 * Waits on a cookie representing a request to be passed.
 *
 * Stub implementation that should be replaced with DRM functions when
 * available.
 */
static int
i830_fake_fence_wait(void *priv, unsigned int fence)
{
   ScrnInfoPtr pScrn = priv;

   i830_wait_ring_idle(pScrn);

   return 0;
}

static void
i830_init_bufmgr(ScrnInfoPtr pScrn)
{
   I830Ptr pI830 = I830PTR(pScrn);

   assert(pI830->FbBase != NULL);
   if (pI830->memory_manager) {
      int batch_size;

      batch_size = 4096 * 4;

      /* The 865 has issues with larger-than-page-sized batch buffers. */
      if (IS_I865G(pI830))
	 batch_size = 4096;

      pI830->bufmgr = intel_bufmgr_gem_init(pI830->drmSubFD, batch_size);
      intel_bufmgr_gem_enable_reuse(pI830->bufmgr);
   } else {
      pI830->bufmgr = intel_bufmgr_fake_init(pI830->fake_bufmgr_mem->offset,
					     pI830->FbBase +
					     pI830->fake_bufmgr_mem->offset,
					     pI830->fake_bufmgr_mem->size,
					     i830_fake_fence_emit,
					     i830_fake_fence_wait,
					     pScrn);
   }
}


static Bool
I830ScreenInit(int scrnIndex, ScreenPtr pScreen, int argc, char **argv)
{
   ScrnInfoPtr pScrn;
   vgaHWPtr hwp;
   I830Ptr pI830;
   VisualPtr visual;
   I830Ptr pI8301 = NULL;
   unsigned long sys_mem;
   int c;
   MessageType from;
#ifdef XF86DRI
   xf86CrtcConfigPtr config;
#endif

   pScrn = xf86Screens[pScreen->myNum];
   pI830 = I830PTR(pScrn);
   hwp = VGAHWPTR(pScrn);

   pScrn->displayWidth = (pScrn->virtualX + 63) & ~63;

   /*
    * The "VideoRam" config file parameter specifies the maximum amount of
    * memory that will be used/allocated.  When not present, we allow the
    * driver to allocate as much memory as it wishes to satisfy its
    * allocations, but if agpgart support isn't available, it gets limited
    * to the amount of pre-allocated ("stolen") memory.
    *
    * Note that in using this value for allocator initialization, we're
    * limiting aperture allocation to the VideoRam option, rather than limiting
    * actual memory allocation, so alignment and things will cause less than
    * VideoRam to be actually used.
    */
   if (pI830->pEnt->device->videoRam == 0) {
      from = X_DEFAULT;
      pScrn->videoRam = pI830->FbMapSize / KB(1);
   } else {
#if 0
      from = X_CONFIG;
      pScrn->videoRam = pI830->pEnt->device->videoRam;
#else
      /* Disable VideoRam configuration, at least for now.  Previously,
       * VideoRam was necessary to avoid overly low limits on allocated
       * memory, so users created larger, yet still small, fixed allocation
       * limits in their config files.  Now, the driver wants to allocate more,
       * and the old intention of the VideoRam lines that had been entered is
       * obsolete.
       */
      from = X_DEFAULT;
      pScrn->videoRam = pI830->FbMapSize / KB(1);

      if (pScrn->videoRam != pI830->pEnt->device->videoRam) {
	 xf86DrvMsg(pScrn->scrnIndex, X_WARNING,
		    "VideoRam configuration found, which is no longer "
		    "recommended.\n");
	 xf86DrvMsg(pScrn->scrnIndex, X_INFO,
		    "Continuing with default %dkB VideoRam instead of %d "
		    "kB.\n",
		    pScrn->videoRam, pI830->pEnt->device->videoRam);
      }
#endif
   }

   /* Limit videoRam to how much we might be able to allocate from AGP */
   sys_mem = I830CheckAvailableMemory(pScrn);
   if (sys_mem == -1) {
      if (pScrn->videoRam > pI830->stolen_size / KB(1)) {
	 xf86DrvMsg(pScrn->scrnIndex, X_WARNING,
		    "/dev/agpgart is either not available, or no memory "
		    "is available\nfor allocation.  "
		    "Using pre-allocated memory only.\n");
	 pScrn->videoRam = pI830->stolen_size / KB(1);
      }
      pI830->StolenOnly = TRUE;
   } else {
      if (sys_mem + (pI830->stolen_size / 1024) < pScrn->videoRam) {
	 pScrn->videoRam = sys_mem + (pI830->stolen_size / 1024);
	 from = X_PROBED;
	 if (sys_mem + (pI830->stolen_size / 1024) <
	     pI830->pEnt->device->videoRam)
	 {
	    xf86DrvMsg(pScrn->scrnIndex, X_WARNING,
		       "VideoRAM reduced to %d kByte "
		       "(limited to available sysmem)\n", pScrn->videoRam);
	 }
      }
   }

   /* Limit video RAM to the actual aperture size */
   if (pScrn->videoRam > pI830->FbMapSize / 1024) {
      pScrn->videoRam = pI830->FbMapSize / 1024;
      if (pI830->FbMapSize / 1024 < pI830->pEnt->device->videoRam) {
	 xf86DrvMsg(pScrn->scrnIndex, X_WARNING,
		    "VideoRam reduced to %d kByte (limited to aperture "
		    "size)\n",
		    pScrn->videoRam);
      }
   }

   /* Make sure it's on a page boundary */
   if (pScrn->videoRam & 3) {
      xf86DrvMsg(pScrn->scrnIndex, X_WARNING, "VideoRam reduced to %d KB "
		 "(page aligned - was %d KB)\n",
		 pScrn->videoRam & ~3, pScrn->videoRam);
      pScrn->videoRam &= ~3;
   }

   if (!IS_I965G(pI830) && pScrn->displayWidth > 2048) {
      xf86DrvMsg(pScrn->scrnIndex, X_ERROR,
		 "Cannot support DRI with frame buffer width > 2048.\n");
      pI830->directRenderingDisabled = TRUE;
   }

#ifdef XF86DRI
   /* If DRI hasn't been explicitly disabled, try to initialize it.
    * It will be used by the memory allocator.
    */
   if (!pI830->directRenderingDisabled)
      pI830->directRenderingEnabled = I830DRIScreenInit(pScreen);
   else
      pI830->directRenderingEnabled = FALSE;
#else
   pI830->directRenderingEnabled = FALSE;
#endif

   /* Enable tiling by default */
   pI830->tiling = TRUE;

   /* Allow user override if they set a value */
   if (xf86IsOptionSet(pI830->Options, OPTION_TILING)) {
       if (xf86ReturnOptValBool(pI830->Options, OPTION_TILING, FALSE))
	   pI830->tiling = TRUE;
       else
	   pI830->tiling = FALSE;
   }

   /* Enable FB compression if possible */
   if (i830_fb_compression_supported(pI830))
       pI830->fb_compression = TRUE;
   else
       pI830->fb_compression = FALSE;

   /* Again, allow user override if set */
   if (xf86IsOptionSet(pI830->Options, OPTION_FBC)) {
       if (xf86ReturnOptValBool(pI830->Options, OPTION_FBC, FALSE))
	   pI830->fb_compression = TRUE;
       else
	   pI830->fb_compression = FALSE;
   }

   xf86DrvMsg(pScrn->scrnIndex, X_CONFIG, "Framebuffer compression %sabled\n",
	      pI830->fb_compression ? "en" : "dis");
   xf86DrvMsg(pScrn->scrnIndex, X_CONFIG, "Tiling %sabled\n", pI830->tiling ?
	      "en" : "dis");

   if (I830IsPrimary(pScrn)) {
      /* Alloc our pointers for the primary head */
      if (!pI830->LpRing)
         pI830->LpRing = xcalloc(1, sizeof(I830RingBuffer));
      if (!pI830->overlayOn)
         pI830->overlayOn = xalloc(sizeof(Bool));
      if (!pI830->last_3d)
         pI830->last_3d = xalloc(sizeof(enum last_3d));
      if (!pI830->LpRing || !pI830->overlayOn || !pI830->last_3d) {
         xf86DrvMsg(pScrn->scrnIndex, X_ERROR,
		 "Could not allocate primary data structures.\n");
         return FALSE;
      }
      *pI830->last_3d = LAST_3D_OTHER;
      *pI830->overlayOn = FALSE;
      if (pI830->entityPrivate)
         pI830->entityPrivate->XvInUse = -1;
   } else {
      /* Make our second head point to the first heads structures */
      pI8301 = I830PTR(pI830->entityPrivate->pScrn_1);
      pI830->LpRing = pI8301->LpRing;
      pI830->overlay_regs = pI8301->overlay_regs;
      pI830->overlayOn = pI8301->overlayOn;
      pI830->last_3d = pI8301->last_3d;
   }

#ifdef I830_XV
    /*
     * Set this so that the overlay allocation is factored in when
     * appropriate.
     */
    pI830->XvEnabled = !pI830->XvDisabled;
#endif


   /* Need MMIO mapped to do GTT lookups during memory allocation. */
   I830MapMMIO(pScrn);

   if (!i830_memory_init(pScrn)) {
       xf86DrvMsg(pScrn->scrnIndex, X_ERROR,
	       "Couldn't allocate video memory\n");
       return FALSE;
   }

   I830UnmapMMIO(pScrn);

   i830_fixup_mtrrs(pScrn);

   pI830->starting = TRUE;

   miClearVisualTypes();
   if (!miSetVisualTypes(pScrn->depth,
			    miGetDefaultVisualMask(pScrn->depth),
			    pScrn->rgbBits, pScrn->defaultVisual))
	 return FALSE;
   if (!miSetPixmapDepths())
      return FALSE;

#ifdef I830_XV
   pI830->XvEnabled = !pI830->XvDisabled;
   if (pI830->XvEnabled) {
      if (!I830IsPrimary(pScrn)) {
         if (!pI8301->XvEnabled || pI830->accel == ACCEL_NONE) {
            pI830->XvEnabled = FALSE;
	    xf86DrvMsg(pScrn->scrnIndex, X_PROBED, "Xv is disabled.\n");
         }
      } else
      if (pI830->accel == ACCEL_NONE || pI830->StolenOnly) {
	 xf86DrvMsg(pScrn->scrnIndex, X_PROBED, "Xv is disabled because it "
		    "needs 2D accel and AGPGART.\n");
	 pI830->XvEnabled = FALSE;
      }
   }
#else
   pI830->XvEnabled = FALSE;
#endif

   if (pI830->accel != ACCEL_NONE) {
      if (pI830->memory_manager == NULL && pI830->LpRing->mem->size == 0) {
	  xf86DrvMsg(pScrn->scrnIndex, X_WARNING,
		     "Disabling acceleration because the ring buffer "
		      "allocation failed.\n");
	   pI830->accel = ACCEL_NONE;
      }
   }

#ifdef I830_XV
   if (pI830->XvEnabled) {
      if (pI830->accel == ACCEL_NONE) {
	 xf86DrvMsg(pScrn->scrnIndex, X_WARNING, "Disabling Xv because it "
		    "needs 2D acceleration.\n");
	 pI830->XvEnabled = FALSE;
      }
      if (!OVERLAY_NOEXIST(pI830) && pI830->overlay_regs == NULL) {
	  xf86DrvMsg(pScrn->scrnIndex, X_WARNING,
		     "Disabling Xv because the overlay register buffer "
		      "allocation failed.\n");
	 pI830->XvEnabled = FALSE;
      }
   }
#endif

#ifdef XF86DRI
   /*
    * Setup DRI after visuals have been established, but before fbScreenInit
    * is called.   fbScreenInit will eventually call into the drivers
    * InitGLXVisuals call back.
    */

   if (pI830->directRenderingEnabled) {
      if (pI830->accel == ACCEL_NONE || pI830->SWCursor || (pI830->StolenOnly && I830IsPrimary(pScrn))) {
	 xf86DrvMsg(pScrn->scrnIndex, X_PROBED, "DRI is disabled because it "
		    "needs HW cursor, 2D accel and AGPGART.\n");
	 pI830->directRenderingEnabled = FALSE;
      }
   }

   if (pI830->directRenderingEnabled)
      pI830->directRenderingEnabled = I830DRIDoMappings(pScreen);

   /* If we failed for any reason, free DRI memory. */
   if (!pI830->directRenderingEnabled)
      i830_free_3d_memory(pScrn);

   config = XF86_CRTC_CONFIG_PTR(pScrn);

   /*
    * If an LVDS display is present, swap the plane/pipe mappings so we can
    * use FBC on the builtin display.
    * Note: 965+ chips can compress either plane, so we leave the mapping
    *       alone in that case.
    * Also make sure the DRM can handle the swap.
    */
   if (I830LVDSPresent(pScrn) && !IS_I965GM(pI830) && !IS_GM45(pI830) &&
       (!pI830->directRenderingEnabled ||
	(pI830->directRenderingEnabled && pI830->drmMinor >= 10))) {
       xf86DrvMsg(pScrn->scrnIndex, X_INFO, "adjusting plane->pipe mappings "
		  "to allow for framebuffer compression\n");
       for (c = 0; c < config->num_crtc; c++) {
	   xf86CrtcPtr	      crtc = config->crtc[c];
	   I830CrtcPrivatePtr   intel_crtc = crtc->driver_private;

	   if (intel_crtc->pipe == 0)
	       intel_crtc->plane = 1;
	   else if (intel_crtc->pipe == 1)
	       intel_crtc->plane = 0;
      }
   }

#else
   pI830->directRenderingEnabled = FALSE;
#endif

#ifdef XF86DRI

   xf86DrvMsg(pScrn->scrnIndex, X_INFO, "Page Flipping %sabled\n",
	      pI830->allowPageFlip ? "en" : "dis");
#endif

   DPRINTF(PFX, "assert( if(!I830MapMem(pScrn)) )\n");
   if (!I830MapMem(pScrn))
      return FALSE;

   pScrn->memPhysBase = (unsigned long)pI830->FbBase;

   if (I830IsPrimary(pScrn)) {
      pScrn->fbOffset = pI830->front_buffer->offset;
   } else {
      pScrn->fbOffset = pI8301->front_buffer_2->offset;
   }

   pI830->xoffset = (pScrn->fbOffset / pI830->cpp) % pScrn->displayWidth;
   pI830->yoffset = (pScrn->fbOffset / pI830->cpp) / pScrn->displayWidth;

   i830_init_bufmgr(pScrn);

   vgaHWSetMmioFuncs(hwp, pI830->MMIOBase, 0);
   vgaHWGetIOBase(hwp);
   DPRINTF(PFX, "assert( if(!vgaHWMapMem(pScrn)) )\n");
   if (!vgaHWMapMem(pScrn))
      return FALSE;

   DPRINTF(PFX, "assert( if(!I830EnterVT(scrnIndex, 0)) )\n");

   if (pI830->accel <= ACCEL_XAA) {
      if (I830IsPrimary(pScrn)) {
	 if (!I830InitFBManager(pScreen, &(pI830->FbMemBox))) {
	    xf86DrvMsg(pScrn->scrnIndex, X_ERROR,
		       "Failed to init memory manager\n");
	 }
      } else {
	 if (!I830InitFBManager(pScreen, &(pI8301->FbMemBox2))) {
	    xf86DrvMsg(pScrn->scrnIndex, X_ERROR,
		       "Failed to init memory manager\n");
	 }
      }
   }

    if (pScrn->virtualX > pScrn->displayWidth)
	pScrn->displayWidth = pScrn->virtualX;

   DPRINTF(PFX, "assert( if(!fbScreenInit(pScreen, ...) )\n");
   if (!fbScreenInit(pScreen, pI830->FbBase + pScrn->fbOffset, 
                     pScrn->virtualX, pScrn->virtualY,
		     pScrn->xDpi, pScrn->yDpi,
		     pScrn->displayWidth, pScrn->bitsPerPixel))
      return FALSE;

   if (pScrn->bitsPerPixel > 8) {
      /* Fixup RGB ordering */
      visual = pScreen->visuals + pScreen->numVisuals;
      while (--visual >= pScreen->visuals) {
	 if ((visual->class | DynamicClass) == DirectColor) {
	    visual->offsetRed = pScrn->offset.red;
	    visual->offsetGreen = pScrn->offset.green;
	    visual->offsetBlue = pScrn->offset.blue;
	    visual->redMask = pScrn->mask.red;
	    visual->greenMask = pScrn->mask.green;
	    visual->blueMask = pScrn->mask.blue;
	 }
      }
   }

   fbPictureInit(pScreen, NULL, 0);

   xf86SetBlackWhitePixels(pScreen);

   xf86DiDGAInit (pScreen, pI830->LinearAddr + pScrn->fbOffset);

   DPRINTF(PFX,
	   "assert( if(!I830InitFBManager(pScreen, &(pI830->FbMemBox))) )\n");

   if (pI830->accel != ACCEL_NONE) {
      if (!I830AccelInit(pScreen)) {
	 xf86DrvMsg(pScrn->scrnIndex, X_ERROR,
		    "Hardware acceleration initialization failed\n");
      }
   }

   miInitializeBackingStore(pScreen);
   xf86SetBackingStore(pScreen);
   xf86SetSilkenMouse(pScreen);
   miDCInitialize(pScreen, xf86GetPointerScreenFuncs());

   if (!pI830->SWCursor) {
      xf86DrvMsg(pScrn->scrnIndex, X_INFO, "Initializing HW Cursor\n");
      if (!I830CursorInit(pScreen))
	 xf86DrvMsg(pScrn->scrnIndex, X_ERROR,
		    "Hardware cursor initialization failed\n");
   } else
      xf86DrvMsg(pScrn->scrnIndex, X_INFO, "Initializing SW Cursor!\n");

#ifdef XF86DRI
   /* Must be called before EnterVT, so we can acquire the DRI lock when
    * binding our memory.
    */
   if (pI830->directRenderingEnabled)
      pI830->directRenderingEnabled = I830DRIFinishScreenInit(pScreen);
#endif

   /* Must force it before EnterVT, so we are in control of VT and
    * later memory should be bound when allocating, e.g rotate_mem */
   pScrn->vtSema = TRUE;

   if (!I830EnterVT(scrnIndex, 0))
      return FALSE;

   pI830->BlockHandler = pScreen->BlockHandler;
   pScreen->BlockHandler = I830BlockHandler;

   pScreen->SaveScreen = xf86SaveScreen;
   pI830->CloseScreen = pScreen->CloseScreen;
   pScreen->CloseScreen = I830CloseScreen;
   pI830->CreateScreenResources = pScreen->CreateScreenResources;
   pScreen->CreateScreenResources = i830CreateScreenResources;

   if (!xf86CrtcScreenInit (pScreen))
       return FALSE;

   DPRINTF(PFX, "assert( if(!miCreateDefColormap(pScreen)) )\n");
   if (!miCreateDefColormap(pScreen))
      return FALSE;

   DPRINTF(PFX, "assert( if(!xf86HandleColormaps(pScreen, ...)) )\n");
   if (!xf86HandleColormaps(pScreen, 256, 8, I830LoadPalette, NULL,
			    CMAP_RELOAD_ON_MODE_SWITCH |
			    CMAP_PALETTED_TRUECOLOR)) {
      return FALSE;
   }

   xf86DPMSInit(pScreen, xf86DPMSSet, 0);

#ifdef I830_XV
   /* Init video */
   if (pI830->XvEnabled)
      I830InitVideo(pScreen);
#endif

   /* Setup 3D engine, needed for rotation too */
   IntelEmitInvarientState(pScrn);

#ifdef XF86DRI
   if (pI830->directRenderingEnabled) {
      pI830->directRenderingOpen = TRUE;
      xf86DrvMsg(pScrn->scrnIndex, X_INFO, "direct rendering: Enabled\n");
   } else {
      if (pI830->directRenderingDisabled)
	 xf86DrvMsg(pScrn->scrnIndex, X_INFO, "direct rendering: Disabled\n");
      else
	 xf86DrvMsg(pScrn->scrnIndex, X_INFO, "direct rendering: Failed\n");
   }
#else
   xf86DrvMsg(pScrn->scrnIndex, X_INFO, "direct rendering: Not available\n");
#endif


   /* Wrap pointer motion to flip touch screen around */
   pI830->PointerMoved = pScrn->PointerMoved;
   pScrn->PointerMoved = I830PointerMoved;

   if (serverGeneration == 1)
      xf86ShowUnusedOptions(pScrn->scrnIndex, pScrn->options);

   pI830->starting = FALSE;
   pI830->closing = FALSE;
   pI830->suspended = FALSE;

   return TRUE;
}

static void
i830AdjustFrame(int scrnIndex, int x, int y, int flags)
{
   ScrnInfoPtr pScrn = xf86Screens[scrnIndex];
   xf86CrtcConfigPtr	config = XF86_CRTC_CONFIG_PTR(pScrn);
   I830Ptr pI830 = I830PTR(pScrn);
   xf86OutputPtr  output = config->output[config->compat_output];
   xf86CrtcPtr	crtc = output->crtc;

   DPRINTF(PFX, "i830AdjustFrame: y = %d (+ %d), x = %d (+ %d)\n",
	   x, pI830->xoffset, y, pI830->yoffset);

   if (crtc && crtc->enabled)
   {
      /* Sync the engine before adjust frame */
      i830WaitSync(pScrn);
      i830PipeSetBase(crtc, crtc->desiredX + x, crtc->desiredY + y);
      crtc->x = output->initial_x + x;
      crtc->y = output->initial_y + y;
   }
}

static void
I830FreeScreen(int scrnIndex, int flags)
{
#ifdef INTEL_XVMC
    ScrnInfoPtr pScrn = xf86Screens[scrnIndex];
    I830Ptr pI830 = I830PTR(pScrn);
    if (pI830 && pI830->XvMCEnabled)
	intel_xvmc_finish(xf86Screens[scrnIndex]);
#endif
   I830FreeRec(xf86Screens[scrnIndex]);
   if (xf86LoaderCheckSymbol("vgaHWFreeHWRec"))
      vgaHWFreeHWRec(xf86Screens[scrnIndex]);
}

static void
I830LeaveVT(int scrnIndex, int flags)
{
   ScrnInfoPtr pScrn = xf86Screens[scrnIndex];
   I830Ptr pI830 = I830PTR(pScrn);
#ifndef HAVE_FREE_SHADOW
   xf86CrtcConfigPtr config = XF86_CRTC_CONFIG_PTR(pScrn);
   int o;
#endif

   DPRINTF(PFX, "Leave VT\n");

   pI830->leaving = TRUE;

   if (pI830->devicesTimer)
      TimerCancel(pI830->devicesTimer);
   pI830->devicesTimer = NULL;

   i830SetHotkeyControl(pScrn, HOTKEY_BIOS_SWITCH);

   if (!I830IsPrimary(pScrn)) {
   	I830Ptr pI8301 = I830PTR(pI830->entityPrivate->pScrn_1);
	if (!pI8301->gtt_acquired) {
		return;
	}
   }

#ifdef XF86DRI
   if (pI830->directRenderingOpen) {
      DRILock(screenInfo.screens[pScrn->scrnIndex], 0);

      I830DRISetVBlankInterrupt (pScrn, FALSE);
      drmCtlUninstHandler(pI830->drmSubFD);
   }
#endif

#ifndef HAVE_FREE_SHADOW
   for (o = 0; o < config->num_crtc; o++) {
       xf86CrtcPtr crtc = config->crtc[o];

       if (crtc->rotatedPixmap || crtc->rotatedData) {
	   crtc->funcs->shadow_destroy(crtc, crtc->rotatedPixmap,
				crtc->rotatedData);
	   crtc->rotatedPixmap = NULL;
	   crtc->rotatedData = NULL;
       }
   }
#else
   xf86RotateFreeShadow(pScrn);
#endif

   xf86_hide_cursors (pScrn);

   I830Sync(pScrn);

   RestoreHWState(pScrn);

   /* Evict everything from the bufmgr, as we're about to lose ownership of
    * the graphics memory.
    */
   if (!pI830->memory_manager)
      intel_bufmgr_fake_evict_all(pI830->bufmgr);
   intel_batch_teardown(pScrn);

   if (!pI830->memory_manager)
      i830_stop_ring(pScrn, TRUE);

   if (pI830->debug_modes) {
      i830CompareRegsToSnapshot(pScrn, "After LeaveVT");
      i830DumpRegs (pScrn);
   }

   if (I830IsPrimary(pScrn))
      i830_unbind_all_memory(pScrn);

#ifdef XF86DRI
   if (pI830->memory_manager) {
      int ret;

      /* Tell the kernel to evict all buffer objects and block GTT usage while
       * we're no longer in control of the chip.
       */
      ret = drmCommandNone(pI830->drmSubFD, DRM_I915_GEM_LEAVEVT);
      if (ret != 0)
	 FatalError("DRM_I915_LEAVEVT failed: %s\n", strerror(ret));
   }
#endif /* XF86DRI */

   if (pI830->useEXA && IS_I965G(pI830))
      gen4_render_state_cleanup(pScrn);

   if (pI830->AccelInfoRec)
      pI830->AccelInfoRec->NeedToSync = FALSE;
}

/*
 * This gets called when gaining control of the VT, and from ScreenInit().
 */
static Bool
I830EnterVT(int scrnIndex, int flags)
{
   ScrnInfoPtr pScrn = xf86Screens[scrnIndex];
   I830Ptr  pI830 = I830PTR(pScrn);

   DPRINTF(PFX, "Enter VT\n");

   /*
    * Only save state once per server generation since that's what most
    * drivers do.  Could change this to save state at each VT enter.
    */
   if (pI830->SaveGeneration != serverGeneration) {
      pI830->SaveGeneration = serverGeneration;
      SaveHWState(pScrn);
   }

   pI830->leaving = FALSE;

#ifdef XF86DRI
   if (pI830->memory_manager) {
      int ret;

      /* Tell the kernel that we're back in control and ready for GTT
       * usage.
       */
      ret = drmCommandNone(pI830->drmSubFD, DRM_I915_GEM_ENTERVT);
      if (ret != 0)
	 FatalError("DRM_I915_ENTERVT failed: %s\n", strerror(ret));
   }
#endif /* XF86DRI */

   if (I830IsPrimary(pScrn))
      if (!i830_bind_all_memory(pScrn))
         return FALSE;

   i830_describe_allocations(pScrn, 1, "");

   /* Update the screen pixmap in case the buffer moved */
   i830_update_front_offset(pScrn);

   intel_batch_init(pScrn);

   if (pI830->useEXA && IS_I965G(pI830))
      gen4_render_state_init(pScrn);

   if (i830_check_error_state(pScrn)) {
      xf86DrvMsg(pScrn->scrnIndex, X_WARNING,
		 "Existing errors found in hardware state.\n");
   }

   /* Re-set up the ring. */
   if (!pI830->memory_manager) {
      i830_stop_ring(pScrn, FALSE);
      i830_start_ring(pScrn);
   }
   if (!pI830->SWCursor)
      I830InitHWCursor(pScrn);

   /* Tell the BIOS that we're in control of mode setting now. */
   i830_init_bios_control(pScrn);

   i830_init_clock_gating(pScrn);

   if (pI830->power_context)
       OUTREG(PWRCTXA, pI830->power_context->offset | PWRCTX_EN);

   /* Clear the framebuffer */
   memset(pI830->FbBase + pScrn->fbOffset, 0,
	  pScrn->virtualY * pScrn->displayWidth * pI830->cpp);

   if (!xf86SetDesiredModes (pScrn))
      return FALSE;
   
   if (pI830->debug_modes) {
      xf86DrvMsg(pScrn->scrnIndex, X_INFO, "Hardware state at EnterVT:\n");
      i830DumpRegs (pScrn);
   }
   i830DescribeOutputConfiguration(pScrn);

#ifdef XF86DRI
   if (pI830->directRenderingEnabled) {
       /* HW status is fixed, we need to set it up before any drm
	* operation which accessing that page, like irq install, etc.
	*/
       if (pI830->starting) {
	   if (pI830->hw_status != NULL && !I830DRISetHWS(pScrn)) {
		   xf86DrvMsg(pScrn->scrnIndex, X_ERROR,
			   "Fail to setup hardware status page.\n");
		   I830DRICloseScreen(pScrn->pScreen);
		   return FALSE;
	   }
	   if (!I830DRIInstIrqHandler(pScrn)) {
	       I830DRICloseScreen(pScrn->pScreen);
	       return FALSE;
	   }
       }

      /* Update buffer offsets in sarea and mappings, since buffer offsets
       * may have changed.
       */
      if (!i830_update_dri_buffers(pScrn))
	 FatalError("i830_update_dri_buffers() failed\n");

      I830DRISetVBlankInterrupt (pScrn, TRUE);

      if (!pI830->starting) {
         ScreenPtr pScreen = pScrn->pScreen;
         drmI830Sarea *sarea = (drmI830Sarea *) DRIGetSAREAPrivate(pScreen);
         int i;

	 I830DRIResume(screenInfo.screens[scrnIndex]);

	 if (!pI830->memory_manager)
	    i830_refresh_ring(pScrn);
	 I830Sync(pScrn);

	 sarea->texAge++;
	 for(i = 0; i < I830_NR_TEX_REGIONS+1 ; i++)
	    sarea->texList[i].age = sarea->texAge;

	 DPRINTF(PFX, "calling dri unlock\n");
	 DRIUnlock(screenInfo.screens[pScrn->scrnIndex]);
      }
      pI830->LockHeld = 0;
   }
#endif

   /* Set the hotkey to just notify us.  We can check its results periodically
    * in the CheckDevicesTimer.  Eventually we want the kernel to just hand us
    * an input event when someone presses the button, but for now we just have
    * to poll.
    */
   i830SetHotkeyControl(pScrn, HOTKEY_DRIVER_NOTIFY);

   if (pI830->checkDevices)
      pI830->devicesTimer = TimerSet(NULL, 0, 1000, I830CheckDevicesTimer, pScrn);

   /* Mark 3D state as being clobbered and setup the basics */
   *pI830->last_3d = LAST_3D_OTHER;
   IntelEmitInvarientState(pScrn);

   return TRUE;
}

static Bool
I830SwitchMode(int scrnIndex, DisplayModePtr mode, int flags)
{
   ScrnInfoPtr pScrn = xf86Screens[scrnIndex];
   I830Ptr pI830 = I830PTR(pScrn);

   return xf86SetSingleMode (pScrn, mode, pI830->rotation);
}

static Bool
I830CloseScreen(int scrnIndex, ScreenPtr pScreen)
{
   ScrnInfoPtr pScrn = xf86Screens[scrnIndex];
   I830Ptr pI830 = I830PTR(pScrn);
#ifdef I830_USE_XAA
   XAAInfoRecPtr infoPtr = pI830->AccelInfoRec;
#endif

   pI830->closing = TRUE;

   if (pScrn->vtSema == TRUE) {
      I830LeaveVT(scrnIndex, 0);
   }

   dri_bufmgr_destroy(pI830->bufmgr);
   pI830->bufmgr = NULL;

   if (pI830->devicesTimer)
      TimerCancel(pI830->devicesTimer);
   pI830->devicesTimer = NULL;

   DPRINTF(PFX, "\nUnmapping memory\n");
   I830UnmapMem(pScrn);
   vgaHWUnmapMem(pScrn);

   if (pI830->ScanlineColorExpandBuffers) {
      xfree(pI830->ScanlineColorExpandBuffers);
      pI830->ScanlineColorExpandBuffers = NULL;
   }
#ifdef I830_USE_XAA
   if (infoPtr) {
      if (infoPtr->ScanlineColorExpandBuffers)
	 xfree(infoPtr->ScanlineColorExpandBuffers);
      XAADestroyInfoRec(infoPtr);
      pI830->AccelInfoRec = NULL;
   }
#endif
#ifdef I830_USE_EXA
   if (pI830->EXADriverPtr) {
       exaDriverFini(pScreen);
       xfree(pI830->EXADriverPtr);
       pI830->EXADriverPtr = NULL;
   }
#endif
#ifdef I830_USE_UXA
   if (pI830->uxa_driver) {
       uxa_driver_fini (pScreen);
       xfree (pI830->uxa_driver);
       pI830->uxa_driver = NULL;
   }
#endif
   xf86_cursors_fini (pScreen);

   i830_allocator_fini(pScrn);
#ifdef XF86DRI
   if (pI830->directRenderingOpen) {
#ifdef DAMAGE
      if (pI830->pDamage) {
	 PixmapPtr pPix = pScreen->GetScreenPixmap(pScreen);

	 DamageUnregister(&pPix->drawable, pI830->pDamage);
	 DamageDestroy(pI830->pDamage);
	 pI830->pDamage = NULL;
      }
#endif
      pI830->directRenderingOpen = FALSE;
      I830DRICloseScreen(pScreen);
   }
#endif

   if (I830IsPrimary(pScrn)) {
      xf86GARTCloseScreen(scrnIndex);

      xfree(pI830->LpRing);
      pI830->LpRing = NULL;
      xfree(pI830->overlayOn);
      pI830->overlayOn = NULL;
      xfree(pI830->last_3d);
      pI830->last_3d = NULL;
   }

   pScrn->PointerMoved = pI830->PointerMoved;
   pScrn->vtSema = FALSE;
   pI830->closing = FALSE;
   pScreen->CloseScreen = pI830->CloseScreen;
   return (*pScreen->CloseScreen) (scrnIndex, pScreen);
}

static ModeStatus
I830ValidMode(int scrnIndex, DisplayModePtr mode, Bool verbose, int flags)
{
   if (mode->Flags & V_INTERLACE) {
      if (verbose) {
	 xf86DrvMsg(scrnIndex, X_PROBED,
		    "Removing interlaced mode \"%s\"\n", mode->name);
      }
      return MODE_BAD;
   }
   return MODE_OK;
}

#ifndef SUSPEND_SLEEP
#define SUSPEND_SLEEP 0
#endif
#ifndef RESUME_SLEEP
#define RESUME_SLEEP 0
#endif

/*
 * This function is only required if we need to do anything differently from
 * DoApmEvent() in common/xf86PM.c, including if we want to see events other
 * than suspend/resume.
 */
static Bool
I830PMEvent(int scrnIndex, pmEvent event, Bool undo)
{
   ScrnInfoPtr pScrn = xf86Screens[scrnIndex];
   I830Ptr pI830 = I830PTR(pScrn);

   DPRINTF(PFX, "Enter VT, event %d, undo: %s\n", event, BOOLTOSTRING(undo));
 
   switch(event) {
   case XF86_APM_SYS_SUSPEND:
   case XF86_APM_CRITICAL_SUSPEND: /*do we want to delay a critical suspend?*/
   case XF86_APM_USER_SUSPEND:
   case XF86_APM_SYS_STANDBY:
   case XF86_APM_USER_STANDBY:
      if (!undo && !pI830->suspended) {
	 pScrn->LeaveVT(scrnIndex, 0);
	 pI830->suspended = TRUE;
	 sleep(SUSPEND_SLEEP);
      } else if (undo && pI830->suspended) {
	 sleep(RESUME_SLEEP);
	 pScrn->EnterVT(scrnIndex, 0);
	 pI830->suspended = FALSE;
      }
      break;
   case XF86_APM_STANDBY_RESUME:
   case XF86_APM_NORMAL_RESUME:
   case XF86_APM_CRITICAL_RESUME:
      if (pI830->suspended) {
	 sleep(RESUME_SLEEP);
	 pScrn->EnterVT(scrnIndex, 0);
	 pI830->suspended = FALSE;
	 /*
	  * Turn the screen saver off when resuming.  This seems to be
	  * needed to stop xscreensaver kicking in (when used).
	  *
	  * XXX DoApmEvent() should probably call this just like
	  * xf86VTSwitch() does.  Maybe do it here only in 4.2
	  * compatibility mode.
	  */
	 SaveScreens(SCREEN_SAVER_FORCER, ScreenSaverReset);
      }
      break;
   /* This is currently used for ACPI */
   case XF86_APM_CAPABILITY_CHANGED:
#if 0
      /* If we had status checking turned on, turn it off now */
      if (pI830->checkDevices) {
         if (pI830->devicesTimer)
            TimerCancel(pI830->devicesTimer);
         pI830->devicesTimer = NULL;
         pI830->checkDevices = FALSE; 
      }
#endif
      if (!I830IsPrimary(pScrn))
         return TRUE;

      ErrorF("I830PMEvent: Capability change\n");

      I830CheckDevicesTimer(NULL, 0, pScrn);
      SaveScreens(SCREEN_SAVER_FORCER, ScreenSaverReset);
      if (pI830->quirk_flag & QUIRK_RESET_MODES)
	 xf86SetDesiredModes(pScrn);

      break;
   default:
      ErrorF("I830PMEvent: received APM event %d\n", event);
   }
   return TRUE;
}

xf86CrtcPtr
i830_pipe_to_crtc(ScrnInfoPtr pScrn, int pipe)
{
   xf86CrtcConfigPtr config = XF86_CRTC_CONFIG_PTR (pScrn);
   int c;
   
   for (c = 0; c < config->num_crtc; c++) {
      xf86CrtcPtr crtc = config->crtc[c];
      I830CrtcPrivatePtr intel_crtc = crtc->driver_private;

      if (intel_crtc->pipe == pipe)
	  return crtc;
   }

   return NULL;
} 

#if 0
/**
 * This function is used for testing of the screen detect functions from the
 * periodic timer.
 */
static void
i830MonitorDetectDebugger(ScrnInfoPtr pScrn)
{
   Bool found_crt;
   I830Ptr pI830 = I830PTR(pScrn);
   int start, finish, i;

   if (!pScrn->vtSema)
      return 1000;

   for (i = 0; i < xf86_config->num_output; i++) {
      enum output_status ret;
      char *result;

      start = GetTimeInMillis();
      ret = pI830->output[i].detect(pScrn, &pI830->output[i]);
      finish = GetTimeInMillis();

      if (ret == OUTPUT_STATUS_CONNECTED)
	 result = "connected";
      else if (ret == OUTPUT_STATUS_DISCONNECTED)
	 result = "disconnected";
      else
	 result = "unknown";

      xf86DrvMsg(pScrn->scrnIndex, X_ERROR, "Detected SDVO as %s in %dms\n",
		 result, finish - start);
   }
}
#endif

static CARD32
I830CheckDevicesTimer(OsTimerPtr timer, CARD32 now, pointer arg)
{
   ScrnInfoPtr pScrn = (ScrnInfoPtr) arg;
   I830Ptr pI830 = I830PTR(pScrn);
   uint8_t gr18;

   if (!pScrn->vtSema)
      return 1000;

#if 0
   i830MonitorDetectDebugger(pScrn);
#endif

   /* Check for a hotkey press report from the BIOS. */
   gr18 = pI830->readControl(pI830, GRX, 0x18);
   if ((gr18 & (HOTKEY_TOGGLE | HOTKEY_SWITCH)) != 0) {
      /* The user has pressed the hotkey requesting a toggle or switch.
       * Re-probe our connected displays and turn on whatever we find.
       *
       * In the future, we want the hotkey to dump down to a user app which
       * implements a sensible policy using RandR-1.2.  For now, all we get
       * is this.
       */
      
      xf86ProbeOutputModes (pScrn, 0, 0);
      xf86SetScrnInfoModes (pScrn);
      xf86DiDGAReInit (pScrn->pScreen);
      xf86SwitchMode(pScrn->pScreen, pScrn->currentMode);

      /* Clear the BIOS's hotkey press flags */
      gr18 &= ~(HOTKEY_TOGGLE | HOTKEY_SWITCH);
      pI830->writeControl(pI830, GRX, 0x18, gr18);
   }

   return 1000;
}

void
i830WaitSync(ScrnInfoPtr pScrn)
{
   I830Ptr pI830 = I830PTR(pScrn);

   switch (pI830->accel) {
#ifdef I830_USE_XAA
   case ACCEL_XAA:
      if (pI830->AccelInfoRec && pI830->AccelInfoRec->NeedToSync) {
	 (*pI830->AccelInfoRec->Sync)(pScrn);
	 pI830->AccelInfoRec->NeedToSync = FALSE;
      }
      break;
#endif
#ifdef I830_USE_EXA
   case ACCEL_EXA:
      if (pI830->EXADriverPtr) {
	 ScreenPtr pScreen = screenInfo.screens[pScrn->scrnIndex];
	 exaWaitSync(pScreen);
      }
      break;
#endif
#ifdef I830_USE_UXA
   case ACCEL_UXA:
      if (pI830->uxa_driver) {
	 ScreenPtr pScreen = screenInfo.screens[pScrn->scrnIndex];
	 uxa_wait_sync(pScreen);
      }
      break;
#endif
   default:
      break;
   }
}

void
i830MarkSync(ScrnInfoPtr pScrn)
{
   I830Ptr pI830 = I830PTR(pScrn);

   switch (pI830->accel) {
#ifdef I830_USE_XAA
   case ACCEL_XAA:
      if (pI830->AccelInfoRec)
	 pI830->AccelInfoRec->NeedToSync = TRUE;
      break;
#endif
#ifdef I830_USE_EXA
   case ACCEL_EXA:
      if (pI830->EXADriverPtr) {
	 ScreenPtr pScreen = screenInfo.screens[pScrn->scrnIndex];
	 exaMarkSync(pScreen);
      }
      break;
#endif
#ifdef I830_USE_UXA
   case ACCEL_UXA:
      if (pI830->uxa_driver) {
	 ScreenPtr pScreen = screenInfo.screens[pScrn->scrnIndex];
	 exaMarkSync(pScreen);
      }
      break;
#endif
   default:
      break;
   }
}

void
I830InitpScrn(ScrnInfoPtr pScrn)
{
   pScrn->PreInit = I830PreInit;
   pScrn->ScreenInit = I830ScreenInit;
   pScrn->SwitchMode = I830SwitchMode;
   pScrn->AdjustFrame = i830AdjustFrame;
   pScrn->EnterVT = I830EnterVT;
   pScrn->LeaveVT = I830LeaveVT;
   pScrn->FreeScreen = I830FreeScreen;
   pScrn->ValidMode = I830ValidMode;
   pScrn->PMEvent = I830PMEvent;
}