summaryrefslogtreecommitdiff
path: root/driver/xf86-video-intel/src/legacy/i810/i810_driver.c
blob: 5ac646370777e0bfc004a3a04b8d1d78f99e1f26 (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

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

Copyright 1998-1999 Precision Insight, Inc., Cedar Park, Texas.
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 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 PRECISION INSIGHT AND/OR ITS 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.

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

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

/*
 * Authors:
 *   Keith Whitwell <keith@tungstengraphics.com>
 *
 * Add ARGB HW cursor support:
 *   Alan Hourihane <alanh@tungstengraphics.com>
 *
 */

/*
 * This server does not support these XFree86 4.0 features yet
 * shadowFb (if requested or acceleration is off)
 * Overlay planes
 * DGA
 */

#include <math.h>
#include <string.h>
#include <unistd.h>

/*
 * These are X and server generic header files.
 */
#include "xf86.h"
#include "xf86_OSproc.h"
#include "xf86cmap.h"

#include "compiler.h"
#include "mibstore.h"
#include "vgaHW.h"
#include "mipointer.h"
#include "micmap.h"

#include "fb.h"
#include "miscstruct.h"
#include "xf86xv.h"
#include <X11/extensions/Xv.h>
#include "vbe.h"
#include "xf86fbman.h"

#include "i810.h"

#ifdef HAVE_DRI1
#include "dri.h"
#endif

#include "../legacy.h"

static Bool I810PreInit(ScrnInfoPtr pScrn, int flags);
static Bool I810ScreenInit(SCREEN_INIT_ARGS_DECL);
static Bool I810EnterVT(VT_FUNC_ARGS_DECL);
static void I810LeaveVT(VT_FUNC_ARGS_DECL);
static Bool I810CloseScreen(CLOSE_SCREEN_ARGS_DECL);
static Bool I810SaveScreen(ScreenPtr pScreen, Bool unblank);
static void I810FreeScreen(FREE_SCREEN_ARGS_DECL);
static void I810DisplayPowerManagementSet(ScrnInfoPtr pScrn,
					  int PowerManagermentMode,
					  int flags);
static ModeStatus I810ValidMode(SCRN_ARG_TYPE arg, DisplayModePtr mode,
				Bool verbose, int flags);

typedef enum {
   OPTION_NOACCEL,
   OPTION_SW_CURSOR,
   OPTION_COLOR_KEY,
   OPTION_CACHE_LINES,
   OPTION_DAC_6BIT,
   OPTION_DRI,
   OPTION_NO_DDC,
   OPTION_SHOW_CACHE,
   OPTION_XVMC_SURFACES,
   OPTION_PAGEFLIP
} I810Opts;
 
static const OptionInfoRec I810Options[] = {
   {OPTION_NOACCEL,		"NoAccel",	OPTV_BOOLEAN,	{0}, FALSE},
   {OPTION_SW_CURSOR,		"SWcursor",	OPTV_BOOLEAN,	{0}, FALSE},
   {OPTION_COLOR_KEY,		"ColorKey",	OPTV_INTEGER,	{0}, FALSE},
   {OPTION_CACHE_LINES,		"CacheLines",	OPTV_INTEGER,	{0}, FALSE},
   {OPTION_DAC_6BIT,		"Dac6Bit",	OPTV_BOOLEAN,	{0}, FALSE},
   {OPTION_DRI,			"DRI",		OPTV_BOOLEAN,	{0}, FALSE},
   {OPTION_NO_DDC,		"NoDDC",	OPTV_BOOLEAN,	{0}, FALSE},
   {OPTION_SHOW_CACHE,		"ShowCache",	OPTV_BOOLEAN,	{0}, FALSE},
   {OPTION_XVMC_SURFACES,	"XvMCSurfaces",	OPTV_INTEGER,	{0}, FALSE},
   {OPTION_PAGEFLIP,            "PageFlip",     OPTV_BOOLEAN, {0},   FALSE},
   {-1,				NULL,		OPTV_NONE,	{0}, FALSE}
};
/* *INDENT-ON* */

#ifndef I810_DEBUG
int I810_DEBUG = (0
/*     		  | DEBUG_ALWAYS_SYNC  */
/*    		  | DEBUG_VERBOSE_ACCEL */
/*  		  | DEBUG_VERBOSE_SYNC */
/*  		  | DEBUG_VERBOSE_VGA */
/*  		  | DEBUG_VERBOSE_RING */
/*  		  | DEBUG_VERBOSE_OUTREG */
/*  		  | DEBUG_VERBOSE_MEMORY */
/*  		  | DEBUG_VERBOSE_CURSOR */
      );
#endif

#ifdef HAVE_DRI1
static int i810_pitches[] = {
   512,
   1024,
   2048,
   4096,
   0
};
#endif

/*
 * I810GetRec and I810FreeRec --
 *
 * Private data for the driver is stored in the screen structure.
 * These two functions create and destroy that private data.
 *
 */
static Bool
I810GetRec(ScrnInfoPtr scrn)
{
   if (scrn->driverPrivate != NULL)
      return TRUE;

   scrn->driverPrivate = xnfcalloc(sizeof(I810Rec), 1);
   return TRUE;
}

static void
I810FreeRec(ScrnInfoPtr scrn)
{
   if (!scrn)
      return;
   if (!scrn->driverPrivate)
      return;
   free(scrn->driverPrivate);
   scrn->driverPrivate = NULL;
}

struct pci_device *
intel_host_bridge (void)
{
    static const struct pci_slot_match bridge_match = {
	0, 0, 0, PCI_MATCH_ANY, 0
    };
    struct pci_device_iterator	*slot_iterator;
    struct pci_device		*bridge;

    slot_iterator = pci_slot_match_iterator_create (&bridge_match);
    bridge = pci_device_next (slot_iterator);
    pci_iterator_destroy (slot_iterator);
    return bridge;
}

static void
I810ProbeDDC(ScrnInfoPtr scrn, int index)
{
   vbeInfoPtr pVbe;

   if (xf86LoadSubModule(scrn, "vbe")) {
      pVbe = VBEInit(NULL, index);
      ConfiguredMonitor = vbeDoEDID(pVbe, NULL);
      vbeFree(pVbe);
   }
}

static xf86MonPtr
I810DoDDC(ScrnInfoPtr scrn, int index)
{
   vbeInfoPtr pVbe;
   xf86MonPtr MonInfo = NULL;
   I810Ptr pI810 = I810PTR(scrn);

   /* Honour Option "noDDC" */
   if (xf86ReturnOptValBool(pI810->Options, OPTION_NO_DDC, FALSE)) {
      return MonInfo;
   }

   if (xf86LoadSubModule(scrn, "vbe") && (pVbe = VBEInit(NULL, index))) {
      MonInfo = vbeDoEDID(pVbe, NULL);
      xf86PrintEDID(MonInfo);
      xf86SetDDCproperties(scrn, MonInfo);
      vbeFree(pVbe);
   } else {
      xf86DrvMsg(scrn->scrnIndex, X_INFO,
		 "this driver cannot do DDC without VBE\n");
   }

   return MonInfo;
}

/*
 * I810PreInit --
 *
 * Do initial setup of the board before we know what resolution we will
 * be running at.
 *
 */
static Bool
I810PreInit(ScrnInfoPtr scrn, int flags)
{
   vgaHWPtr hwp;
   I810Ptr pI810;
   ClockRangePtr clockRanges;
   int i;
   MessageType from;
   int flags24;
   rgb defaultWeight = { 0, 0, 0 };
   int mem;
   Bool enable;
   struct intel_chipset chipset;

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

   /* Allocate driverPrivate */
   if (!I810GetRec(scrn))
      return FALSE;

   pI810 = I810PTR(scrn);

   pI810->pEnt = xf86GetEntityInfo(scrn->entityList[0]);
   if (pI810->pEnt == NULL || pI810->pEnt->location.type != BUS_PCI)
      return FALSE;

   if (flags & PROBE_DETECT) {
      I810ProbeDDC(scrn, pI810->pEnt->index);
      return TRUE;
   }

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

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

   hwp = VGAHWPTR(scrn);
   vgaHWSetStdFuncs(hwp);

   pI810->PciInfo = xf86GetPciInfoForEntity(pI810->pEnt->index);

   /* Set scrn->monitor */
   scrn->monitor = scrn->confScreen->monitor;

   flags24 = Support24bppFb | PreferConvert32to24 | SupportConvert32to24;
   if (!xf86SetDepthBpp(scrn, 16, 0, 16, flags24)) {
      return FALSE;
   } else {
      switch (scrn->depth) {
      case 8:
      case 15:
      case 16:
      case 24:
	 break;
      default:
	 xf86DrvMsg(scrn->scrnIndex, X_ERROR,
		    "Given depth (%d) is not supported by i810 driver\n",
		    scrn->depth);
	 return FALSE;
      }
   }
   xf86PrintDepthBpp(scrn);

   switch (scrn->bitsPerPixel) {
   case 8:
   case 16:
   case 24:
      break;
   default:
      xf86DrvMsg(scrn->scrnIndex, X_ERROR,
		 "Given bpp (%d) is not supported by i810 driver\n",
		 scrn->bitsPerPixel);
      return FALSE;
   }

   if (!xf86SetWeight(scrn, defaultWeight, defaultWeight))
      return FALSE;

   if (!xf86SetDefaultVisual(scrn, -1))
      return FALSE;

   /* We use a programmable clock */
   scrn->progClock = TRUE;

   pI810->cpp = scrn->bitsPerPixel / 8;

   /* Process the options */
   xf86CollectOptions(scrn, NULL);
   if (!(pI810->Options = malloc(sizeof(I810Options))))
      return FALSE;
   memcpy(pI810->Options, I810Options, sizeof(I810Options));
   xf86ProcessOptions(scrn->scrnIndex, scrn->options, pI810->Options);

   scrn->rgbBits = 8;
   if (xf86ReturnOptValBool(pI810->Options, OPTION_DAC_6BIT, FALSE))
      scrn->rgbBits = 6;

   if (xf86ReturnOptValBool(pI810->Options, OPTION_SHOW_CACHE, FALSE))
     pI810->showCache = TRUE;
   else
     pI810->showCache = FALSE;

   /* 6-BIT dac isn't reasonable for modes with > 8bpp */
   if (xf86ReturnOptValBool(pI810->Options, OPTION_DAC_6BIT, FALSE) &&
       scrn->bitsPerPixel > 8) {
      OptionInfoPtr ptr;

      ptr = xf86TokenToOptinfo(pI810->Options, OPTION_DAC_6BIT);
      ptr->found = FALSE;
   }

   if (xf86ReturnOptValBool(pI810->Options, OPTION_NOACCEL, FALSE))
      pI810->noAccel = TRUE;

   if (!pI810->noAccel && !xf86LoadSubModule(scrn, "xaa"))
      pI810->noAccel = TRUE;
   
#ifdef HAVE_DRI1
   pI810->directRenderingDisabled =
     !xf86ReturnOptValBool(pI810->Options, OPTION_DRI, TRUE);

   if (!pI810->directRenderingDisabled) {
     if (scrn->depth!=16) {
       xf86DrvMsg(scrn->scrnIndex, X_WARNING, "DRI is disabled because it "
		  "runs only at 16-bit depth.\n");
       pI810->directRenderingDisabled=TRUE;
     }
   }
#endif

   /* Get DDC info from monitor */
   /* after xf86ProcessOptions,
    * because it is controlled by options [no]vbe and [no]ddc
    */
   I810DoDDC(scrn, pI810->pEnt->index);

   intel_detect_chipset(scrn, pI810->PciInfo, &chipset);

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

   xf86DrvMsg(scrn->scrnIndex, from, "Chipset: \"%s\"\n",
	      (scrn->chipset != NULL) ? scrn->chipset : "Unknown i810");
   
   pI810->LinearAddr = pI810->PciInfo->regions[0].base_addr;
   xf86DrvMsg(scrn->scrnIndex, X_PROBED, "Linear framebuffer at 0x%lX\n",
	      (unsigned long)pI810->LinearAddr);

   pI810->MMIOAddr = pI810->PciInfo->regions[1].base_addr;
   xf86DrvMsg(scrn->scrnIndex, X_PROBED, "IO registers at addr 0x%lX\n",
	      (unsigned long)pI810->MMIOAddr);

   /* AGP GART support is required.  Don't proceed any further if it isn't
    * present.
    */
   if (!xf86AgpGARTSupported()) {
      xf86DrvMsg(scrn->scrnIndex, X_ERROR,
		 "AGP GART support is not available.  Make sure your kernel has\n"
		 "\tagpgart support or that the agpgart kernel module is loaded.\n");
      return FALSE;
   }

   /* Find out memory bus frequency.
    */
   {
      uint32_t whtcfg_pamr_drp;
    
      pci_device_cfg_read_u32(pI810->PciInfo, & whtcfg_pamr_drp, WHTCFG_PAMR_DRP);

      /* Need this for choosing watermarks.
       */
      if ((whtcfg_pamr_drp & LM_FREQ_MASK) == LM_FREQ_133)
	 pI810->LmFreqSel = 133;
      else
	 pI810->LmFreqSel = 100;
   }

   /* Default to 4MB framebuffer, which is sufficient for all
    * supported 2d resolutions.  If the user has specified a different
    * size in the XF86Config, use that amount instead.
    *
    *  Changed to 8 Meg so we can have acceleration by default (Mark).
    */
   mem = I810CheckAvailableMemory(scrn);
   if (pI810->directRenderingDisabled || mem < 131072)  /* < 128 MB */
       scrn->videoRam = 8192;
   else if (mem < 196608)
       scrn->videoRam = 16384;  /* < 192 MB */
   else
       scrn->videoRam = 24576;
   
   from = X_DEFAULT;
   
   if (pI810->pEnt->device->videoRam) {
      scrn->videoRam = pI810->pEnt->device->videoRam;
      from = X_CONFIG;
   }

   if (mem > 0 && mem < scrn->videoRam) {
      xf86DrvMsg(scrn->scrnIndex, X_WARNING, "%dk of memory was requested,"
		 " but the\n\t maximum AGP memory available is %dk.\n",
		 scrn->videoRam, mem);
      from = X_PROBED;
      if (mem > (6 * 1024)) {
	 xf86DrvMsg(scrn->scrnIndex, X_INFO,
		    "Reducing video memory to 4MB\n");
	 scrn->videoRam = 4096;
      } else {
	 xf86DrvMsg(scrn->scrnIndex, X_ERROR, "Less than 6MB of AGP memory"
		    " is available. Cannot proceed.\n");
	 I810FreeRec(scrn);
	 return FALSE;
      }
   }

   xf86DrvMsg(scrn->scrnIndex, from,
	      "Will alloc AGP framebuffer: %d kByte\n", scrn->videoRam);

   /* Calculate Fixed Offsets depending on graphics aperture size */
   {
      struct pci_device *bridge = intel_host_bridge ();
      uint32_t   smram_miscc;
      
      pci_device_cfg_read_u32 (bridge, & smram_miscc, SMRAM_MISCC);

      if ((smram_miscc & GFX_MEM_WIN_SIZE) == GFX_MEM_WIN_32M) {
	 pI810->FbMapSize = 0x1000000;
	 pI810->DepthOffset = 0x1000000;
	 pI810->BackOffset = 0x1800000;
      } else {
	 pI810->FbMapSize = 0x3000000;
	 pI810->DepthOffset = 0x3000000;
	 pI810->BackOffset = 0x3800000;
      }
   }

   /*
    * If the driver can do gamma correction, it should call xf86SetGamma()
    * here.
    */
   {
      Gamma zeros = { 0.0, 0.0, 0.0 };

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

   pI810->MaxClock = 0;
   if (pI810->pEnt->device->dacSpeeds[0]) {
      switch (scrn->bitsPerPixel) {
      case 8:
	 pI810->MaxClock = pI810->pEnt->device->dacSpeeds[DAC_BPP8];
	 break;
      case 16:
	 pI810->MaxClock = pI810->pEnt->device->dacSpeeds[DAC_BPP16];
	 break;
      case 24:
	 pI810->MaxClock = pI810->pEnt->device->dacSpeeds[DAC_BPP24];
	 break;
      case 32:				/* not supported */
	 pI810->MaxClock = pI810->pEnt->device->dacSpeeds[DAC_BPP32];
	 break;
      }
      if (!pI810->MaxClock)
	 pI810->MaxClock = pI810->pEnt->device->dacSpeeds[0];
   } else {
      switch (scrn->bitsPerPixel) {
      case 8:
	 pI810->MaxClock = 203000;
	 break;
      case 16:
	 pI810->MaxClock = 163000;
	 break;
      case 24:
	 pI810->MaxClock = 136000;
	 break;
      case 32:				/* not supported */
	 pI810->MaxClock = 86000;
      }
   }
   clockRanges = xnfcalloc(sizeof(ClockRange), 1);
   clockRanges->next = NULL;
   /* 9.4MHz appears to be the smallest that works. */
   clockRanges->minClock = 9500;
   clockRanges->maxClock = pI810->MaxClock;
   clockRanges->clockIndex = -1;
   clockRanges->interlaceAllowed = TRUE;
   clockRanges->doubleScanAllowed = FALSE;

   i = xf86ValidateModes(scrn, scrn->monitor->Modes,
			 scrn->display->modes, clockRanges,
#ifndef HAVE_DRI1
			 0, 320, 1600, 64 * scrn->bitsPerPixel,
#else
			 i810_pitches, 0, 0, 64 * scrn->bitsPerPixel,
#endif
			 200, 1200,
			 scrn->display->virtualX, scrn->display->virtualY,
			 scrn->videoRam * 1024, LOOKUP_BEST_REFRESH);

   if (i == -1) {
      I810FreeRec(scrn);
      return FALSE;
   }

   xf86PruneDriverModes(scrn);

   if (!i || !scrn->modes) {
      xf86DrvMsg(scrn->scrnIndex, X_ERROR, "No valid modes found\n");
      I810FreeRec(scrn);
      return FALSE;
   }

   xf86SetCrtcForModes(scrn, INTERLACE_HALVE_V);

   scrn->currentMode = scrn->modes;

   xf86PrintModes(scrn);

   xf86SetDpi(scrn, 0, 0);

   if (!xf86LoadSubModule(scrn, "fb")) {
      I810FreeRec(scrn);
      return FALSE;
   }

   if (!xf86ReturnOptValBool(pI810->Options, OPTION_SW_CURSOR, FALSE)) {
      if (!xf86LoadSubModule(scrn, "ramdac")) {
	 I810FreeRec(scrn);
	 return FALSE;
      }
   }

   if (xf86GetOptValInteger
       (pI810->Options, OPTION_COLOR_KEY, &(pI810->colorKey))) {
      xf86DrvMsg(scrn->scrnIndex, X_CONFIG,
		 "video overlay key set to 0x%x\n", pI810->colorKey);
   } else {
      pI810->colorKey = (1 << scrn->offset.red) |
	    (1 << scrn->offset.green) |
	    (((scrn->mask.blue >> scrn->offset.blue) -
	      1) << scrn->offset.blue);
   }

   pI810->allowPageFlip=FALSE;
   enable = xf86ReturnOptValBool(pI810->Options, OPTION_PAGEFLIP, FALSE);   

#ifdef HAVE_DRI1
   if (!pI810->directRenderingDisabled) {
     pI810->allowPageFlip = enable;
     if (pI810->allowPageFlip == TRUE)
     {
       if (!xf86LoadSubModule(scrn, "shadowfb")) {
	 pI810->allowPageFlip = 0;
	 xf86DrvMsg(scrn->scrnIndex, X_ERROR, 
		    "Couldn't load shadowfb module:\n");
       }
     }
     
     xf86DrvMsg(scrn->scrnIndex, X_CONFIG, "page flipping %s\n",
		enable ? "enabled" : "disabled");
     
   }
#endif

   if (xf86GetOptValInteger(pI810->Options, OPTION_XVMC_SURFACES,
			    &(pI810->numSurfaces))) {
      xf86DrvMsg(scrn->scrnIndex, X_CONFIG, "%d XvMC Surfaces Requested.\n",
		 pI810->numSurfaces);
      if (pI810->numSurfaces > 7) {
	 xf86DrvMsg(scrn->scrnIndex, X_PROBED,
		    "Using 7 XvMC Surfaces (Maximum Allowed).\n");
	 pI810->numSurfaces = 7;
      }
      if (pI810->numSurfaces < 6) {
	 xf86DrvMsg(scrn->scrnIndex, X_PROBED,
		    "Using 6 XvMC Surfaces (Minimum Allowed).\n");
	 pI810->numSurfaces = 6;
      }
   } else {
      xf86DrvMsg(scrn->scrnIndex, X_INFO,
		 "XvMC is Disabled: use XvMCSurfaces config option to enable.\n");
      pI810->numSurfaces = 0;
   }

#ifdef HAVE_DRI1
   /* Load the dri module if requested. */
   if (xf86ReturnOptValBool(pI810->Options, OPTION_DRI, FALSE)) {
      xf86LoadSubModule(scrn, "dri");
   }
#endif

   return TRUE;
}

static Bool
I810MapMMIO(ScrnInfoPtr scrn)
{
   I810Ptr pI810 = I810PTR(scrn);
   struct pci_device *const device = pI810->PciInfo;
   int err;

   err = pci_device_map_range (device,
			       pI810->MMIOAddr,
			       I810_REG_SIZE,
			       PCI_DEV_MAP_FLAG_WRITABLE,
			       (void **) &pI810->MMIOBase);
   if (err) 
   {
      xf86DrvMsg (scrn->scrnIndex, X_ERROR,
		  "Unable to map mmio BAR. %s (%d)\n",
		  strerror (err), err);
      return FALSE;
   }
   return TRUE;
}

static Bool
I810MapMem(ScrnInfoPtr scrn)
{
   I810Ptr pI810 = I810PTR(scrn);
   struct pci_device *const device = pI810->PciInfo;
   int err;

   if (!I810MapMMIO(scrn))
      return FALSE;

   err = pci_device_map_range (device,
			       pI810->LinearAddr,
			       pI810->FbMapSize,
			       PCI_DEV_MAP_FLAG_WRITABLE | PCI_DEV_MAP_FLAG_WRITE_COMBINE,
			       (void **) &pI810->FbBase);
   if (err) 
   {
      xf86DrvMsg (scrn->scrnIndex, X_ERROR,
		  "Unable to map frame buffer BAR. %s (%d)\n",
		  strerror (err), err);
      return FALSE;
   }

   pI810->LpRing->virtual_start = pI810->FbBase + pI810->LpRing->mem.Start;

   return TRUE;
}

static void
I810UnmapMMIO(ScrnInfoPtr scrn)
{
   I810Ptr pI810 = I810PTR(scrn);

   pci_device_unmap_range (pI810->PciInfo, pI810->MMIOBase, I810_REG_SIZE);
   pI810->MMIOBase = NULL;
}

static Bool
I810UnmapMem(ScrnInfoPtr scrn)
{
   I810Ptr pI810 = I810PTR(scrn);

   pci_device_unmap_range (pI810->PciInfo, pI810->FbBase, pI810->FbMapSize);
   pI810->FbBase = NULL;
   I810UnmapMMIO(scrn);
   return TRUE;
}

/* Famous last words
 */
void
I810PrintErrorState(ScrnInfoPtr scrn)
{
   I810Ptr pI810 = I810PTR(scrn);

   ErrorF("pgetbl_ctl: 0x%lx pgetbl_err: 0x%lx\n",
	  (unsigned long) INREG(PGETBL_CTL), (unsigned long) INREG(PGE_ERR));

   ErrorF("ipeir: %lx iphdr: %lx\n", (unsigned long) INREG(IPEIR), 
	  (unsigned long) INREG(IPEHR));

   ErrorF("LP ring tail: %lx head: %lx len: %lx start %lx\n",
	  (unsigned long) INREG(LP_RING + RING_TAIL),
	  (unsigned long) INREG(LP_RING + RING_HEAD) & HEAD_ADDR,
	  (unsigned long) INREG(LP_RING + RING_LEN), 
	  (unsigned long) INREG(LP_RING + RING_START));

   ErrorF("eir: %x esr: %x emr: %x\n",
	  INREG16(EIR), INREG16(ESR), INREG16(EMR));

   ErrorF("instdone: %x instpm: %x\n", INREG16(INST_DONE), INREG8(INST_PM));

   ErrorF("memmode: %lx instps: %lx\n", (unsigned long) INREG(MEMMODE), 
	  (unsigned long) INREG(INST_PS));

   ErrorF("hwstam: %x ier: %x imr: %x iir: %x\n",
	  INREG16(HWSTAM), INREG16(IER), INREG16(IMR), INREG16(IIR));
}

/*
 * I810Save --
 *
 * This function saves the video state.  It reads all of the SVGA registers
 * into the vgaI810Rec data structure.  There is in general no need to
 * mask out bits here - just read the registers.
 */
static void
DoSave(ScrnInfoPtr scrn, vgaRegPtr vgaReg, I810RegPtr i810Reg,
       Bool saveFonts)
{
   I810Ptr pI810;
   vgaHWPtr hwp;
   int i;

   pI810 = I810PTR(scrn);
   hwp = VGAHWPTR(scrn);

   /*
    * This function will handle creating the data structure and filling
    * in the generic VGA portion.
    */
   if (saveFonts)
      vgaHWSave(scrn, vgaReg, VGA_SR_MODE | VGA_SR_FONTS | VGA_SR_CMAP);
   else
      vgaHWSave(scrn, vgaReg, VGA_SR_MODE | VGA_SR_CMAP);

   /*
    * The port I/O code necessary to read in the extended registers
    * into the fields of the vgaI810Rec structure goes here.
    */
   i810Reg->IOControl = hwp->readCrtc(hwp, IO_CTNL);
   i810Reg->AddressMapping = hwp->readGr(hwp, ADDRESS_MAPPING);
   i810Reg->BitBLTControl = INREG8(BITBLT_CNTL);
   i810Reg->VideoClk2_M = INREG16(VCLK2_VCO_M);
   i810Reg->VideoClk2_N = INREG16(VCLK2_VCO_N);
   i810Reg->VideoClk2_DivisorSel = INREG8(VCLK2_VCO_DIV_SEL);

   i810Reg->ExtVertTotal = hwp->readCrtc(hwp, EXT_VERT_TOTAL);
   i810Reg->ExtVertDispEnd = hwp->readCrtc(hwp, EXT_VERT_DISPLAY);
   i810Reg->ExtVertSyncStart = hwp->readCrtc(hwp, EXT_VERT_SYNC_START);
   i810Reg->ExtVertBlankStart = hwp->readCrtc(hwp, EXT_VERT_BLANK_START);
   i810Reg->ExtHorizTotal = hwp->readCrtc(hwp, EXT_HORIZ_TOTAL);
   i810Reg->ExtHorizBlank = hwp->readCrtc(hwp, EXT_HORIZ_BLANK);
   i810Reg->ExtOffset = hwp->readCrtc(hwp, EXT_OFFSET);
   i810Reg->InterlaceControl = hwp->readCrtc(hwp, INTERLACE_CNTL);

   i810Reg->PixelPipeCfg0 = INREG8(PIXPIPE_CONFIG_0);
   i810Reg->PixelPipeCfg1 = INREG8(PIXPIPE_CONFIG_1);
   i810Reg->PixelPipeCfg2 = INREG8(PIXPIPE_CONFIG_2);
   i810Reg->DisplayControl = INREG8(DISPLAY_CNTL);
   i810Reg->LMI_FIFO_Watermark = INREG(FWATER_BLC);

   for (i = 0; i < 8; i++)
      i810Reg->Fence[i] = INREG(FENCE + i * 4);

   i810Reg->LprbTail = INREG(LP_RING + RING_TAIL);
   i810Reg->LprbHead = INREG(LP_RING + RING_HEAD);
   i810Reg->LprbStart = INREG(LP_RING + RING_START);
   i810Reg->LprbLen = INREG(LP_RING + RING_LEN);

   if ((i810Reg->LprbTail & TAIL_ADDR) != (i810Reg->LprbHead & HEAD_ADDR) &&
       i810Reg->LprbLen & RING_VALID) {
      I810PrintErrorState(scrn);
      FatalError("Active ring not flushed\n");
   }
}

static void
I810Save(ScrnInfoPtr scrn)
{
   vgaHWPtr hwp;
   I810Ptr pI810;
   uint32_t temp;

   hwp = VGAHWPTR(scrn);
   pI810 = I810PTR(scrn);
   DoSave(scrn, &hwp->SavedReg, &pI810->SavedReg, TRUE);

   temp = INREG(MEMMODE);
   temp |= 4;
   OUTREG(MEMMODE, temp);
}

static void
i810PrintMode(vgaRegPtr vgaReg, I810RegPtr mode)
{
   int i;

   ErrorF("   MiscOut: %x\n", vgaReg->MiscOutReg);

   ErrorF("SEQ: ");
   for (i = 0; i < vgaReg->numSequencer; i++) {
      if ((i & 7) == 0)
	 ErrorF("\n");
      ErrorF("   %d: %x", i, vgaReg->Sequencer[i]);
   }
   ErrorF("\n");

   ErrorF("CRTC: ");
   for (i = 0; i < vgaReg->numCRTC; i++) {
      if ((i & 3) == 0)
	 ErrorF("\n");
      ErrorF("   %d: %x", i, vgaReg->CRTC[i]);
   }
   ErrorF("\n");

   ErrorF("GFX: ");
   for (i = 0; i < vgaReg->numGraphics; i++) {
      if ((i & 7) == 0)
	 ErrorF("\n");
      ErrorF("   %d: %x", i, vgaReg->Graphics[i]);
   }
   ErrorF("\n");

   ErrorF("ATTR: ");
   for (i = 0; i < vgaReg->numAttribute; i++) {
      if ((i & 7) == 0)
	 ErrorF("\n");
      ErrorF("   %d: %x", i, vgaReg->Attribute[i]);
   }
   ErrorF("\n");

   ErrorF("   DisplayControl: %x\n", mode->DisplayControl);
   ErrorF("   PixelPipeCfg0: %x\n", mode->PixelPipeCfg0);
   ErrorF("   PixelPipeCfg1: %x\n", mode->PixelPipeCfg1);
   ErrorF("   PixelPipeCfg2: %x\n", mode->PixelPipeCfg2);
   ErrorF("   VideoClk2_M: %x\n", mode->VideoClk2_M);
   ErrorF("   VideoClk2_N: %x\n", mode->VideoClk2_N);
   ErrorF("   VideoClk2_DivisorSel: %x\n", mode->VideoClk2_DivisorSel);
   ErrorF("   AddressMapping: %x\n", mode->AddressMapping);
   ErrorF("   IOControl: %x\n", mode->IOControl);
   ErrorF("   BitBLTControl: %x\n", mode->BitBLTControl);
   ErrorF("   ExtVertTotal: %x\n", mode->ExtVertTotal);
   ErrorF("   ExtVertDispEnd: %x\n", mode->ExtVertDispEnd);
   ErrorF("   ExtVertSyncStart: %x\n", mode->ExtVertSyncStart);
   ErrorF("   ExtVertBlankStart: %x\n", mode->ExtVertBlankStart);
   ErrorF("   ExtHorizTotal: %x\n", mode->ExtHorizTotal);
   ErrorF("   ExtHorizBlank: %x\n", mode->ExtHorizBlank);
   ErrorF("   ExtOffset: %x\n", mode->ExtOffset);
   ErrorF("   InterlaceControl: %x\n", mode->InterlaceControl);
   ErrorF("   LMI_FIFO_Watermark: %x\n", mode->LMI_FIFO_Watermark);
   ErrorF("   LprbTail: %x\n", mode->LprbTail);
   ErrorF("   LprbHead: %x\n", mode->LprbHead);
   ErrorF("   LprbStart: %x\n", mode->LprbStart);
   ErrorF("   LprbLen: %x\n", mode->LprbLen);
}

static void
DoRestore(ScrnInfoPtr scrn, vgaRegPtr vgaReg, I810RegPtr i810Reg,
	  Bool restoreFonts)
{
   I810Ptr pI810;
   vgaHWPtr hwp;
   unsigned char temp;
   unsigned int itemp;
   int i;

   pI810 = I810PTR(scrn);
   hwp = VGAHWPTR(scrn);

   if (I810_DEBUG & DEBUG_VERBOSE_VGA) {
      ErrorF("Setting mode in I810Restore:\n");
      i810PrintMode(vgaReg, i810Reg);
   }

   vgaHWProtect(scrn, TRUE);

   usleep(50000);

   /* Turn off DRAM Refresh */
   temp = INREG8(DRAM_ROW_CNTL_HI);
   temp &= ~DRAM_REFRESH_RATE;
   temp |= DRAM_REFRESH_DISABLE;
   OUTREG8(DRAM_ROW_CNTL_HI, temp);

   usleep(1000);			/* Wait 1 ms */

   /* Write the M, N and P values */
   OUTREG16(VCLK2_VCO_M, i810Reg->VideoClk2_M);
   OUTREG16(VCLK2_VCO_N, i810Reg->VideoClk2_N);
   OUTREG8(VCLK2_VCO_DIV_SEL, i810Reg->VideoClk2_DivisorSel);

   /*
    * Turn on 8 bit dac mode, if requested.  This is needed to make
    * sure that vgaHWRestore writes the values into the DAC properly.
    * The problem occurs if 8 bit dac mode is requested and the HW is
    * in 6 bit dac mode.  If this happens, all the values are
    * automatically shifted left twice by the HW and incorrect colors
    * will be displayed on the screen.  The only time this can happen
    * is at server startup time and when switching back from a VT.
    */
   temp = INREG8(PIXPIPE_CONFIG_0);
   temp &= 0x7F;			/* Save all but the 8 bit dac mode bit */
   temp |= (i810Reg->PixelPipeCfg0 & DAC_8_BIT);
   OUTREG8(PIXPIPE_CONFIG_0, temp);

   /*
    * Code to restore any SVGA registers that have been saved/modified
    * goes here.  Note that it is allowable, and often correct, to
    * only modify certain bits in a register by a read/modify/write cycle.
    *
    * A special case - when using an external clock-setting program,
    * this function must not change bits associated with the clock
    * selection.  This condition can be checked by the condition:
    *
    *   if (i810Reg->std.NoClock >= 0)
    *           restore clock-select bits.
    */
   if (restoreFonts)
      vgaHWRestore(scrn, vgaReg, VGA_SR_FONTS | VGA_SR_MODE | VGA_SR_CMAP);
   else
      vgaHWRestore(scrn, vgaReg, VGA_SR_MODE | VGA_SR_CMAP);

   hwp->writeCrtc(hwp, EXT_VERT_TOTAL, i810Reg->ExtVertTotal);
   hwp->writeCrtc(hwp, EXT_VERT_DISPLAY, i810Reg->ExtVertDispEnd);
   hwp->writeCrtc(hwp, EXT_VERT_SYNC_START, i810Reg->ExtVertSyncStart);
   hwp->writeCrtc(hwp, EXT_VERT_BLANK_START, i810Reg->ExtVertBlankStart);
   hwp->writeCrtc(hwp, EXT_HORIZ_TOTAL, i810Reg->ExtHorizTotal);
   hwp->writeCrtc(hwp, EXT_HORIZ_BLANK, i810Reg->ExtHorizBlank);
   hwp->writeCrtc(hwp, EXT_OFFSET, i810Reg->ExtOffset);

   temp = hwp->readCrtc(hwp, INTERLACE_CNTL);
   temp &= ~INTERLACE_ENABLE;
   temp |= i810Reg->InterlaceControl;
   hwp->writeCrtc(hwp, INTERLACE_CNTL, temp);

   temp = hwp->readGr(hwp, ADDRESS_MAPPING);
   temp &= 0xE0;			/* Save reserved bits 7:5 */
   temp |= i810Reg->AddressMapping;
   hwp->writeGr(hwp, ADDRESS_MAPPING, temp);

   /* Setting the OVRACT Register for video overlay */
   {
       uint32_t LCD_TV_Control = INREG(LCD_TV_C);
       uint32_t TV_HTotal = INREG(LCD_TV_HTOTAL);
       uint32_t ActiveStart, ActiveEnd;

       if((LCD_TV_Control & LCD_TV_ENABLE)
	  && !(LCD_TV_Control & LCD_TV_VGAMOD)
	   && TV_HTotal) {
	   ActiveStart = ((TV_HTotal >> 16) & 0xfff) - 31;
	   ActiveEnd = (TV_HTotal & 0x3ff) - 31;
       } else {
	   ActiveStart = i810Reg->OverlayActiveStart;
	   ActiveEnd = i810Reg->OverlayActiveEnd;
       }
       OUTREG(LCD_TV_OVRACT,
	      (ActiveEnd << 16) | ActiveStart);
   }

   /* Turn on DRAM Refresh */
   temp = INREG8(DRAM_ROW_CNTL_HI);
   temp &= ~DRAM_REFRESH_RATE;
   temp |= DRAM_REFRESH_60HZ;
   OUTREG8(DRAM_ROW_CNTL_HI, temp);

   temp = INREG8(BITBLT_CNTL);
   temp &= ~COLEXP_MODE;
   temp |= i810Reg->BitBLTControl;
   OUTREG8(BITBLT_CNTL, temp);

   temp = INREG8(DISPLAY_CNTL);
   temp &= ~(VGA_WRAP_MODE | GUI_MODE);
   temp |= i810Reg->DisplayControl;
   OUTREG8(DISPLAY_CNTL, temp);

   temp = INREG8(PIXPIPE_CONFIG_0);
   temp &= 0x64;			/* Save reserved bits 6:5,2 */
   temp |= i810Reg->PixelPipeCfg0;
   OUTREG8(PIXPIPE_CONFIG_0, temp);

   temp = INREG8(PIXPIPE_CONFIG_2);
   temp &= 0xF3;			/* Save reserved bits 7:4,1:0 */
   temp |= i810Reg->PixelPipeCfg2;
   OUTREG8(PIXPIPE_CONFIG_2, temp);

   temp = INREG8(PIXPIPE_CONFIG_1);
   temp &= ~DISPLAY_COLOR_MODE;
   temp &= 0xEF;			/* Restore the CRT control bit */
   temp |= i810Reg->PixelPipeCfg1;
   OUTREG8(PIXPIPE_CONFIG_1, temp);

   OUTREG16(EIR, 0);

   itemp = INREG(FWATER_BLC);
   itemp &= ~(LM_BURST_LENGTH | LM_FIFO_WATERMARK |
	      MM_BURST_LENGTH | MM_FIFO_WATERMARK);
   itemp |= i810Reg->LMI_FIFO_Watermark;
   OUTREG(FWATER_BLC, itemp);

   for (i = 0; i < 8; i++) {
      OUTREG(FENCE + i * 4, i810Reg->Fence[i]);
      if (I810_DEBUG & DEBUG_VERBOSE_VGA)
	 ErrorF("Fence Register : %x\n", i810Reg->Fence[i]);
   }

   /* First disable the ring buffer (Need to wait for empty first?, if so
    * should probably do it before entering this section)
    */
   itemp = INREG(LP_RING + RING_LEN);
   itemp &= ~RING_VALID_MASK;
   OUTREG(LP_RING + RING_LEN, itemp);

   /* Set up the low priority ring buffer.
    */
   OUTREG(LP_RING + RING_TAIL, 0);
   OUTREG(LP_RING + RING_HEAD, 0);

   pI810->LpRing->head = 0;
   pI810->LpRing->tail = 0;

   itemp = INREG(LP_RING + RING_START);
   itemp &= ~(START_ADDR);
   itemp |= i810Reg->LprbStart;
   OUTREG(LP_RING + RING_START, itemp);

   itemp = INREG(LP_RING + RING_LEN);
   itemp &= ~(RING_NR_PAGES | RING_REPORT_MASK | RING_VALID_MASK);
   itemp |= i810Reg->LprbLen;
   OUTREG(LP_RING + RING_LEN, itemp);

   if (!(vgaReg->Attribute[0x10] & 0x1)) {
      usleep(50000);
      if (restoreFonts)
	 vgaHWRestore(scrn, vgaReg,
		      VGA_SR_FONTS | VGA_SR_MODE | VGA_SR_CMAP);
      else
	 vgaHWRestore(scrn, vgaReg, VGA_SR_MODE | VGA_SR_CMAP);
   }

   vgaHWProtect(scrn, FALSE);

   temp = hwp->readCrtc(hwp, IO_CTNL);
   temp &= ~(EXTENDED_ATTR_CNTL | EXTENDED_CRTC_CNTL);
   temp |= i810Reg->IOControl;
   hwp->writeCrtc(hwp, IO_CTNL, temp);
}

static void
I810SetRingRegs(ScrnInfoPtr scrn)
{
   unsigned int itemp;
   I810Ptr pI810 = I810PTR(scrn);

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

   itemp = INREG(LP_RING + RING_START);
   itemp &= ~(START_ADDR);
   itemp |= pI810->LpRing->mem.Start;
   OUTREG(LP_RING + RING_START, itemp);

   itemp = INREG(LP_RING + RING_LEN);
   itemp &= ~(RING_NR_PAGES | RING_REPORT_MASK | RING_VALID_MASK);
   itemp |= ((pI810->LpRing->mem.Size - 4096) | RING_NO_REPORT | RING_VALID);
   OUTREG(LP_RING + RING_LEN, itemp);
}

static void
I810Restore(ScrnInfoPtr scrn)
{
   vgaHWPtr hwp;
   I810Ptr pI810;

   hwp = VGAHWPTR(scrn);
   pI810 = I810PTR(scrn);

   DoRestore(scrn, &hwp->SavedReg, &pI810->SavedReg, TRUE);
}

/*
 * I810CalcVCLK --
 *
 * Determine the closest clock frequency to the one requested.
 */

#define MAX_VCO_FREQ 600.0
#define TARGET_MAX_N 30
#define REF_FREQ 24.0

#define CALC_VCLK(m,n,p) \
    (double)m / ((double)n * (1 << p)) * 4 * REF_FREQ

static void
I810CalcVCLK(ScrnInfoPtr scrn, double freq)
{
   I810Ptr pI810 = I810PTR(scrn);
   I810RegPtr i810Reg = &pI810->ModeReg;
   int m, n, p;
   double f_out;
   double f_err;
   double f_vco;
   int m_best = 0, n_best = 0, p_best = 0;
   double f_target = freq;
   double err_max = 0.005;
   double err_target = 0.001;
   double err_best = 999999.0;

   p_best = p = log(MAX_VCO_FREQ / f_target) / log((double)2);
   /* Make sure p is within range. */
   if (p_best > 5) {
      p_best = p = 5;
   }

   f_vco = f_target * (1 << p);

   n = 2;
   do {
      n++;
      m = f_vco / (REF_FREQ / (double)n) / (double)4.0 + 0.5;
      if (m < 3)
	 m = 3;
      f_out = CALC_VCLK(m, n, p);
      f_err = 1.0 - (f_target / f_out);
      if (fabs(f_err) < err_max) {
	 m_best = m;
	 n_best = n;
	 err_best = f_err;
      }
   } while ((fabs(f_err) >= err_target) &&
	    ((n <= TARGET_MAX_N) || (fabs(err_best) > err_max)));

   if (fabs(f_err) < err_target) {
      m_best = m;
      n_best = n;
   }

   i810Reg->VideoClk2_M = (m_best - 2) & 0x3FF;
   i810Reg->VideoClk2_N = (n_best - 2) & 0x3FF;
   i810Reg->VideoClk2_DivisorSel = (p_best << 4);

   xf86DrvMsgVerb(scrn->scrnIndex, X_INFO, 3,
		  "Setting dot clock to %.1f MHz " "[ 0x%x 0x%x 0x%x ] "
		  "[ %d %d %d ]\n", CALC_VCLK(m_best, n_best, p_best),
		  i810Reg->VideoClk2_M, i810Reg->VideoClk2_N,
		  i810Reg->VideoClk2_DivisorSel, m_best, n_best, p_best);
}

static Bool
I810SetMode(ScrnInfoPtr scrn, DisplayModePtr mode)
{
   I810Ptr pI810 = I810PTR(scrn);
   I810RegPtr i810Reg = &pI810->ModeReg;
   vgaRegPtr pVga = &VGAHWPTR(scrn)->ModeReg;
   double dclk = mode->Clock / 1000.0;

   switch (scrn->bitsPerPixel) {
   case 8:
      pVga->CRTC[0x13] = scrn->displayWidth >> 3;
      i810Reg->ExtOffset = scrn->displayWidth >> 11;
      i810Reg->PixelPipeCfg1 = DISPLAY_8BPP_MODE;
      i810Reg->BitBLTControl = COLEXP_8BPP;
      break;
   case 16:
      if (scrn->weight.green == 5) {
	 i810Reg->PixelPipeCfg1 = DISPLAY_15BPP_MODE;
      } else {
	 i810Reg->PixelPipeCfg1 = DISPLAY_16BPP_MODE;
      }
      pVga->CRTC[0x13] = scrn->displayWidth >> 2;
      i810Reg->ExtOffset = scrn->displayWidth >> 10;
      i810Reg->BitBLTControl = COLEXP_16BPP;

      /* Enable Palette Programming for Direct Color visuals. -jens */
      i810Reg->PixelPipeCfg2 = DISPLAY_GAMMA_ENABLE;
      break;
   case 24:
      pVga->CRTC[0x13] = (scrn->displayWidth * 3) >> 3;
      i810Reg->ExtOffset = (scrn->displayWidth * 3) >> 11;

      i810Reg->PixelPipeCfg1 = DISPLAY_24BPP_MODE;
      i810Reg->BitBLTControl = COLEXP_24BPP;

      /* Enable Palette Programming for Direct Color visuals. -jens */
      i810Reg->PixelPipeCfg2 = DISPLAY_GAMMA_ENABLE;
      break;
   default:
      break;
   }

   /* Turn on 8 bit dac if requested */
   if (xf86ReturnOptValBool(pI810->Options, OPTION_DAC_6BIT, FALSE))
      i810Reg->PixelPipeCfg0 = DAC_6_BIT;
   else
      i810Reg->PixelPipeCfg0 = DAC_8_BIT;

   /* Do not delay CRT Blank: needed for video overlay */
   i810Reg->PixelPipeCfg1 |= 0x10;

   /* Turn on Extended VGA Interpretation */
   i810Reg->IOControl = EXTENDED_CRTC_CNTL;

   /* Turn on linear and page mapping */
   i810Reg->AddressMapping = (LINEAR_MODE_ENABLE | GTT_MEM_MAP_ENABLE);

   /* Turn on GUI mode */
   i810Reg->DisplayControl = HIRES_MODE;

   /* Calculate the extended CRTC regs */
   i810Reg->ExtVertTotal = (mode->CrtcVTotal - 2) >> 8;
   i810Reg->ExtVertDispEnd = (mode->CrtcVDisplay - 1) >> 8;
   i810Reg->ExtVertSyncStart = mode->CrtcVSyncStart >> 8;
   i810Reg->ExtVertBlankStart = mode->CrtcVBlankStart >> 8;
   i810Reg->ExtHorizTotal = ((mode->CrtcHTotal >> 3) - 5) >> 8;
   i810Reg->ExtHorizBlank = (((mode->CrtcHBlankEnd >> 3) - 1) & 0x40) >> 6;

   /*
    * the KGA fix in vgaHW.c results in the first
    * scanline and the first character clock (8 pixels)
    * of each scanline thereafter on display with an i810
    * to be blank. Restoring CRTC 3, 5, & 22 to their
    * "theoretical" values corrects the problem. KAO.
    */
   pVga->CRTC[3] = (((mode->CrtcHBlankEnd >> 3) - 1) & 0x1F) | 0x80;
   pVga->CRTC[5] = ((((mode->CrtcHBlankEnd >> 3) - 1) & 0x20) << 2)
	 | (((mode->CrtcHSyncEnd >> 3)) & 0x1F);
   pVga->CRTC[22] = (mode->CrtcVBlankEnd - 1) & 0xFF;

   i810Reg->ExtHorizBlank = vgaHWHBlankKGA(mode, pVga, 7, 0);
   vgaHWVBlankKGA(mode, pVga, 8, 0);

   /*
    * The following workarounds are needed to get video overlay working
    * at 1024x768 and 1280x1024 display resolutions.
    */
   if ((mode->CrtcVDisplay == 768) && (i810Reg->ExtVertBlankStart == 3)) {
      i810Reg->ExtVertBlankStart = 2;
   }
   if ((mode->CrtcVDisplay == 1024) && (i810Reg->ExtVertBlankStart == 4)) {
      i810Reg->ExtVertBlankStart = 3;
   }

   /* OVRACT Register */
   i810Reg->OverlayActiveStart = mode->CrtcHTotal - 32;
   i810Reg->OverlayActiveEnd = mode->CrtcHDisplay - 32;

   /* Turn on interlaced mode if necessary */
   if (mode->Flags & V_INTERLACE) {
      i810Reg->InterlaceControl = INTERLACE_ENABLE;
      i810Reg->ExtVertDispEnd *= 2;
   } else
      i810Reg->InterlaceControl = INTERLACE_DISABLE;

   /*
    * Set the overscan color to 0.
    * NOTE: This only affects >8bpp mode.
    */
   pVga->Attribute[0x11] = 0;

   /*
    * Calculate the VCLK that most closely matches the requested dot
    * clock.
    */
   I810CalcVCLK(scrn, dclk);

   /* Since we program the clocks ourselves, always use VCLK2. */
   pVga->MiscOutReg |= 0x0C;

   /* Calculate the FIFO Watermark and Burst Length. */
   i810Reg->LMI_FIFO_Watermark = I810CalcWatermark(scrn, dclk, FALSE);

   /* Setup the ring buffer */
   i810Reg->LprbTail = 0;
   i810Reg->LprbHead = 0;
   i810Reg->LprbStart = pI810->LpRing->mem.Start;

   if (i810Reg->LprbStart)
      i810Reg->LprbLen = ((pI810->LpRing->mem.Size - 4096) |
			  RING_NO_REPORT | RING_VALID);
   else
      i810Reg->LprbLen = RING_INVALID;

   return TRUE;
}

static Bool
I810ModeInit(ScrnInfoPtr scrn, DisplayModePtr mode)
{
   vgaHWPtr hwp;
   I810Ptr pI810;

   hwp = VGAHWPTR(scrn);
   pI810 = I810PTR(scrn);

   vgaHWUnlock(hwp);

   if (!vgaHWInit(scrn, mode))
      return FALSE;

   scrn->vtSema = TRUE;

   if (!I810SetMode(scrn, mode))
      return FALSE;

#ifdef HAVE_DRI1
   if (pI810->directRenderingEnabled) {
      DRILock(xf86ScrnToScreen(scrn), 0);
      pI810->LockHeld = 1;
   }
#endif

   DoRestore(scrn, &hwp->ModeReg, &pI810->ModeReg, FALSE);

#ifdef HAVE_DRI1
   if (pI810->directRenderingEnabled) {
      DRIUnlock(xf86ScrnToScreen(scrn));
      pI810->LockHeld = 0;
   }
#endif

   return TRUE;
}

static void
I810LoadPalette15(ScrnInfoPtr scrn, int numColors, int *indices,
		  LOCO * colors, VisualPtr pVisual)
{
   vgaHWPtr hwp;
   int i, j, index;
   unsigned char r, g, b;

   hwp = VGAHWPTR(scrn);

   for (i = 0; i < numColors; i++) {
      index = indices[i];
      r = colors[index].red;
      g = colors[index].green;
      b = colors[index].blue;
      for (j = 0; j < 8; j++) {
	 hwp->writeDacWriteAddr(hwp, (index << 3) + j);
	 hwp->writeDacData(hwp, r);
	 hwp->writeDacData(hwp, g);
	 hwp->writeDacData(hwp, b);
      }
   }
}

static void
I810LoadPalette16(ScrnInfoPtr scrn, int numColors, int *indices,
		  LOCO * colors, VisualPtr pVisual)
{
   vgaHWPtr hwp;
   int i, index;
   unsigned char r, g, b;

   hwp = VGAHWPTR(scrn);

   /* Load all four entries in each of the 64 color ranges.  -jens */
   for (i = 0; i < numColors; i++) {
      index = indices[i / 2];
      r = colors[index].red;
      b = colors[index].blue;
      index = indices[i];
      g = colors[index].green;

      hwp->writeDacWriteAddr(hwp, index << 2);
      hwp->writeDacData(hwp, r);
      hwp->writeDacData(hwp, g);
      hwp->writeDacData(hwp, b);

      hwp->writeDacWriteAddr(hwp, (index << 2) + 1);
      hwp->writeDacData(hwp, r);
      hwp->writeDacData(hwp, g);
      hwp->writeDacData(hwp, b);

      hwp->writeDacWriteAddr(hwp, (index << 2) + 2);
      hwp->writeDacData(hwp, r);
      hwp->writeDacData(hwp, g);
      hwp->writeDacData(hwp, b);

      hwp->writeDacWriteAddr(hwp, (index << 2) + 3);
      hwp->writeDacData(hwp, r);
      hwp->writeDacData(hwp, g);
      hwp->writeDacData(hwp, b);

      i++;
      index = indices[i];
      g = colors[index].green;

      hwp->writeDacWriteAddr(hwp, index << 2);
      hwp->writeDacData(hwp, r);
      hwp->writeDacData(hwp, g);
      hwp->writeDacData(hwp, b);

      hwp->writeDacWriteAddr(hwp, (index << 2) + 1);
      hwp->writeDacData(hwp, r);
      hwp->writeDacData(hwp, g);
      hwp->writeDacData(hwp, b);

      hwp->writeDacWriteAddr(hwp, (index << 2) + 2);
      hwp->writeDacData(hwp, r);
      hwp->writeDacData(hwp, g);
      hwp->writeDacData(hwp, b);

      hwp->writeDacWriteAddr(hwp, (index << 2) + 3);
      hwp->writeDacData(hwp, r);
      hwp->writeDacData(hwp, g);
      hwp->writeDacData(hwp, b);
   }
}

static void
I810LoadPalette24(ScrnInfoPtr scrn, int numColors, int *indices,
		  LOCO * colors, VisualPtr pVisual)
{
   vgaHWPtr hwp;
   int i, index;
   unsigned char r, g, b;

   hwp = VGAHWPTR(scrn);

   for (i = 0; i < numColors; i++) {
      index = indices[i];
      r = colors[index].red;
      g = colors[index].green;
      b = colors[index].blue;
      hwp->writeDacWriteAddr(hwp, index);
      hwp->writeDacData(hwp, r);
      hwp->writeDacData(hwp, g);
      hwp->writeDacData(hwp, b);
   }
}

Bool
I810AllocateFront(ScrnInfoPtr scrn)
{
   I810Ptr pI810 = I810PTR(scrn);
   int cache_lines = -1;

   if (pI810->DoneFrontAlloc)
      return TRUE;

   memset(&(pI810->FbMemBox), 0, sizeof(BoxRec));
   /* Alloc FrontBuffer/Ring/Accel memory */
   pI810->FbMemBox.x1 = 0;
   pI810->FbMemBox.x2 = scrn->displayWidth;
   pI810->FbMemBox.y1 = 0;
   pI810->FbMemBox.y2 = scrn->virtualY;

   xf86GetOptValInteger(pI810->Options, OPTION_CACHE_LINES, &cache_lines);

   if (cache_lines < 0) {
      /* make sure there is enough for two DVD sized YUV buffers */
      cache_lines = (scrn->depth == 24) ? 256 : 384;
      if (scrn->displayWidth <= 1024)
	 cache_lines *= 2;
   }
   /* Make sure there's enough space for cache_lines.
    *
    * Had a bug here where maxCacheLines was computed to be less than 0.
    * Not sure why 256 was initially subtracted from videoRam in the
    * maxCacheLines calculation, but that was causing a problem
    * for configurations that have exactly enough Ram for the framebuffer.
    * Common code should catch the case where there isn't enough space for
    * framebuffer, we'll just check for no space for cache_lines.  -jens
    *
    */
   {
      int maxCacheLines;

      maxCacheLines = (scrn->videoRam * 1024 /
		       (scrn->bitsPerPixel / 8) /
		       scrn->displayWidth) - scrn->virtualY;
      if (maxCacheLines < 0)
	 maxCacheLines = 0;
      if (cache_lines > maxCacheLines)
	 cache_lines = maxCacheLines;
   }
   pI810->FbMemBox.y2 += cache_lines;

   xf86DrvMsg(scrn->scrnIndex, X_INFO,
	      "Adding %i scanlines for pixmap caching\n", cache_lines);

   /* Reserve room for the framebuffer and pixcache.  Put at the top
    * of memory so we can have nice alignment for the tiled regions at
    * the start of memory.
    */

   if (!I810AllocLow(&(pI810->FrontBuffer),
		     &(pI810->SysMem),
		     ALIGN((pI810->FbMemBox.x2 * pI810->FbMemBox.y2 * pI810->cpp), 4096))) {
      xf86DrvMsg(scrn->scrnIndex,
		 X_WARNING, "Framebuffer allocation failed\n");
      return FALSE;
   }

   memset(pI810->LpRing, 0, sizeof(I810RingBuffer));
   if (I810AllocLow(&(pI810->LpRing->mem), &(pI810->SysMem), 16 * 4096)) {
      pI810->LpRing->tail_mask = pI810->LpRing->mem.Size - 1;
      pI810->LpRing->virtual_start = pI810->FbBase + pI810->LpRing->mem.Start;
      pI810->LpRing->head = 0;
      pI810->LpRing->tail = 0;
      pI810->LpRing->space = 0;
   } else {
      xf86DrvMsg(scrn->scrnIndex, X_ERROR,
		 "Ring buffer allocation failed\n");
      return (FALSE);
   }

   if (I810AllocLow(&pI810->Scratch, &(pI810->SysMem), 64 * 1024) ||
       I810AllocLow(&pI810->Scratch, &(pI810->SysMem), 16 * 1024)) {
      xf86DrvMsg(scrn->scrnIndex, X_INFO, "Allocated Scratch Memory\n");
   } else {
      xf86DrvMsg(scrn->scrnIndex, X_ERROR,
		 "Scratch memory allocation failed\n");
      return (FALSE);
   }

   pI810->DoneFrontAlloc = TRUE;
   return TRUE;
}

static Bool
I810ScreenInit(SCREEN_INIT_ARGS_DECL)
{
   ScrnInfoPtr scrn;
   vgaHWPtr hwp;
   I810Ptr pI810;
   VisualPtr visual;

   scrn = xf86ScreenToScrn(screen);
   pI810 = I810PTR(scrn);
   hwp = VGAHWPTR(scrn);

   pI810->LpRing = calloc(sizeof(I810RingBuffer),1);
   if (!pI810->LpRing) {
     xf86DrvMsg(scrn->scrnIndex, X_ERROR,
		"Could not allocate lpring data structure.\n");
     return FALSE;
   }

   miClearVisualTypes();

   /* Re-implemented Direct Color support, -jens */
   if (!miSetVisualTypes(scrn->depth, miGetDefaultVisualMask(scrn->depth),
			 scrn->rgbBits, scrn->defaultVisual))
      return FALSE;

   if (!miSetPixmapDepths())
      return FALSE;

   {
      I810RegPtr i810Reg = &pI810->ModeReg;
      int i;

      for (i = 0; i < 8; i++)
	 i810Reg->Fence[i] = 0;
   }

   /* Have to init the DRM earlier than in other drivers to get agp
    * memory.  Wonder if this is going to be a problem...
    */

#ifdef HAVE_DRI1
   /*
    * Setup DRI after visuals have been established, but before fbScreenInit
    * is called.   fbScreenInit will eventually call into the drivers
    * InitGLXVisuals call back.
    */
   /*
    * pI810->directRenderingDisabled is set once in PreInit.  Reinitialise
    * pI810->directRenderingEnabled based on it each generation.
    */
   pI810->directRenderingEnabled = !pI810->directRenderingDisabled;

   if (pI810->directRenderingEnabled==TRUE)
     pI810->directRenderingEnabled = I810DRIScreenInit(screen);

#else
   pI810->directRenderingEnabled = FALSE;
   if (!I810AllocateGARTMemory(scrn))
      return FALSE;
   if (!I810AllocateFront(scrn))
      return FALSE;
#endif

   if (!I810MapMem(scrn))
      return FALSE;

   scrn->memPhysBase = (unsigned long)pI810->LinearAddr;
   scrn->fbOffset = 0;

   vgaHWSetMmioFuncs(hwp, pI810->MMIOBase, 0);
   vgaHWGetIOBase(hwp);
   if (!vgaHWMapMem(scrn))
      return FALSE;

   I810Save(scrn);
   if (!I810ModeInit(scrn, scrn->currentMode))
      return FALSE;

   I810SaveScreen(screen, FALSE);
   I810AdjustFrame(ADJUST_FRAME_ARGS(scrn, scrn->frameX0, scrn->frameY0));

   if (!fbScreenInit(screen, pI810->FbBase + scrn->fbOffset,
		     scrn->virtualX, scrn->virtualY,
		     scrn->xDpi, scrn->yDpi,
		     scrn->displayWidth, scrn->bitsPerPixel))
      return FALSE;

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

   fbPictureInit(screen, NULL, 0);

   xf86SetBlackWhitePixels(screen);

#ifdef HAVE_DRI1
   if (pI810->LpRing->mem.Start == 0 && pI810->directRenderingEnabled) {
      pI810->directRenderingEnabled = FALSE;
      I810DRICloseScreen(screen);
   }

   if (!pI810->directRenderingEnabled) {
      pI810->DoneFrontAlloc = FALSE;
      if (!I810AllocateGARTMemory(scrn))
	 return FALSE;
      if (!I810AllocateFront(scrn))
	 return FALSE;
   }
#endif

#ifdef HAVE_DGAPROC_H
   I810DGAInit(screen);
#endif

   if (!xf86InitFBManager(screen, &(pI810->FbMemBox))) {
      xf86DrvMsg(scrn->scrnIndex, X_ERROR,
		 "Failed to init memory manager\n");
      return FALSE;
   }

   if (pI810->LpRing->mem.Size != 0) {
      I810SetRingRegs(scrn);

      if (!pI810->noAccel && !I810AccelInit(screen)) {
	 xf86DrvMsg(scrn->scrnIndex, X_ERROR,
		    "Hardware acceleration initialization failed\n");
      }

      I810EmitFlush(scrn);
   }

   miInitializeBackingStore(screen);
   xf86SetBackingStore(screen);
   xf86SetSilkenMouse(screen);

   miDCInitialize(screen, xf86GetPointerScreenFuncs());

   if (!xf86ReturnOptValBool(pI810->Options, OPTION_SW_CURSOR, FALSE)) {
      if (!I810CursorInit(screen)) {
	 xf86DrvMsg(scrn->scrnIndex, X_ERROR,
		    "Hardware cursor initialization failed\n");
      }
   }

   if (!miCreateDefColormap(screen))
      return FALSE;

   /* Use driver specific palette load routines for Direct Color support. -jens */
   if (scrn->bitsPerPixel == 16) {
      if (scrn->depth == 15) {
	 if (!xf86HandleColormaps(screen, 256, 8, I810LoadPalette15, NULL,
				  CMAP_PALETTED_TRUECOLOR |
				  CMAP_RELOAD_ON_MODE_SWITCH))
	    return FALSE;
      } else {
	 if (!xf86HandleColormaps(screen, 256, 8, I810LoadPalette16, NULL,
				  CMAP_PALETTED_TRUECOLOR |
				  CMAP_RELOAD_ON_MODE_SWITCH))
	    return FALSE;
      }
   } else {
      if (!xf86HandleColormaps(screen, 256, 8, I810LoadPalette24, NULL,
			       CMAP_PALETTED_TRUECOLOR |
			       CMAP_RELOAD_ON_MODE_SWITCH))
	 return FALSE;
   }

   xf86DPMSInit(screen, I810DisplayPowerManagementSet, 0);

   I810InitVideo(screen);

#ifdef HAVE_DRI1
   if (pI810->directRenderingEnabled) {
      /* Now that mi, fb, drm and others have done their thing,
       * complete the DRI setup.
       */
      pI810->directRenderingEnabled = I810DRIFinishScreenInit(screen);
   }
#ifdef XvMCExtension
   if ((pI810->directRenderingEnabled) && (pI810->numSurfaces)) {
      /* Initialize the hardware motion compensation code */
      I810InitMC(screen);
   }
#endif
#endif

   if (pI810->directRenderingEnabled) {
      xf86DrvMsg(scrn->scrnIndex, X_INFO, "Direct rendering enabled\n");
   } else {
      xf86DrvMsg(scrn->scrnIndex, X_WARNING, "Direct rendering disabled\n");
   }

   screen->SaveScreen = I810SaveScreen;
   pI810->CloseScreen = screen->CloseScreen;
   screen->CloseScreen = I810CloseScreen;

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

   return TRUE;
}

Bool
I810SwitchMode(SWITCH_MODE_ARGS_DECL)
{
   SCRN_INFO_PTR(arg);
#if 0
   I810Ptr pI810 = I810PTR(scrn);
#endif
   if (I810_DEBUG & DEBUG_VERBOSE_CURSOR)
      ErrorF("I810SwitchMode %p\n", (void *)mode);

#if 0
/* 
 * This has been added to prevent lockups on mode switch by modeling
 * it after I810Leave()/I810Enter() but the call to I810DRILeave() 
 * was missing so it caused the opposite. 
 * The version below works but it is doubtful it does any good.
 * If lockups on mode switch are still seen revisit this code. (EE)
 */

# ifdef HAVE_DRI1
   if (pI810->directRenderingEnabled) {
      if (I810_DEBUG & DEBUG_VERBOSE_DRI)
	 ErrorF("calling dri lock\n");
      DRILock(screenInfo.screens[scrnIndex], 0);
      pI810->LockHeld = 1;
   }
# endif
   if (pI810->AccelInfoRec != NULL) {
      I810RefreshRing(scrn);
      I810Sync(scrn);
      pI810->AccelInfoRec->NeedToSync = FALSE;
   }
   I810Restore(scrn);

# ifdef HAVE_DRI1
   if (pI810->directRenderingEnabled) {
       if (!I810DRILeave(scrn))
	   return FALSE;
       if (!I810DRIEnter(scrn))
	   return FALSE;

       if (I810_DEBUG & DEBUG_VERBOSE_DRI)
	   ErrorF("calling dri unlock\n");
       DRIUnlock(screenInfo.screens[scrnIndex]);
       pI810->LockHeld = 0;
   }
# endif
#endif
   return I810ModeInit(scrn, mode);
}

void
I810AdjustFrame(ADJUST_FRAME_ARGS_DECL)
{
   SCRN_INFO_PTR(arg);
   I810Ptr pI810 = I810PTR(scrn);
   vgaHWPtr hwp = VGAHWPTR(scrn);
   int Base;

#if 1
   if (pI810->showCache) {
     int lastline = pI810->FbMapSize / 
       ((scrn->displayWidth * scrn->bitsPerPixel) / 8);
     lastline -= scrn->currentMode->VDisplay;
     if (y > 0)
       y += scrn->currentMode->VDisplay;
     if (y > lastline) y = lastline;
   }
#endif
   Base = (y * scrn->displayWidth + x) >> 2;

   if (I810_DEBUG & DEBUG_VERBOSE_CURSOR)
      ErrorF("I810AdjustFrame %d,%d\n", x, y);

   switch (scrn->bitsPerPixel) {
   case 8:
      break;
   case 16:
      Base *= 2;
      break;
   case 24:
      /* KW: Need to do 16-pixel alignment for i810, otherwise you
       * get bad watermark problems.  Need to fixup the mouse
       * pointer positioning to take this into account.
       */
      pI810->CursorOffset = (Base & 0x3) * 4;
      Base &= ~0x3;
      Base *= 3;
      break;
   case 32:
      Base *= 4;
      break;
   }

   hwp->writeCrtc(hwp, START_ADDR_LO, Base & 0xFF);
   hwp->writeCrtc(hwp, START_ADDR_HI, (Base & 0xFF00) >> 8);
   hwp->writeCrtc(hwp, EXT_START_ADDR_HI, (Base & 0x3FC00000) >> 22);
   hwp->writeCrtc(hwp, EXT_START_ADDR,
		  ((Base & 0x00eF0000) >> 16 | EXT_START_ADDR_ENABLE));
}

/* These functions are usually called with the lock **not held**.
 */
static Bool
I810EnterVT(VT_FUNC_ARGS_DECL)
{
   SCRN_INFO_PTR(arg);

#ifdef HAVE_DRI1
   I810Ptr pI810 = I810PTR(scrn);
#endif

   if (I810_DEBUG & DEBUG_VERBOSE_DRI)
      ErrorF("\n\nENTER VT\n");

   if (!I810BindGARTMemory(scrn)) {
      return FALSE;
   }
#ifdef HAVE_DRI1
   if (!I810DRIEnter(scrn)) {
      return FALSE;
   }
   if (pI810->directRenderingEnabled) {
      if (I810_DEBUG & DEBUG_VERBOSE_DRI)
	 ErrorF("calling dri unlock\n");
      DRIUnlock(xf86ScrnToScreen(scrn));
      pI810->LockHeld = 0;
   }
#endif

   if (!I810ModeInit(scrn, scrn->currentMode))
      return FALSE;
   I810AdjustFrame(ADJUST_FRAME_ARGS(scrn, scrn->frameX0, scrn->frameY0));
   return TRUE;
}

static void
I810LeaveVT(VT_FUNC_ARGS_DECL)
{
   SCRN_INFO_PTR(arg);
   vgaHWPtr hwp = VGAHWPTR(scrn);
   I810Ptr pI810 = I810PTR(scrn);

   if (I810_DEBUG & DEBUG_VERBOSE_DRI)
      ErrorF("\n\n\nLeave VT\n");

#ifdef HAVE_DRI1
   if (pI810->directRenderingEnabled) {
      if (I810_DEBUG & DEBUG_VERBOSE_DRI)
	 ErrorF("calling dri lock\n");
      DRILock(xf86ScrnToScreen(scrn), 0);
      pI810->LockHeld = 1;
   }
#endif

#ifdef HAVE_XAA_H
   if (pI810->AccelInfoRec != NULL) {
      I810RefreshRing(scrn);
      I810Sync(scrn);
      pI810->AccelInfoRec->NeedToSync = FALSE;
   }
#endif
   I810Restore(scrn);

   if (!I810UnbindGARTMemory(scrn))
      return;
#ifdef HAVE_DRI1
   if (!I810DRILeave(scrn))
      return;
#endif

   vgaHWLock(hwp);
}

static Bool
I810CloseScreen(CLOSE_SCREEN_ARGS_DECL)
{
   ScrnInfoPtr scrn = xf86ScreenToScrn(screen);
   vgaHWPtr hwp = VGAHWPTR(scrn);
   I810Ptr pI810 = I810PTR(scrn);
#ifdef HAVE_XAA_H
   XAAInfoRecPtr infoPtr = pI810->AccelInfoRec;
#endif

   if (scrn->vtSema == TRUE) {
#ifdef HAVE_XAA_H
      if (pI810->AccelInfoRec != NULL) {
	 I810RefreshRing(scrn);
	 I810Sync(scrn);
	 pI810->AccelInfoRec->NeedToSync = FALSE;
      }
#endif
      I810Restore(scrn);
      vgaHWLock(hwp);
   }
#ifdef HAVE_DRI1
   if (pI810->directRenderingEnabled) {
      I810DRICloseScreen(screen);
      pI810->directRenderingEnabled = FALSE;
   }
#endif

   if (scrn->vtSema == TRUE) {
      I810UnbindGARTMemory(scrn);
      I810Restore(scrn);
      vgaHWLock(hwp);
   }

   I810UnmapMem(scrn);
   vgaHWUnmapMem(scrn);

   if (pI810->ScanlineColorExpandBuffers) {
      free(pI810->ScanlineColorExpandBuffers);
      pI810->ScanlineColorExpandBuffers = NULL;
   }

#ifdef HAVE_XAA_H
   if (infoPtr) {
      if (infoPtr->ScanlineColorExpandBuffers)
	 free(infoPtr->ScanlineColorExpandBuffers);
      XAADestroyInfoRec(infoPtr);
      pI810->AccelInfoRec = NULL;
   }
#endif

   if (pI810->CursorInfoRec) {
      xf86DestroyCursorInfoRec(pI810->CursorInfoRec);
      pI810->CursorInfoRec = NULL;
   }

   /* Free all allocated video ram.
    */
   pI810->SysMem = pI810->SavedSysMem;
   pI810->DcacheMem = pI810->SavedDcacheMem;
   pI810->DoneFrontAlloc = FALSE;

   /* Need to actually close the gart fd, or the unbound memory will just sit
    * around.  Will prevent the Xserver from recycling.
    */
   xf86GARTCloseScreen(scrn->scrnIndex);

   free(pI810->LpRing);
   pI810->LpRing = NULL;

   scrn->vtSema = FALSE;
   screen->CloseScreen = pI810->CloseScreen;
   return (*screen->CloseScreen) (CLOSE_SCREEN_ARGS);
}

static void
I810FreeScreen(FREE_SCREEN_ARGS_DECL)
{
   SCRN_INFO_PTR(arg);
   I810FreeRec(scrn);
   if (xf86LoaderCheckSymbol("vgaHWFreeHWRec"))
     vgaHWFreeHWRec(scrn);
}

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

static Bool
I810SaveScreen(ScreenPtr screen, Bool unblack)
{
   return vgaHWSaveScreen(screen, unblack);
}

static void
I810DisplayPowerManagementSet(ScrnInfoPtr scrn, int PowerManagementMode,
			      int flags)
{
   I810Ptr pI810;
   unsigned char SEQ01 = 0;
   int DPMSSyncSelect = 0;
   vgaHWPtr hwp;

   pI810 = I810PTR(scrn);
   switch (PowerManagementMode) {
   case DPMSModeOn:
      /* Screen: On; HSync: On, VSync: On */
      SEQ01 = 0x00;
      DPMSSyncSelect = HSYNC_ON | VSYNC_ON;
      break;
   case DPMSModeStandby:
      /* Screen: Off; HSync: Off, VSync: On */
      SEQ01 = 0x20;
      DPMSSyncSelect = HSYNC_OFF | VSYNC_ON;
      break;
   case DPMSModeSuspend:
      /* Screen: Off; HSync: On, VSync: Off */
      SEQ01 = 0x20;
      DPMSSyncSelect = HSYNC_ON | VSYNC_OFF;
      break;
   case DPMSModeOff:
      /* Screen: Off; HSync: Off, VSync: Off */
      SEQ01 = 0x20;
      DPMSSyncSelect = HSYNC_OFF | VSYNC_OFF;
      break;
   }

   hwp = VGAHWPTR(scrn);

   /* Turn the screen on/off */
   SEQ01 |= hwp->readSeq(hwp, 0x01) & ~0x20;
   hwp->writeSeq(hwp, 0x01, SEQ01);

   /* Set the DPMS mode */
   OUTREG8(DPMS_SYNC_SELECT, DPMSSyncSelect);
}

const OptionInfoRec *
lg_i810_available_options(int chipid, int busid)
{
   return I810Options;
}


Bool lg_i810_init(ScrnInfoPtr scrn)
{
    scrn->PreInit = I810PreInit;
    scrn->ScreenInit = I810ScreenInit;
    scrn->SwitchMode = I810SwitchMode;
    scrn->AdjustFrame = I810AdjustFrame;
    scrn->EnterVT = I810EnterVT;
    scrn->LeaveVT = I810LeaveVT;
    scrn->FreeScreen = I810FreeScreen;
    scrn->ValidMode = I810ValidMode;
    return TRUE;
}