summaryrefslogtreecommitdiff
path: root/src/ast_driver.c
blob: 4a10e6e06e61315b3a76c83904041d7238d99538 (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
/*
 * Copyright (c) 2005 ASPEED Technology Inc.
 *
 * Permission to use, copy, modify, distribute, and sell this software and its
 * documentation for any purpose is hereby granted without fee, provided that
 * the above copyright notice appear in all copies and that both that
 * copyright notice and this permission notice appear in supporting
 * documentation, and that the name of the authors not be used in
 * advertising or publicity pertaining to distribution of the software without
 * specific, written prior permission.  The authors makes no representations
 * about the suitability of this software for any purpose.  It is provided
 * "as is" without express or implied warranty.
 *
 * THE AUTHORS DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
 * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO
 * EVENT SHALL THE AUTHORS BE LIABLE FOR ANY SPECIAL, INDIRECT OR
 * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE,
 * DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
 * TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
 * PERFORMANCE OF THIS SOFTWARE.
 */

#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include "xf86.h"
#include "xf86_OSproc.h"
#if GET_ABI_MAJOR(ABI_VIDEODRV_VERSION) < 6
#include "xf86Resources.h"
#include "xf86RAC.h"
#endif
#include "xf86cmap.h"
#include "compiler.h"
#include "mibstore.h"
#include "vgaHW.h"
#include "mipointer.h"
#include "micmap.h"

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

#include "xf86PciInfo.h"
#include "xf86Pci.h"

/* framebuffer offscreen manager */
#include "xf86fbman.h"

/* include xaa includes */
#include "xaa.h"
#include "xaarop.h"

/* H/W cursor support */
#include "xf86Cursor.h"

/* Driver specific headers */
#include "ast.h"

/* external reference fucntion */
extern Bool ASTMapMem(ScrnInfoPtr pScrn);
extern Bool ASTUnmapMem(ScrnInfoPtr pScrn);
extern Bool ASTMapMMIO(ScrnInfoPtr pScrn);
extern void ASTUnmapMMIO(ScrnInfoPtr pScrn);

extern void vASTOpenKey(ScrnInfoPtr pScrn);
extern Bool bASTRegInit(ScrnInfoPtr pScrn);
extern void GetDRAMInfo(ScrnInfoPtr pScrn);
extern ULONG GetVRAMInfo(ScrnInfoPtr pScrn);
extern ULONG GetMaxDCLK(ScrnInfoPtr pScrn);
extern void GetChipType(ScrnInfoPtr pScrn);
extern void vASTLoadPalette(ScrnInfoPtr pScrn, int numColors, int *indices, LOCO *colors, VisualPtr pVisual);
extern void ASTDisplayPowerManagementSet(ScrnInfoPtr pScrn, int PowerManagementMode, int flags);
extern void vSetStartAddressCRT1(ASTRecPtr pAST, ULONG base);
extern Bool ASTSetMode(ScrnInfoPtr pScrn, DisplayModePtr mode);
extern Bool GetVGA2EDID(ScrnInfoPtr pScrn, unsigned char *pEDIDBuffer);
extern void vInitDRAMReg(ScrnInfoPtr pScrn);
extern Bool bIsVGAEnabled(ScrnInfoPtr pScrn);
extern void ASTBlankScreen(ScrnInfoPtr pScreen, Bool unblack);
extern Bool InitVGA(ScrnInfoPtr pScrn, ULONG Flags);
extern Bool GetVGAEDID(ScrnInfoPtr pScrn, unsigned char *pEDIDBuffer);
extern Bool bInitAST1180(ScrnInfoPtr pScrn);
extern void GetAST1180DRAMInfo(ScrnInfoPtr pScrn);

extern Bool bInitCMDQInfo(ScrnInfoPtr pScrn, ASTRecPtr pAST);
extern Bool bEnableCMDQ(ScrnInfoPtr pScrn, ASTRecPtr pAST);
extern void vDisable2D(ScrnInfoPtr pScrn, ASTRecPtr pAST);

extern Bool ASTAccelInit(ScreenPtr pScreen);

extern Bool ASTCursorInit(ScreenPtr pScreen);
extern void ASTDisableHWC(ScrnInfoPtr pScrn);

/* Mandatory functions */
static void ASTIdentify(int flags);
const OptionInfoRec *ASTAvailableOptions(int chipid, int busid);
static Bool ASTProbe(DriverPtr drv, int flags);
static Bool ASTPreInit(ScrnInfoPtr pScrn, int flags);
static Bool ASTScreenInit(int Index, ScreenPtr pScreen, int argc, char **argv);
Bool ASTSwitchMode(int scrnIndex, DisplayModePtr mode, int flags);
void ASTAdjustFrame(int scrnIndex, int x, int y, int flags);
static Bool ASTEnterVT(int scrnIndex, int flags);
static void ASTLeaveVT(int scrnIndex, int flags);
static void ASTFreeScreen(int scrnIndex, int flags);
static ModeStatus ASTValidMode(int scrnIndex, DisplayModePtr mode, Bool verbose, int flags);

/* Internally used functions */
static Bool ASTGetRec(ScrnInfoPtr pScrn);
static void ASTFreeRec(ScrnInfoPtr pScrn);
static Bool ASTSaveScreen(ScreenPtr pScreen, Bool unblack);
static Bool ASTCloseScreen(int scrnIndex, ScreenPtr pScreen);
static void ASTSave(ScrnInfoPtr pScrn);
static void ASTRestore(ScrnInfoPtr pScrn);
static void ASTProbeDDC(ScrnInfoPtr pScrn, int index);
static xf86MonPtr ASTDoDDC(ScrnInfoPtr pScrn, int index);
static void vFillASTModeInfo (ScrnInfoPtr pScrn);
static Bool ASTModeInit(ScrnInfoPtr pScrn, DisplayModePtr mode);

#ifdef AstVideo
/* video function */
static void ASTInitVideo(ScreenPtr pScreen);
static int  ASTPutImage( ScrnInfoPtr,
        short, short, short, short, short, short, short, short,
        int, unsigned char*, short, short, Bool, RegionPtr, pointer);
#endif

/*
 * This is intentionally screen-independent.  It indicates the binding
 * choice made in the first PreInit.
 */
_X_EXPORT DriverRec AST = {
   AST_VERSION,
   AST_DRIVER_NAME,
   ASTIdentify,
   ASTProbe,
   ASTAvailableOptions,
   NULL,
   0
};

/* Chipsets */
static SymTabRec ASTChipsets[] = {
   {PCI_CHIP_AST2000,	"ASPEED Graphics Family"},
   {PCI_CHIP_AST2100,	"ASPEED Graphics Family"},
   {PCI_CHIP_AST1180,	"ASPEED AST1180 Graphics"},   
   {-1,			NULL}
};

static PciChipsets ASTPciChipsets[] = {
   {PCI_CHIP_AST2000,		PCI_CHIP_AST2000,	RES_SHARED_VGA},
   {PCI_CHIP_AST2100,		PCI_CHIP_AST2100,	RES_SHARED_VGA},
   {PCI_CHIP_AST1180,		PCI_CHIP_AST1180,	RES_SHARED_VGA},   
   {-1,				-1, 			RES_UNDEFINED }
};

typedef enum {
   OPTION_NOACCEL,
   OPTION_MMIO2D,   
   OPTION_SW_CURSOR,
   OPTION_HWC_NUM,
   OPTION_ENG_CAPS,   
   OPTION_DBG_SELECT,
   OPTION_NO_DDC,
   OPTION_VGA2_CLONE
} ASTOpts;

static const OptionInfoRec ASTOptions[] = {
   {OPTION_NOACCEL,	"NoAccel",	OPTV_BOOLEAN,	{0},	FALSE},
   {OPTION_MMIO2D,	"MMIO2D",	OPTV_BOOLEAN,	{0},	FALSE},
   {OPTION_SW_CURSOR,	"SWCursor",	OPTV_BOOLEAN,	{0},	FALSE},
   {OPTION_HWC_NUM,	"HWCNumber",	OPTV_INTEGER,	{0},	FALSE},
   {OPTION_ENG_CAPS,	"ENGCaps",	OPTV_INTEGER,	{0},	FALSE},
   {OPTION_DBG_SELECT,	"DBGSelect",	OPTV_INTEGER,	{0},	FALSE},
   {OPTION_NO_DDC,	"NoDDC",	OPTV_BOOLEAN,	{0}, 	FALSE},
   {OPTION_VGA2_CLONE,	"VGA2Clone",	OPTV_BOOLEAN,	{0}, 	FALSE},
   {-1,			NULL,		OPTV_NONE,	{0}, 	FALSE}
};

#ifdef XFree86LOADER

static MODULESETUPPROTO(astSetup);

static XF86ModuleVersionInfo astVersRec = {
   AST_DRIVER_NAME,
   MODULEVENDORSTRING,
   MODINFOSTRING1,
   MODINFOSTRING2,
   XORG_VERSION_CURRENT,
   AST_MAJOR_VERSION, AST_MINOR_VERSION, AST_PATCH_VERSION,
   ABI_CLASS_VIDEODRV,
#ifdef PATCH_ABI_VERSION
   ABI_VIDEODRV_VERSION_PATCH,
#else 
   ABI_VIDEODRV_VERSION,
#endif
   MOD_CLASS_VIDEODRV,
   {0, 0, 0, 0}
};

_X_EXPORT XF86ModuleData astModuleData = { &astVersRec, astSetup, NULL };

static pointer
astSetup(pointer module, pointer opts, int *errmaj, int *errmin)
{
   static Bool setupDone = FALSE;

   /* This module should be loaded only once, but check to be sure.
    */
   if (!setupDone) {
      setupDone = TRUE;
      xf86AddDriver(&AST, module, 0);

      /*
       * The return value must be non-NULL on success even though there
       * is no TearDownProc.
       */
      return (pointer) TRUE;
   } else {
      if (errmaj)
	 *errmaj = LDR_ONCEONLY;
      return NULL;
   }
}

#endif	/* XFree86LOADER */

/*
 * ASTIdentify --
 *
 * Returns the string name for the driver based on the chipset. In this
 * case it will always be an AST, so we can return a static string.
 *
 */
static void
ASTIdentify(int flags)
{
   xf86PrintChipsets(AST_NAME, "Driver for ASPEED Graphics Chipsets",
		     ASTChipsets);
}

const OptionInfoRec *
ASTAvailableOptions(int chipid, int busid)
{
	
   return ASTOptions;

}

/*
 * ASTProbe --
 *
 * Look through the PCI bus to find cards that are AST boards.
 * Setup the dispatch table for the rest of the driver functions.
 *
 */
static Bool
ASTProbe(DriverPtr drv, int flags)
{
    int i, numUsed, numDevSections, *usedChips;
    Bool foundScreen = FALSE;
    GDevPtr *devSections;   

   /*
    * Find the config file Device sections that match this
    * driver, and return if there are none.
    */
    if ((numDevSections =
	xf86MatchDevice(AST_DRIVER_NAME, &devSections)) <= 0) {
      return FALSE;
    }

#ifndef XSERVER_LIBPCIACCESS
   /*
    * This probing is just checking the PCI data the server already
    * collected.
    */
    if (xf86GetPciVideoInfo() == NULL) {
	return FALSE;
    }
#endif

    numUsed = xf86MatchPciInstances(AST_NAME, PCI_VENDOR_AST,
				   ASTChipsets, ASTPciChipsets,
				   devSections, numDevSections,
				   drv, &usedChips);

    xfree(devSections);

    if (flags & PROBE_DETECT) {
        if (numUsed > 0)
	    foundScreen = TRUE;
    } else {
        for (i = 0; i < numUsed; i++) {
	    ScrnInfoPtr pScrn = NULL;

	    /* Allocate new ScrnInfoRec and claim the slot */
	    if ((pScrn = xf86ConfigPciEntity(pScrn, 0, usedChips[i],
					     ASTPciChipsets, 0, 0, 0, 0, 0)))
            {
	        EntityInfoPtr pEnt;

	        pEnt = xf86GetEntityInfo(usedChips[i]);

	        pScrn->driverVersion = AST_VERSION;
	        pScrn->driverName = AST_DRIVER_NAME;
	        pScrn->name = AST_NAME;
	    
	        pScrn->Probe = ASTProbe;
	        pScrn->PreInit = ASTPreInit;
	        pScrn->ScreenInit = ASTScreenInit;
	        pScrn->SwitchMode = ASTSwitchMode;
	        pScrn->AdjustFrame = ASTAdjustFrame;   
	        pScrn->EnterVT = ASTEnterVT;
	        pScrn->LeaveVT = ASTLeaveVT;
	        pScrn->FreeScreen = ASTFreeScreen;
	        pScrn->ValidMode = ASTValidMode;
	    
	        foundScreen = TRUE;	    

	    } /* end of if */
        }  /* end of for-loop */
    } /* end of if flags */	   

    xfree(usedChips);

    return foundScreen;
}

/*
 * ASTPreInit --
 *
 * Do initial setup of the board before we know what resolution we will
 * be running at.
 *
 */
static Bool
ASTPreInit(ScrnInfoPtr pScrn, int flags)
{
   EntityInfoPtr pEnt;
   vgaHWPtr hwp;
   int flags24;
   rgb defaultWeight = { 0, 0, 0 };
      
   ASTRecPtr pAST;
   
   ClockRangePtr clockRanges;
   int i;
   MessageType from;

   /* Suport one adapter only now */
   if (pScrn->numEntities != 1)
       return FALSE;

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

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

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

#ifndef XSERVER_LIBPCIACCESS
   if (xf86RegisterResources(pEnt->index, 0, ResExclusive))
       return FALSE;
#endif

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

   /* The fb module should be loaded here when needed */
   if (!xf86LoadSubModule(pScrn, "fb"))
      return FALSE;
   	
   /* Allocate a vgaHWRec */
   if (!vgaHWGetHWRec(pScrn))
       return FALSE;
   hwp = VGAHWPTR(pScrn);

   /* Color Depth Check */
   flags24 = Support32bppFb;
   if (!xf86SetDepthBpp(pScrn, 0, 0, 0, flags24)) {
      return FALSE;
   } else {
      switch (pScrn->depth) {
      case 8:
      case 16:
      case 24:
	 break;
      default:
	 xf86DrvMsg(pScrn->scrnIndex, X_ERROR,
		    "Given depth (%d) is not supported by ast driver\n",
		    pScrn->depth);
	 return FALSE;
      }
   }
   xf86PrintDepthBpp(pScrn);

   switch (pScrn->bitsPerPixel) {
   case 8:
   case 16:
   case 32:
      break;
   default:
      xf86DrvMsg(pScrn->scrnIndex, X_ERROR,
		 "Given bpp (%d) is not supported by ast driver\n",
		 pScrn->bitsPerPixel);
      return FALSE;
   }
   
   /* fill pScrn misc. */
   pScrn->progClock = TRUE;
   pScrn->rgbBits = 6;
   pScrn->monitor = pScrn->confScreen->monitor; /* should be initialized before set gamma */
#ifndef XSERVER_LIBPCIACCESS
   pScrn->racMemFlags = RAC_FB | RAC_COLORMAP | RAC_CURSOR | RAC_VIEWPORT;
   pScrn->racIoFlags = RAC_COLORMAP | RAC_CURSOR | RAC_VIEWPORT;   
#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)) {
         xf86DrvMsg(pScrn->scrnIndex, X_ERROR, "call xf86SetGamma failed \n");      	
	 return FALSE;
      }
   }


   if (!xf86SetWeight(pScrn, defaultWeight, defaultWeight)) {
       return FALSE;
   }    

   if (!xf86SetDefaultVisual(pScrn, -1)) {
       return FALSE;
   }      

   /* Allocate driverPrivate */
   if (!ASTGetRec(pScrn)) {
       xf86DrvMsg(pScrn->scrnIndex, X_ERROR, "call ASTGetRec failed \n");   	
       return FALSE;
   }    

   /* Fill AST Info */
   pAST = ASTPTR(pScrn);
   pAST->pEnt    = xf86GetEntityInfo(pScrn->entityList[0]);
   pAST->PciInfo = xf86GetPciInfoForEntity(pAST->pEnt->index);
#ifndef XSERVER_LIBPCIACCESS
   pAST->PciTag  = pciTag(pAST->PciInfo->bus, pAST->PciInfo->device,
			  pAST->PciInfo->func);
#endif

   /* Process the options
    * pScrn->confScreen, pScrn->display, pScrn->monitor, pScrn->numEntities, 
    * and pScrn->entityList should be initialized before
    */
   xf86CollectOptions(pScrn, NULL);   
   if (!(pAST->Options = xalloc(sizeof(ASTOptions))))
   {  	
      ASTFreeRec(pScrn);   	
      return FALSE;
   }      
   memcpy(pAST->Options, ASTOptions, sizeof(ASTOptions));
   xf86ProcessOptions(pScrn->scrnIndex, pScrn->options, pAST->Options);
    
   /*
    * Set the Chipset and ChipRev, allowing config file entries to
    * override.
    */
   if (pAST->pEnt->device->chipset && *pAST->pEnt->device->chipset) {
      pScrn->chipset = pAST->pEnt->device->chipset;
      from = X_CONFIG;
   } else if (pAST->pEnt->device->chipID >= 0) {
      pScrn->chipset = (char *)xf86TokenToString(ASTChipsets,
						 pAST->pEnt->device->chipID);
      from = X_CONFIG;
      xf86DrvMsg(pScrn->scrnIndex, X_CONFIG, "ChipID override: 0x%04X\n",
		 pAST->pEnt->device->chipID);
   } else {
      from = X_PROBED;
      pScrn->chipset = (char *)xf86TokenToString(ASTChipsets,
						 PCI_DEV_DEVICE_ID(pAST->PciInfo));
   }
   if (pAST->pEnt->device->chipRev >= 0) {
      xf86DrvMsg(pScrn->scrnIndex, X_CONFIG, "ChipRev override: %d\n",
		 pAST->pEnt->device->chipRev);
   }

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

   /* Resource Allocation */
    pAST->IODBase = pScrn->domainIOBase;  
    /* "Patch" the PIOOffset inside vgaHW in order to force
     * the vgaHW module to use our relocated i/o ports.
     */
    VGAHWPTR(pScrn)->PIOOffset = pAST->PIOOffset = pAST->IODBase + PCI_REGION_BASE(pAST->PciInfo, 2, REGION_IO) - 0x380;
	
    pAST->RelocateIO = (IOADDRESS)(PCI_REGION_BASE(pAST->PciInfo, 2, REGION_IO) + pAST->IODBase);
	
   if (pAST->pEnt->device->MemBase != 0) {
      pAST->FBPhysAddr = pAST->pEnt->device->MemBase;
      from = X_CONFIG;
   } else {
      if (PCI_REGION_BASE(pAST->PciInfo, 0, REGION_MEM) != 0) {
	 pAST->FBPhysAddr = PCI_REGION_BASE(pAST->PciInfo, 0, REGION_MEM) & 0xFFF00000;
	 from = X_PROBED;
      } else {
	 xf86DrvMsg(pScrn->scrnIndex, X_ERROR,
		    "No valid FB address in PCI config space\n");
	 ASTFreeRec(pScrn);
	 return FALSE;
      }
   }
   xf86DrvMsg(pScrn->scrnIndex, X_INFO, "Linear framebuffer at 0x%lX\n",
	      (unsigned long) pAST->FBPhysAddr);

   if (pAST->pEnt->device->IOBase != 0) {
      pAST->MMIOPhysAddr = pAST->pEnt->device->IOBase;
      from = X_CONFIG;
   } else {
      if (PCI_REGION_BASE(pAST->PciInfo, 1, REGION_MEM)) {
	 pAST->MMIOPhysAddr = PCI_REGION_BASE(pAST->PciInfo, 1, REGION_MEM) & 0xFFFF0000;
	 from = X_PROBED;
      } else {
	 xf86DrvMsg(pScrn->scrnIndex, X_INFO,
		    "No valid MMIO address in PCI config space\n");
	 ASTFreeRec(pScrn);
	 return FALSE;
      }
   }
   xf86DrvMsg(pScrn->scrnIndex, X_INFO, "IO registers at addr 0x%lX\n",
	      (unsigned long) pAST->MMIOPhysAddr);
	      
   /* Map MMIO */
   pAST->MMIOMapSize = DEFAULT_MMIO_SIZE; 
   if (!ASTMapMMIO(pScrn)) {
      xf86DrvMsg(pScrn->scrnIndex, X_ERROR, "Map Memory Map IO Failed \n");      	
      return FALSE;
   }

   if (PCI_DEV_DEVICE_ID(pAST->PciInfo) == PCI_CHIP_AST1180)
   {   	
       pAST->jChipType = AST1180;
   	
       /* validate mode */
       if ( (pScrn->bitsPerPixel == 8) || (pScrn->depth == 8) )
       {
           xf86DrvMsg(pScrn->scrnIndex, X_ERROR,
		      "Given bpp (%d) is not supported by ast driver\n",
		      pScrn->bitsPerPixel);
           return FALSE;       	
       }
	
       /* Init AST1180 */
       bInitAST1180(pScrn);
       
       /* Get AST1180 Information */
       GetAST1180DRAMInfo(pScrn);     
       pScrn->videoRam = pAST->ulVRAMSize / 1024;
       	
   }
   else    	
   {   	
       /* Init VGA Adapter */
       if (!xf86IsPrimaryPci(pAST->PciInfo))
       {       	
           InitVGA(pScrn, 0);      	
       }

       vASTOpenKey(pScrn);
       bASTRegInit(pScrn);

       /* Get Chip Type */
       if (PCI_DEV_REVISION(pAST->PciInfo) >= 0x20)
           pAST->jChipType = AST2300;   
       else if (PCI_DEV_REVISION(pAST->PciInfo) >= 0x10)
           GetChipType(pScrn);       
       else
           pAST->jChipType = AST2000;

       /* Get DRAM Info */
       GetDRAMInfo(pScrn);     
       pAST->ulVRAMSize = GetVRAMInfo(pScrn);        
       pScrn->videoRam  = pAST->ulVRAMSize / 1024;           
   }
      
   /* Map Framebuffer */
   from = X_DEFAULT;
   if (pAST->pEnt->device->videoRam) {
      pScrn->videoRam = pAST->pEnt->device->videoRam;
      from = X_CONFIG;
   }
   
   pAST->FbMapSize = pScrn->videoRam * 1024;

#if 0   
   if (!ASTMapMem(pScrn)) {
      xf86DrvMsg(pScrn->scrnIndex, X_ERROR, "Map FB Memory Failed \n");      	
      return FALSE;
   }
#endif

   pScrn->memPhysBase = (ULONG)pAST->FBPhysAddr;
   pScrn->fbOffset = 0;

   /* Do DDC 
    * should be done after xf86CollectOptions
    */
   pScrn->monitor->DDC = ASTDoDDC(pScrn, pAST->pEnt->index);    

   /* Mode Valid */
   clockRanges = xnfcalloc(sizeof(ClockRange), 1);
   clockRanges->next = NULL;
   clockRanges->minClock = 9500;
   clockRanges->maxClock = GetMaxDCLK(pScrn) * 1000;   
   clockRanges->clockIndex = -1;
   clockRanges->interlaceAllowed = FALSE;
   clockRanges->doubleScanAllowed = FALSE;
   
   /* Add for AST2100, ycchen@061807 */
   if ((pAST->jChipType == AST2100) || (pAST->jChipType == AST2200) || (pAST->jChipType == AST2300) || (pAST->jChipType == AST1180))
       i = xf86ValidateModes(pScrn, pScrn->monitor->Modes,
			 pScrn->display->modes, clockRanges,
			 0, 320, 1920, 8 * pScrn->bitsPerPixel,
			 200, 1200,
			 pScrn->display->virtualX, pScrn->display->virtualY,
			 pAST->FbMapSize, LOOKUP_BEST_REFRESH);
   else
       i = xf86ValidateModes(pScrn, pScrn->monitor->Modes,
			 pScrn->display->modes, clockRanges,
			 0, 320, 1600, 8 * pScrn->bitsPerPixel,
			 200, 1200,
			 pScrn->display->virtualX, pScrn->display->virtualY,
			 pAST->FbMapSize, LOOKUP_BEST_REFRESH);   

   if (i == -1) {
      ASTFreeRec(pScrn);
      return FALSE;
   }

   xf86PruneDriverModes(pScrn);

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

   xf86SetCrtcForModes(pScrn, INTERLACE_HALVE_V);

   pScrn->currentMode = pScrn->modes;

   xf86PrintModes(pScrn);

   xf86SetDpi(pScrn, 0, 0);

   /* Accelaration Check */
   pAST->noAccel = TRUE;
   pAST->AccelInfoPtr = NULL; 
   pAST->pCMDQPtr = NULL;   
   pAST->CMDQInfo.ulCMDQSize = 0;      
#ifdef	Accel_2D
   if (!xf86ReturnOptValBool(pAST->Options, OPTION_NOACCEL, FALSE))
   {
       if (!xf86LoadSubModule(pScrn, "xaa")) {
	   ASTFreeRec(pScrn);
	   return FALSE;
       }       
       
       pAST->noAccel = FALSE; 
       
       pAST->MMIO2D = TRUE;
#ifndef	MMIO_2D                   
       if (!xf86ReturnOptValBool(pAST->Options, OPTION_MMIO2D, FALSE)) {
           pAST->CMDQInfo.ulCMDQSize = DEFAULT_CMDQ_SIZE;       
           pAST->MMIO2D = FALSE;    	
       }	
#endif

       pAST->ENGCaps = ENG_CAP_ALL;
       if (!xf86GetOptValInteger(pAST->Options, OPTION_ENG_CAPS, &pAST->ENGCaps)) {
           xf86DrvMsg(pScrn->scrnIndex, X_INFO, "No ENG Capability options found\n");      	
       }
       
       pAST->DBGSelect = 0;
       if (!xf86GetOptValInteger(pAST->Options, OPTION_DBG_SELECT, &pAST->DBGSelect)) {
           xf86DrvMsg(pScrn->scrnIndex, X_INFO, "No DBG Seleclt options found\n");      	
       }	       
   }
#endif   

   /* HW Cursor Check */
   pAST->noHWC = TRUE; 
   pAST->HWCInfoPtr = NULL;
   pAST->pHWCPtr = NULL;    
#ifdef	HWC   
   if (!xf86ReturnOptValBool(pAST->Options, OPTION_SW_CURSOR, FALSE)) {
      if (!xf86LoadSubModule(pScrn, "ramdac")) {
	 ASTFreeRec(pScrn);
	 return FALSE;
      }
      
      pAST->noHWC = FALSE;  
      pAST->HWCInfo.HWC_NUM = DEFAULT_HWC_NUM;
      if (!xf86GetOptValInteger(pAST->Options, OPTION_HWC_NUM, &pAST->HWCInfo.HWC_NUM)) {
          xf86DrvMsg(pScrn->scrnIndex, X_INFO, "No HWC_NUM options found\n");      	
      }	
             
   }    
#endif

#ifndef XSERVER_LIBPCIACCESS
   /*  We won't be using the VGA access after the probe */
   xf86SetOperatingState(resVgaIo, pAST->pEnt->index, ResUnusedOpr);
   xf86SetOperatingState(resVgaMem, pAST->pEnt->index, ResDisableOpr);
#endif

   return TRUE;
}


static Bool
ASTScreenInit(int scrnIndex, ScreenPtr pScreen, int argc, char **argv)
{
   ScrnInfoPtr pScrn;
   ASTRecPtr pAST;
   vgaHWPtr hwp;   
   VisualPtr visual;
 
   /* for FB Manager */
   BoxRec FBMemBox;   
   int    AvailFBSize;     

   pScrn = xf86Screens[pScreen->myNum];
   pAST = ASTPTR(pScrn);
   hwp = VGAHWPTR(pScrn);

   if (!ASTMapMem(pScrn)) {
      xf86DrvMsg(pScrn->scrnIndex, X_ERROR, "Map FB Memory Failed \n");      	
      return FALSE;
   }
      
/*   if (!pAST->noAccel) */
   {
       /* AvailFBSize = pAST->FbMapSize - pAST->CMDQInfo.ulCMDQSize; */
       AvailFBSize = pAST->FbMapSize;
   
       FBMemBox.x1 = 0;
       FBMemBox.y1 = 0;
       FBMemBox.x2 = pScrn->displayWidth;
       FBMemBox.y2 = (AvailFBSize / (pScrn->displayWidth * ((pScrn->bitsPerPixel+1)/8))) - 1;

       if (!xf86InitFBManager(pScreen, &FBMemBox)) {
          xf86DrvMsg(pScrn->scrnIndex, X_ERROR, "Failed to init memory manager\n");
          return FALSE;
       }      

   }
       
   vgaHWGetIOBase(hwp);

   vFillASTModeInfo (pScrn);      

   ASTSave(pScrn);     
   if (!ASTModeInit(pScrn, pScrn->currentMode)) {
      xf86DrvMsg(pScrn->scrnIndex, X_ERROR, "Mode Init Failed \n");      	  	
      return FALSE;
   }   

   ASTSaveScreen(pScreen, FALSE);
   ASTAdjustFrame(scrnIndex, pScrn->frameX0, pScrn->frameY0, 0);

   miClearVisualTypes();

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

   if (!miSetPixmapDepths())
   {
       ASTSaveScreen(pScreen, SCREEN_SAVER_OFF);
       return FALSE;
   }    

   switch(pScrn->bitsPerPixel) {
       case 8:
       case 16:
       case 32:
           if (!fbScreenInit(pScreen, pAST->FBVirtualAddr + pScrn->fbOffset,
  	                     pScrn->virtualX, pScrn->virtualY,
		             pScrn->xDpi, pScrn->yDpi,
		             pScrn->displayWidth, pScrn->bitsPerPixel))
               return FALSE;
           break;
       default:
           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, 0, 0);

   xf86SetBlackWhitePixels(pScreen);

#ifdef Accel_2D
   if (!pAST->noAccel)
   {
       if (!ASTAccelInit(pScreen)) {
           xf86DrvMsg(pScrn->scrnIndex, X_ERROR,"Hardware acceleration initialization failed\n");
           pAST->noAccel = TRUE;           
       }
   }
#endif /* end of Accel_2D */
     
   miInitializeBackingStore(pScreen);
   xf86SetBackingStore(pScreen);
   xf86SetSilkenMouse(pScreen);

   miDCInitialize(pScreen, xf86GetPointerScreenFuncs());

   if (!pAST->noHWC)
   {
       if (!ASTCursorInit(pScreen)) {
           xf86DrvMsg(pScrn->scrnIndex, X_ERROR,"Hardware cursor initialization failed\n");
           pAST->noHWC = TRUE;                      
       }
   }
   
   if (!miCreateDefColormap(pScreen))
      return FALSE;

   if (pAST->jChipType != AST1180)
   {
       if(!xf86HandleColormaps(pScreen, 256, (pScrn->depth == 8) ? 8 : pScrn->rgbBits,
                               vASTLoadPalette, NULL,
                               CMAP_PALETTED_TRUECOLOR | CMAP_RELOAD_ON_MODE_SWITCH)) {
           return FALSE;
       }
   }
   
   xf86DPMSInit(pScreen, ASTDisplayPowerManagementSet, 0);

#ifdef AstVideo
   if ( (pAST->jChipType == AST1180) || (pAST->jChipType == AST2300) )
   {   
       xf86DrvMsg(pScrn->scrnIndex, X_INFO,"AST Initial Video()\n");
       ASTInitVideo(pScreen);
   }
#endif
   
   pScreen->SaveScreen = ASTSaveScreen;
   pAST->CloseScreen = pScreen->CloseScreen;
   pScreen->CloseScreen = ASTCloseScreen;

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

   return TRUE;
   	
} /* ASTScreenInit */


Bool
ASTSwitchMode(int scrnIndex, DisplayModePtr mode, int flags)
{
   ScrnInfoPtr pScrn = xf86Screens[scrnIndex];
   ASTRecPtr pAST = ASTPTR(pScrn);
	
   /* VideoMode validate */
   if (mode->CrtcHDisplay > pScrn->displayWidth)
       return FALSE;
   if ((pAST->VideoModeInfo.ScreenPitch * mode->CrtcVDisplay) > pAST->ulVRAMSize)
       return FALSE;
   
   /* VideModeInfo Update */
   pAST->VideoModeInfo.ScreenWidth  = mode->CrtcHDisplay;   
   pAST->VideoModeInfo.ScreenHeight = mode->CrtcVDisplay;   
   pAST->VideoModeInfo.ScreenPitch  = pScrn->displayWidth * ((pScrn->bitsPerPixel + 1) / 8) ;

#ifdef	HWC
   if (pAST->pHWCPtr) {
       xf86FreeOffscreenLinear(pAST->pHWCPtr);		/* free HWC Cache */
       pAST->pHWCPtr = NULL;      
   }
   ASTDisableHWC(pScrn);
#endif

#ifdef Accel_2D 
   if (pAST->pCMDQPtr) {
       xf86FreeOffscreenLinear(pAST->pCMDQPtr);		/* free CMDQ */
       pAST->pCMDQPtr = NULL;             
   } 
   vDisable2D(pScrn, pAST);
#endif
   
   /* Fixed display abnormal on the of the screen if run xvidtune, ycchen@122909 */
   /* ASTRestore(pScrn); */
   
   return ASTModeInit(pScrn, mode);

}

void
ASTAdjustFrame(int scrnIndex, int x, int y, int flags)
{
   ScrnInfoPtr pScrn = xf86Screens[scrnIndex];
   ASTRecPtr   pAST  = ASTPTR(pScrn);
   ULONG base;
      
   base = y * pAST->VideoModeInfo.ScreenPitch + x * ((pAST->VideoModeInfo.bitsPerPixel + 1) / 8);
   /* base = base >> 2; */			/* DW unit */

   vSetStartAddressCRT1(pAST, base);

}

/* enter into X Server */		
static Bool
ASTEnterVT(int scrnIndex, int flags)
{
   ScrnInfoPtr pScrn = xf86Screens[scrnIndex];
   ASTRecPtr pAST = ASTPTR(pScrn);

   /* Fixed suspend can't resume issue */
   if (!bIsVGAEnabled(pScrn))
   {
       if (pAST->jChipType == AST1180)
           bInitAST1180(pScrn);
       else	
           InitVGA(pScrn, 1);      	   	
       ASTRestore(pScrn);
   }   

   if (!ASTModeInit(pScrn, pScrn->currentMode))
      return FALSE;
   ASTAdjustFrame(scrnIndex, pScrn->frameX0, pScrn->frameY0, 0);
   
   return TRUE;

}

/* leave X server */
static void
ASTLeaveVT(int scrnIndex, int flags)
{
	
   ScrnInfoPtr pScrn = xf86Screens[scrnIndex];
   ASTRecPtr pAST = ASTPTR(pScrn);
   vgaHWPtr hwp = VGAHWPTR(pScrn);

#ifdef	HWC
   if (pAST->pHWCPtr) {
       xf86FreeOffscreenLinear(pAST->pHWCPtr);		/* free HWC Cache */
       pAST->pHWCPtr = NULL;      
   }
   ASTDisableHWC(pScrn);
#endif

#ifdef Accel_2D  
   if (pAST->pCMDQPtr) {
       xf86FreeOffscreenLinear(pAST->pCMDQPtr);		/* free CMDQ */
       pAST->pCMDQPtr = NULL;             
   }    
   vDisable2D(pScrn, pAST);
#endif
      
   ASTRestore(pScrn);
   
   if (pAST->jChipType == AST1180)
       ASTBlankScreen(pScrn, 0);

   vgaHWLock(hwp);	

}

static void
ASTFreeScreen(int scrnIndex, int flags)
{
   ASTFreeRec(xf86Screens[scrnIndex]);
   if (xf86LoaderCheckSymbol("vgaHWFreeHWRec"))
      vgaHWFreeHWRec(xf86Screens[scrnIndex]);   
}

static ModeStatus
ASTValidMode(int scrnIndex, DisplayModePtr mode, Bool verbose, int flags)
{

   ScrnInfoPtr pScrn = xf86Screens[scrnIndex];
   ASTRecPtr   pAST  = ASTPTR(pScrn);
   ModeStatus Flags = MODE_NOMODE;
   UCHAR jReg;
   ULONG RequestBufferSize;
   
   if (mode->Flags & V_INTERLACE) {
      if (verbose) {
	 xf86DrvMsg(scrnIndex, X_PROBED,
		    "Removing interlaced mode \"%s\"\n", mode->name);
      }
      return MODE_NO_INTERLACE;
   }

   if ((mode->CrtcHDisplay > MAX_HResolution) || (mode->CrtcVDisplay > MAX_VResolution)) {
      if (verbose) {
	 xf86DrvMsg(scrnIndex, X_PROBED,
		    "Removing the mode \"%s\"\n", mode->name);
      }
      return Flags;
   }

   /* Valid Framebuffer size */
   RequestBufferSize = mode->CrtcHDisplay * ((pScrn->bitsPerPixel + 1) / 8) * mode->CrtcVDisplay;
   if (RequestBufferSize > pAST->ulVRAMSize)
      return Flags;
   
   /* Check BMC scratch for iKVM compatible */
   if (pAST->jChipType == AST2000)
       jReg = 0x80;
   else if (pAST->jChipType == AST1180)        
       jReg = 0x01;
   else    
   {
       GetIndexRegMask(CRTC_PORT, 0xD0, 0xFF, jReg);
   }		
   
   if ( !(jReg & 0x80) || (jReg & 0x01) )   
   {
      if ( (mode->CrtcHDisplay == 1680) && (mode->CrtcVDisplay == 1050) )
          return MODE_OK;
      if ( (mode->CrtcHDisplay == 1280) && (mode->CrtcVDisplay == 800) )
          return MODE_OK;
      if ( (mode->CrtcHDisplay == 1440) && (mode->CrtcVDisplay == 900) )
          return MODE_OK;
          
      if ( (pAST->jChipType == AST2100) || (pAST->jChipType == AST2200) || (pAST->jChipType == AST2300) || (pAST->jChipType == AST1180) )	
      {
          if ( (mode->CrtcHDisplay == 1920) && (mode->CrtcVDisplay == 1080) )
              return MODE_OK;
      }
   }	
   
   /* Add for AST2100, ycchen@061807 */
   if ( (pAST->jChipType == AST2100) || (pAST->jChipType == AST2200) || (pAST->jChipType == AST2300) || (pAST->jChipType == AST1180) )	
   {
       if ( (mode->CrtcHDisplay == 1920) && (mode->CrtcVDisplay == 1200) )
           return MODE_OK;
   }
     
   switch (mode->CrtcHDisplay)
   {
   case 640:
       if (mode->CrtcVDisplay == 480) Flags=MODE_OK;
       break;
   case 800:
       if (mode->CrtcVDisplay == 600) Flags=MODE_OK;
       break;
   case 1024:
       if (mode->CrtcVDisplay == 768) Flags=MODE_OK;
       break;
   case 1280:
       if (mode->CrtcVDisplay == 1024) Flags=MODE_OK;
       break;
   case 1600:
       if (mode->CrtcVDisplay == 1200) Flags=MODE_OK;
       break;
   default:
       return Flags;
   }

   return Flags;
}

/* Internal used modules */
/*
 * ASTGetRec and ASTFreeRec --
 *
 * Private data for the driver is stored in the screen structure.
 * These two functions create and destroy that private data.
 *
 */
static Bool
ASTGetRec(ScrnInfoPtr pScrn)
{
   if (pScrn->driverPrivate)
      return TRUE;

   pScrn->driverPrivate = xnfcalloc(sizeof(ASTRec), 1);
   return TRUE;
}

static void
ASTFreeRec(ScrnInfoPtr pScrn)
{
   if (!pScrn)
      return;
   if (!pScrn->driverPrivate)
      return;
   xfree(pScrn->driverPrivate);
   pScrn->driverPrivate = 0;
}

static Bool
ASTSaveScreen(ScreenPtr pScreen, Bool unblack)
{
   /* replacement of vgaHWBlankScreen(pScrn, unblank) without seq reset */
   /* return vgaHWSaveScreen(pScreen, unblack); */   
   ScrnInfoPtr pScrn = NULL;

   if (pScreen != NULL)
      pScrn = xf86Screens[pScreen->myNum];

   if ((pScrn != NULL) && pScrn->vtSema) {
     ASTBlankScreen(pScrn, unblack);
   }
   return (TRUE);   
}

static Bool
ASTCloseScreen(int scrnIndex, ScreenPtr pScreen)
{
   ScrnInfoPtr pScrn = xf86Screens[scrnIndex];
   vgaHWPtr hwp = VGAHWPTR(pScrn);
   ASTRecPtr pAST = ASTPTR(pScrn);

   if (pScrn->vtSema == TRUE)
   {  
#ifdef	HWC
   if (pAST->pHWCPtr) {
       xf86FreeOffscreenLinear(pAST->pHWCPtr);		/* free HWC Cache */
       pAST->pHWCPtr = NULL;      
   }
       ASTDisableHWC(pScrn);
#endif
   	   
#ifdef Accel_2D  
   if (pAST->pCMDQPtr) {
       xf86FreeOffscreenLinear(pAST->pCMDQPtr);		/* free CMDQ */
       pAST->pCMDQPtr = NULL;      
   }
   vDisable2D(pScrn, pAST);
#endif
         
      ASTRestore(pScrn);
      
      if (pAST->jChipType == AST1180)
          ASTBlankScreen(pScrn, 0);
      
      vgaHWLock(hwp);
   }

   ASTUnmapMem(pScrn);
   vgaHWUnmapMem(pScrn);

   if(pAST->AccelInfoPtr) {
       XAADestroyInfoRec(pAST->AccelInfoPtr);
       pAST->AccelInfoPtr = NULL;
   }

   if(pAST->HWCInfoPtr) {
       xf86DestroyCursorInfoRec(pAST->HWCInfoPtr);
       pAST->HWCInfoPtr = NULL;
   }

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

static void
ASTSave(ScrnInfoPtr pScrn)
{
   ASTRecPtr pAST;
   vgaRegPtr vgaReg;
   ASTRegPtr astReg;   
   int i, icount=0;
   ULONG ulData;

   pAST = ASTPTR(pScrn);
   vgaReg = &VGAHWPTR(pScrn)->SavedReg;
   astReg = &pAST->SavedReg;
    
   /* do save */    
   if (xf86IsPrimaryPci(pAST->PciInfo)) {
       vgaHWSave(pScrn, vgaReg, VGA_SR_ALL);
   }
   else {
       vgaHWSave(pScrn, vgaReg, VGA_SR_MODE);
   }
   
   /* Ext. Save */
   if (pAST->jChipType == AST1180)
   {
       for (i=0; i<12; i++)
       {
           ReadAST1180SOC(AST1180_GFX_BASE + AST1180_VGA1_CTRL+i*4, ulData);                
           astReg->GFX[i] = ulData;       	
       }		   	
   }
   else
   {	   
       vASTOpenKey(pScrn);
   
       /* fixed Console Switch Refresh Rate Incorrect issue, ycchen@051106 */   
       for (i=0x81; i<=0xB6; i++)
           GetIndexReg(CRTC_PORT, (UCHAR) (i), astReg->ExtCRTC[icount++]);
       for (i=0xBC; i<=0xC1; i++)
           GetIndexReg(CRTC_PORT, (UCHAR) (i), astReg->ExtCRTC[icount++]);
       GetIndexReg(CRTC_PORT, (UCHAR) (0xBB), astReg->ExtCRTC[icount]);
   }    

}

static void
ASTRestore(ScrnInfoPtr pScrn)
{
   ASTRecPtr pAST;
   vgaRegPtr vgaReg;
   ASTRegPtr astReg;   
   int i, icount=0;
   ULONG ulData;

   pAST = ASTPTR(pScrn);
   vgaReg = &VGAHWPTR(pScrn)->SavedReg;
   astReg = &pAST->SavedReg;
    
   /* do restore */    
   vgaHWProtect(pScrn, TRUE);
   if (xf86IsPrimaryPci(pAST->PciInfo))
       vgaHWRestore(pScrn, vgaReg, VGA_SR_ALL);
   else
       vgaHWRestore(pScrn, vgaReg, VGA_SR_MODE);     
   vgaHWProtect(pScrn, FALSE);   
   
   if (pAST->jChipType == AST1180)
   {
       for (i=0; i<12; i++)
       {
           ulData = astReg->GFX[i];       	
           WriteAST1180SOC(AST1180_GFX_BASE + AST1180_VGA1_CTRL+i*4, ulData);                
       }		   	
   }
   else
   {	       
      /* Ext. restore */
      vASTOpenKey(pScrn);
      
      /* fixed Console Switch Refresh Rate Incorrect issue, ycchen@051106 */
      for (i=0x81; i<=0xB6; i++)
          SetIndexReg(CRTC_PORT, (UCHAR) (i), astReg->ExtCRTC[icount++]);
      for (i=0xBC; i<=0xC1; i++)
          SetIndexReg(CRTC_PORT, (UCHAR) (i), astReg->ExtCRTC[icount++]);
      SetIndexReg(CRTC_PORT, (UCHAR) (0xBB), astReg->ExtCRTC[icount]);
   }

}

static void
ASTProbeDDC(ScrnInfoPtr pScrn, int index)
{
   vbeInfoPtr pVbe;	
   ASTRecPtr pAST = ASTPTR(pScrn);	
   unsigned char DDC_data[128];
   Bool Flags;

   if ( (pAST->jChipType == AST1180) || (!xf86IsPrimaryPci(pAST->PciInfo)) )
   {
       if (pAST->jChipType == AST1180)	
           Flags = GetVGA2EDID(pScrn, DDC_data);
       else
           Flags = GetVGAEDID(pScrn, DDC_data);
       
       if (Flags)    
       {
           ConfiguredMonitor = xf86InterpretEDID(pScrn->scrnIndex, DDC_data);
       }
       else
           xf86DrvMsg(pScrn->scrnIndex, X_INFO,"[ASTProbeDDC] Can't Get EDID Properly \n");               
   }   
   else
   {
       if (xf86LoadSubModule(pScrn, "vbe")) {
          pVbe = VBEInit(NULL, index);
          ConfiguredMonitor = vbeDoEDID(pVbe, NULL);
          vbeFree(pVbe);
       }
   }
}

#define SkipDT	0x00
#define DT1	0x01
#define DT2 	0x02
	
static xf86MonPtr
ASTDoDDC(ScrnInfoPtr pScrn, int index)
{
   vbeInfoPtr pVbe;
   xf86MonPtr MonInfo = NULL, MonInfo1 = NULL, MonInfo2 = NULL;
   ASTRecPtr pAST = ASTPTR(pScrn);
   unsigned long i, j, k;
   unsigned char DDC_data[128];
   struct monitor_ranges ranges, ranges1, ranges2;
   int DTSelect, dclock1=0, h_active1=0, v_active1=0, dclock2=0, h_active2=0, v_active2=0;
   struct std_timings stdtiming, *stdtiming1, *stdtiming2;
   Bool Flags;
   
   /* Honour Option "noDDC" */
   if (xf86ReturnOptValBool(pAST->Options, OPTION_NO_DDC, FALSE)) {
      return MonInfo;
   }

   if ( (pAST->jChipType == AST1180) || (!xf86IsPrimaryPci(pAST->PciInfo)) )
   {
   	   	
        if (pAST->jChipType == AST1180)	
            Flags = GetVGA2EDID(pScrn, DDC_data);
        else
            Flags = GetVGAEDID(pScrn, DDC_data);
        
        if (Flags)
        {	
            MonInfo = xf86InterpretEDID(pScrn->scrnIndex, DDC_data);       
            xf86PrintEDID(MonInfo);
            xf86SetDDCproperties(pScrn, MonInfo);   	
        }
        else
            xf86DrvMsg(pScrn->scrnIndex, X_INFO,"[ASTDoDDC] Can't Get EDID Properly \n");                

   }
   else
   {
   	
       if (xf86LoadSubModule(pScrn, "vbe") && (pVbe = VBEInit(NULL, index))) {
          MonInfo1 = vbeDoEDID(pVbe, NULL);
          MonInfo = MonInfo1;
      
          /* For VGA2 CLONE Support, ycchen@012508 */
          if ((xf86ReturnOptValBool(pAST->Options, OPTION_VGA2_CLONE, FALSE)) || pAST->VGA2Clone) {
              if (GetVGA2EDID(pScrn, DDC_data) == TRUE) {
                  xf86DrvMsg(pScrn->scrnIndex, X_INFO, "Get VGA2 EDID Correctly!! \n");	
                  MonInfo2 = xf86InterpretEDID(pScrn->scrnIndex, DDC_data);
                  if (MonInfo1 == NULL)	/* No DDC1 EDID */
                      MonInfo = MonInfo2;
                  else {			/* Check with VGA1 & VGA2 EDID */
                      /* Update establishment timing */
                      MonInfo->timings1.t1 = MonInfo1->timings1.t1 & MonInfo2->timings1.t1;
                      MonInfo->timings1.t2 = MonInfo1->timings1.t2 & MonInfo2->timings1.t2;
                      MonInfo->timings1.t_manu = MonInfo1->timings1.t_manu & MonInfo2->timings1.t_manu;
                  
                      /* Update Std. Timing */
                      for (i=0; i<8; i++) {
	                  stdtiming.hsize = stdtiming.vsize = stdtiming.refresh = stdtiming.id = 0;	              
                          for (j=0; j<8; j++) {                      	
                              if ((MonInfo1->timings2[i].hsize == MonInfo2->timings2[j].hsize) && \
                                  (MonInfo1->timings2[i].vsize == MonInfo2->timings2[j].vsize) && \
                                  (MonInfo1->timings2[i].refresh == MonInfo2->timings2[j].refresh)) {
                                   stdtiming = MonInfo1->timings2[i];
                                   break;
                              }        
                          }
                      
                          MonInfo->timings2[i] = stdtiming;
                      } /* Std. Timing */
               
                      /* Get Detailed Timing */
                      for (i=0;i<4;i++) {
                        if (MonInfo1->det_mon[i].type == 0xFD)
                            ranges1 = MonInfo1->det_mon[i].section.ranges;
                        else if (MonInfo1->det_mon[i].type == 0xFA)
                            stdtiming1 = MonInfo1->det_mon[i].section.std_t;    
                        else if (MonInfo1->det_mon[i].type == 0x00) {
                            if (MonInfo1->det_mon[i].section.d_timings.clock > dclock1)
                                dclock1 = MonInfo1->det_mon[i].section.d_timings.clock;
                            if (MonInfo1->det_mon[i].section.d_timings.h_active > h_active1)
                                h_active1 = MonInfo1->det_mon[i].section.d_timings.h_active;
                            if (MonInfo1->det_mon[i].section.d_timings.v_active > v_active1)
                                v_active1 = MonInfo1->det_mon[i].section.d_timings.v_active;                            
                        }	
                        if (MonInfo2->det_mon[i].type == 0xFD)
                            ranges2 = MonInfo2->det_mon[i].section.ranges;
                        else if (MonInfo1->det_mon[i].type == 0xFA)
                            stdtiming2 = MonInfo2->det_mon[i].section.std_t;                        
                        else if (MonInfo2->det_mon[i].type == 0x00) {
                             if (MonInfo2->det_mon[i].section.d_timings.clock > dclock2)
                                dclock2 = MonInfo2->det_mon[i].section.d_timings.clock;
                             if (MonInfo2->det_mon[i].section.d_timings.h_active > h_active2)
                                h_active2 = MonInfo2->det_mon[i].section.d_timings.h_active;
                             if (MonInfo2->det_mon[i].section.d_timings.v_active > v_active2)
                                v_active2 = MonInfo2->det_mon[i].section.d_timings.v_active;                            
                        }                                                            	 
                      } /* Get Detailed Timing */
   
                      /* Chk Detailed Timing */
                      if ((dclock1 >= dclock2) && (h_active1 >= h_active2) && (v_active1 >= v_active2))
                          DTSelect = DT2;
                      else if ((dclock2 >= dclock1) && (h_active2 >= h_active1) && (v_active2 >= v_active1))
                          DTSelect = DT1;
                      else
                          DTSelect = SkipDT;
   
                      /* Chk Monitor Descriptor */    
                      ranges = ranges1;
                      ranges.min_h = ranges1.min_h > ranges2.min_h ? ranges1.min_h:ranges2.min_h;
                      ranges.min_v = ranges1.min_v > ranges2.min_v ? ranges1.min_v:ranges2.min_v;                  
                      ranges.max_h = ranges1.max_h < ranges2.max_h ? ranges1.max_h:ranges2.max_h;
                      ranges.max_v = ranges1.max_v < ranges2.max_v ? ranges1.max_v:ranges2.max_v;
                      ranges.max_clock = ranges1.max_clock < ranges2.max_clock ? ranges1.max_clock:ranges2.max_clock;
                  
                      /* Update Detailed Timing */
                      for (i=0; i<4; i++)
                      {
                          if (MonInfo->det_mon[i].type == 0xFD) {
                              MonInfo->det_mon[i].section.ranges = ranges;
                          }                      
                          else if (MonInfo->det_mon[i].type == 0xFA) {
                             for (j=0; j<5; j++) {
            	                 stdtiming.hsize = stdtiming.vsize = stdtiming.refresh = stdtiming.id = 0;
                                 for (k=0; k<5; k++) {
                                     if ((stdtiming1[j].hsize == stdtiming2[k].hsize) && \
                                         (stdtiming1[j].vsize == stdtiming2[k].vsize) && \
                                         (stdtiming1[j].refresh == stdtiming2[k].refresh)) {
                                          stdtiming = stdtiming1[j];
                                          break;
                                     }        
                                 }
                                 stdtiming1[j] = stdtiming;
                             } /* Std. Timing */                                                    
                          } /* FA */
                          else if (MonInfo->det_mon[i].type == 0x00) {
                              if (DTSelect == DT2)
                                  MonInfo->det_mon[i] = MonInfo2->det_mon[i];
                              else if (DTSelect == DT1)
                                  MonInfo->det_mon[i] = MonInfo1->det_mon[i];
                              else /* SkipDT */
                              {   /* use 1024x768 as default */
                                  MonInfo->det_mon[i] = MonInfo1->det_mon[i];
                                  MonInfo->det_mon[i].section.d_timings.clock = 65000000;
                                  MonInfo->det_mon[i].section.d_timings.h_active = 1024;
                                  MonInfo->det_mon[i].section.d_timings.h_blanking = 320;
                                  MonInfo->det_mon[i].section.d_timings.v_active = 768;
                                  MonInfo->det_mon[i].section.d_timings.v_blanking = 38;
                                  MonInfo->det_mon[i].section.d_timings.h_sync_off = 24;
                                  MonInfo->det_mon[i].section.d_timings.h_sync_width = 136;
                                  MonInfo->det_mon[i].section.d_timings.v_sync_off = 3;
                                  MonInfo->det_mon[i].section.d_timings.v_sync_width = 6;
                              }                                                	
                          } /* 00 */
                          else { /* use Monitor 1 as default */
                              MonInfo->det_mon[i] = MonInfo1->det_mon[i];                      
                          }
                
                      } /* Update Detailed Timing */
                  
                      /* set feature size */
                      if (DTSelect == DT2)  {
                          MonInfo->features.hsize = MonInfo2->features.hsize;
                          MonInfo->features.vsize = MonInfo2->features.vsize;                          	
                      }
                      else if (DTSelect == DT1)  {
                          MonInfo->features.hsize = MonInfo1->features.hsize;
                          MonInfo->features.vsize = MonInfo1->features.vsize;                          	
                      }
                      else	/* Skip DT */
                      {   /* use 1024x768 as default */
                          MonInfo->features.hsize = 0x20;
                          MonInfo->features.vsize = 0x18;                  	
                      }	
                                  	               	
                  } /* Check with VGA1 & VGA2 EDID */
        	    
              } /* GetVGA2EDID */
              else {
                  xf86DrvMsg(pScrn->scrnIndex, X_INFO, "Can't Get VGA2 EDID Correctly!! \n");
              }    
         
          }
      
          xf86PrintEDID(MonInfo);
          xf86SetDDCproperties(pScrn, MonInfo);
          vbeFree(pVbe);
       } else {
          xf86DrvMsg(pScrn->scrnIndex, X_INFO,
		     "this driver cannot do DDC without VBE\n");   
       }
   
   } /* AST1180 */

   return MonInfo;
}

static void
vFillASTModeInfo (ScrnInfoPtr pScrn)
{
    ASTRecPtr pAST;
    
    pAST = ASTPTR(pScrn);
    
    pAST->VideoModeInfo.ScreenWidth = pScrn->virtualX;   
    pAST->VideoModeInfo.ScreenHeight = pScrn->virtualY;   
    pAST->VideoModeInfo.bitsPerPixel = pScrn->bitsPerPixel;   
    /* Fixed screen pitch incorrect in some specific monitor, ycchen@071707 */
    pAST->VideoModeInfo.ScreenPitch = pScrn->displayWidth * ((pScrn->bitsPerPixel + 1) / 8) ;

}

static Bool
ASTModeInit(ScrnInfoPtr pScrn, DisplayModePtr mode)
{
    vgaHWPtr hwp;
    ASTRecPtr pAST;

    hwp = VGAHWPTR(pScrn);
    pAST = ASTPTR(pScrn);

    vgaHWUnlock(hwp);

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

    pScrn->vtSema = TRUE;
    pAST->ModePtr = mode;

    if (!ASTSetMode(pScrn, mode))
      return FALSE;
    
    vgaHWProtect(pScrn, FALSE);

    return TRUE;
}

#ifdef AstVideo
/*
 * Video Part by ic_yang
 */
#include "fourcc.h"

#define NUM_ATTRIBUTES  	8
#define NUM_IMAGES 		8
#define NUM_FORMATS     	3

#define IMAGE_MIN_WIDTH         32
#define IMAGE_MIN_HEIGHT        24
#define IMAGE_MAX_WIDTH         1920
#define IMAGE_MAX_HEIGHT        1080

#define MAKE_ATOM(a) MakeAtom(a, sizeof(a) - 1, TRUE)

static XF86ImageRec ASTImages[NUM_IMAGES] =
{
    XVIMAGE_YUY2, /* If order is changed, ASTOffscreenImages must be adapted */
};

static XF86VideoFormatRec ASTFormats[NUM_FORMATS] =
{
   { 8, PseudoColor},
   {16, TrueColor},
   {24, TrueColor}
};

/* client libraries expect an encoding */
static XF86VideoEncodingRec DummyEncoding =
{
   0,
   "XV_IMAGE",
   0, 0,                /* Will be filled in */
   {1, 1}
};

static char astxvcolorkey[] 				= "XV_COLORKEY";
static char astxvbrightness[] 				= "XV_BRIGHTNESS";
static char astxvcontrast[] 				= "XV_CONTRAST";
static char astxvsaturation[] 				= "XV_SATURATION";
static char astxvhue[] 				        = "XV_HUE";
static char astxvgammared[] 				= "XV_GAMMA_RED";
static char astxvgammagreen[] 				= "XV_GAMMA_GREEN";
static char astxvgammablue[] 				= "XV_GAMMA_BLUE";

static XF86AttributeRec ASTAttributes[NUM_ATTRIBUTES] =
{
   {XvSettable | XvGettable, 0, (1 << 24) - 1, astxvcolorkey},
   {XvSettable | XvGettable, -128, 127, astxvbrightness},
   {XvSettable | XvGettable, 0, 255, astxvcontrast},
   {XvSettable | XvGettable, -180, 180, astxvsaturation},
   {XvSettable | XvGettable, -180, 180, astxvhue},
   {XvSettable | XvGettable, 100, 10000, astxvgammared},
   {XvSettable | XvGettable, 100, 10000, astxvgammagreen},
   {XvSettable | XvGettable, 100, 10000, astxvgammablue},
};

static void ASTStopVideo(ScrnInfoPtr pScrn, pointer data, Bool exit)
{
    ASTPortPrivPtr pPriv = (ASTPortPrivPtr)data;
    ASTPtr pAST = ASTPTR(pScrn);
    
    REGION_EMPTY(pScrn->pScreen, &pPriv->clip);
    
    if(exit)
    {
        if(pPriv->fbAreaPtr) 
        {
            xf86FreeOffscreenArea(pPriv->fbAreaPtr);
            pPriv->fbAreaPtr = NULL;
            pPriv->fbSize = 0;
        }
        /* clear all flag */
        pPriv->videoStatus = 0;
    } 
    else
    {
#if 0    	
        if(pPriv->videoStatus & CLIENT_VIDEO_ON) 
        {
            pPriv->videoStatus |= OFF_TIMER;
        
        }
#endif
    }
}

static int ASTSetPortAttribute(ScrnInfoPtr pScrn, Atom attribute, INT32 value, pointer data)
{
    ASTPortPrivPtr pPriv = (ASTPortPrivPtr)data;
    ASTPtr pAST = ASTPTR(pScrn);
    
    xf86DrvMsg(pScrn->scrnIndex, X_INFO,"ASTSetPortAttribute(),attribute=%x\n", attribute);
    
    if (attribute == pAST->xvBrightness) 
    {
        if((value < -128) || (value > 127))
         return BadValue;
        
        pPriv->brightness = value;
    }
    else if (attribute == pAST->xvContrast) 
    {
        if ((value < 0) || (value > 255))
         return BadValue;
        
        pPriv->contrast = value;
    }
    else if (attribute == pAST->xvSaturation)
    {
        if ((value < -180) || (value > 180))
         return BadValue;
        
        pPriv->saturation = value;
    }
    else if (attribute == pAST->xvHue)
    {
        if ((value < -180) || (value > 180))
         return BadValue;
        
        pPriv->hue = value;
    }
    else if (attribute == pAST->xvColorKey) 
    {
          pPriv->colorKey = value;
          REGION_EMPTY(pScrn->pScreen, &pPriv->clip);
    }
    else if(attribute == pAST->xvGammaRed) 
    {
        if((value < 100) || (value > 10000))
            return BadValue;
        pPriv->gammaR = value;
    }
    else if(attribute == pAST->xvGammaGreen) 
    {
        if((value < 100) || (value > 10000))
            return BadValue;
        pPriv->gammaG = value;       
    } 
    else if(attribute == pAST->xvGammaBlue) 
    {
        if((value < 100) || (value > 10000))
            return BadValue;
        pPriv->gammaB = value;
    } 
    else
    {
        return BadMatch;
    }
    
    return Success;
}

static int ASTGetPortAttribute(ScrnInfoPtr pScrn, Atom attribute, INT32 *value, pointer data)
{
    ASTPortPrivPtr pPriv = (ASTPortPrivPtr)data;
    ASTPtr pAST = ASTPTR(pScrn);
    
    xf86DrvMsg(pScrn->scrnIndex, X_INFO,"ASTGetPortAttribute(),attribute=%x\n", attribute);
        
    if (attribute == pAST->xvBrightness) 
    {
        *value = pPriv->brightness;
    }
    else if (attribute == pAST->xvContrast) 
    {
        *value = pPriv->contrast;
    }
    else if (attribute == pAST->xvSaturation) 
    {
        *value = pPriv->saturation;
    }
    else if (attribute == pAST->xvHue) 
    {
        *value = pPriv->hue;
    } 
    else if(attribute == pAST->xvGammaRed) 
    {
        *value = pPriv->gammaR;
    	  
    }
    else if(attribute == pAST->xvGammaGreen) 
    {
        *value = pPriv->gammaG;
    }
    else if(attribute == pAST->xvGammaBlue) 
    {
        *value = pPriv->gammaB;
    }
    else if (attribute == pAST->xvColorKey) 
    {
        *value = pPriv->colorKey;
    }
    else
        return BadMatch;
    
    return Success;
}

static void ASTQueryBestSize(ScrnInfoPtr pScrn, Bool motion, 
                                short vid_w, short vid_h, 
                                short drw_w, short drw_h,
                                unsigned int *p_w, unsigned int *p_h,
                                pointer data)
{
    *p_w = drw_w;
    *p_h = drw_h;
    xf86DrvMsg(pScrn->scrnIndex, X_INFO,"ASTQueryBestSize()\n");
  /* TODO: report the HW limitation */
}

static int ASTQueryImageAttributes(ScrnInfoPtr pScrn, int id,
                                    unsigned short *w, unsigned short *h,
                                    int *pitches, int *offsets)
{
    int pitchY, pitchUV;
    int size, sizeY, sizeUV;

    xf86DrvMsg(pScrn->scrnIndex, X_INFO,"ASTQueryImageAttributes()\n");

    if(*w < IMAGE_MIN_WIDTH) *w = IMAGE_MIN_WIDTH;
    if(*h < IMAGE_MIN_HEIGHT) *h = IMAGE_MIN_HEIGHT;

    switch(id) {
    case PIXEL_FMT_YV12:
        *w = (*w + 7) & ~7;
        *h = (*h + 1) & ~1;
        pitchY = *w;
        pitchUV = *w >> 1;
        if(pitches) {
          pitches[0] = pitchY;
          pitches[1] = pitches[2] = pitchUV;
        }
        sizeY = pitchY * (*h);
        sizeUV = pitchUV * ((*h) >> 1);
        if(offsets) {
          offsets[0] = 0;
          offsets[1] = sizeY;
          offsets[2] = sizeY + sizeUV;
        }
        size = sizeY + (sizeUV << 1);
        break;
    case PIXEL_FMT_NV12:
    case PIXEL_FMT_NV21:
        *w = (*w + 7) & ~7;
        *h = (*h + 1) & ~1;
		pitchY = *w;
    	pitchUV = *w;
    	if(pitches) {
      	    pitches[0] = pitchY;
            pitches[1] = pitchUV;
        }
    	sizeY = pitchY * (*h);
    	sizeUV = pitchUV * ((*h) >> 1);
    	if(offsets) {
          offsets[0] = 0;
          offsets[1] = sizeY;
        }
        size = sizeY + (sizeUV << 1);
        break;
    case PIXEL_FMT_YUY2:
    case PIXEL_FMT_UYVY:
    case PIXEL_FMT_YVYU:
    case PIXEL_FMT_RGB6:
    case PIXEL_FMT_RGB5:
    default:
        *w = (*w + 1) & ~1;
        pitchY = *w << 1;
        if(pitches) pitches[0] = pitchY;
        if(offsets) offsets[0] = 0;
        size = pitchY * (*h);
        break;
    }

    return size;
}

extern void ASTDisplayVideo(ScrnInfoPtr pScrn, ASTPortPrivPtr pPriv, RegionPtr clipBoxes, int id);

static int ASTPutImage(ScrnInfoPtr pScrn,
                          short src_x, short src_y,
                          short drw_x, short drw_y,
                          short src_w, short src_h,
                          short drw_w, short drw_h,
                          int id, unsigned char* buf,
                          short width, short height,
                          Bool sync,
                          RegionPtr clipBoxes, pointer data
)
{	
    ASTPtr pAST = ASTPTR(pScrn);
    ASTPortPrivPtr pPriv = (ASTPortPrivPtr)data;
    int i;
    int totalSize=0;

    xf86DrvMsg(pScrn->scrnIndex, X_INFO,"ASTPutImage()\n");
    /*   int depth = pAST->CurrentLayout.bitsPerPixel >> 3; */
    
    pPriv->drw_x = drw_x;
    pPriv->drw_y = drw_y;
    pPriv->drw_w = drw_w;
    pPriv->drw_h = drw_h;
    pPriv->src_x = src_x;
    pPriv->src_y = src_y;
    pPriv->src_w = src_w;
    pPriv->src_h = src_h;
    pPriv->id = id;
    pPriv->height = height;
    
    switch(id)
    {
    case PIXEL_FMT_YV12:
    case PIXEL_FMT_NV12:
    case PIXEL_FMT_NV21:
        pPriv->srcPitch = (width + 7) & ~7;
        totalSize = (pPriv->srcPitch * height * 3) >> 1; /* Verified */
    break;
    case PIXEL_FMT_YUY2:
    case PIXEL_FMT_UYVY:
    case PIXEL_FMT_YVYU:
    case PIXEL_FMT_RGB6:
    case PIXEL_FMT_RGB5:
    default:
        pPriv->srcPitch = ((width << 1) + 3) & ~3;	/* Verified */
        totalSize = pPriv->srcPitch * height;
    }
    
    totalSize += 15;
    totalSize &= ~15;
    /* allocate memory */
    
    if(totalSize == pPriv->fbSize)
    {
        ;    
    }    
    else
    {
        int lines, pitch, depth;   
        BoxPtr pBox = NULL;
        
        pPriv->fbSize = totalSize;
        
        if(pPriv->fbAreaPtr) 
        {
             xf86FreeOffscreenArea(pPriv->fbAreaPtr);
        }
        
        depth = (pScrn->bitsPerPixel + 7 ) / 8;
        pitch = pScrn->displayWidth * depth;
        lines = ((totalSize * 2) / pitch) + 1;
        xf86DrvMsg(pScrn->scrnIndex, X_INFO,"ASTPutImagelines=%x, pitch=%x, displayWidth=%x\n", lines, pitch, pScrn->displayWidth);
        
              
        pPriv->fbAreaPtr = xf86AllocateOffscreenArea(pScrn->pScreen, 
                                 pScrn->displayWidth,
                                lines, 0, NULL, NULL, NULL);
        
        if(!pPriv->fbAreaPtr) 
        {
            xf86DrvMsg(pScrn->scrnIndex, X_ERROR, "Allocate video memory fails\n");
            return BadAlloc;
        }
        
        pBox = &(pPriv->fbAreaPtr->box);     
        pPriv->bufAddr[0] = (pBox->y1 * pitch) + (pBox->x1 * depth); 
        pPriv->bufAddr[1] = pPriv->bufAddr[0] + totalSize;
        xf86DrvMsg(pScrn->scrnIndex, X_INFO, "Put Image, pPriv->bufAddr[0]=0x%08X\n", pPriv->bufAddr[0]);
            
    }
    
    /* copy data */
    if(totalSize < 16) 
    {
      #ifdef NewPath
        memcpy(pAST->FBVirtualAddr + pPriv->bufAddr[pPriv->currentBuf], buf, totalSize);
      #else /* NewPath */
        switch(id)
        {
        case PIXEL_FMT_YUY2:
        case PIXEL_FMT_UYVY:
        case PIXEL_FMT_YVYU:
        {			   
             BYTE *Base = (BYTE *)(pAST->FBVirtualAddr + pPriv->bufAddr[pPriv->currentBuf]);
             for(i=0; i<height; i++)
                  memcpy( Base + i * pPriv->srcPitch, buf + i*width*2, width*2);
             break;
        }   
        default:
            memcpy(pAST->FBVirtualAddr + pPriv->bufAddr[pPriv->currentBuf], buf, totalSize);
            break;
        } /* switch */
      #endif /* NewPath */
    } 
    else
    {
        xf86DrvMsg(pScrn->scrnIndex, X_INFO, "Put Image, copy buf\n");
    
      #ifdef NewPath
       	memcpy(pAST->FBVirtualAddr + pPriv->bufAddr[pPriv->currentBuf], buf, totalSize);
      #else     /* NewPath */
        switch(id)
        {
        case PIXEL_FMT_YUY2:
        case PIXEL_FMT_UYVY:
        case PIXEL_FMT_YVYU:
        {
            BYTE *Base = (BYTE *)(pAST->FBVirtualAddr + pPriv->bufAddr[pPriv->currentBuf]);
            for(i=0; i<height; i++)
                  memcpy( Base + i * pPriv->srcPitch, buf + i*width*2, width*2);
            
            /*for(i=0; i<height; i++)
                for(j=0; j<width*2; j++)
                    *(Base+i*pPriv->srcPitch+j) = *(buf + width*i + j);*/
            break;
        }
        default:
        {    BYTE *Base = (BYTE *)(pAST->FBVirtualAddr + pPriv->bufAddr[pPriv->currentBuf]);
            int j;
            for(i=0; i<height; i++)
                for(j=0; j<width; j++)
                   *(Base + width*i + j) = *(buf + width * i + j);
        break;
        }
        } /* end of switch */
      #endif    /* NewPath */
    }
    
    ASTDisplayVideo(pScrn, pPriv, clipBoxes, id);
    
    /* update cliplist 
    if(!REGION_EQUAL(pScrn->pScreen, &pPriv->clip, clipBoxes)) 
    {      
        REGION_COPY(pScrn->pScreen, &pPriv->clip, clipBoxes);
    }
    else 
    {
        xf86XVFillKeyHelper(pScrn->pScreen, 0xFFFFFFFF, clipBoxes);
    }
    */
    pPriv->currentBuf ^= 1;
    
    return Success;
}

static XF86VideoAdaptorPtr ASTSetupImageVideo(ScreenPtr pScreen)
{
    ScrnInfoPtr pScrn = xf86Screens[pScreen->myNum];
    ASTPtr pAST = ASTPTR(pScrn);
    XF86VideoAdaptorPtr adapt;
    ASTPortPrivPtr pPriv;
  

    if(!(adapt = xcalloc(1, sizeof(XF86VideoAdaptorRec) +
                            sizeof(DevUnion) + 
                            sizeof(ASTPortPrivRec))))
        return NULL;

    adapt->type = XvWindowMask | XvInputMask | XvImageMask | XvVideoMask;
    adapt->flags = VIDEO_OVERLAID_IMAGES | VIDEO_CLIP_TO_VIEWPORT;
    adapt->name = "AST Video";

    adapt->nEncodings = 1;
    adapt->pEncodings = &DummyEncoding;
  
    adapt->nFormats = NUM_FORMATS;
    adapt->pFormats = ASTFormats;
    adapt->nPorts = 1;
    adapt->pPortPrivates = (DevUnion*)(&adapt[1]);

    pPriv = (ASTPortPrivPtr)(&adapt->pPortPrivates[1]);

    adapt->pPortPrivates->ptr = (pointer)(pPriv);
    adapt->pAttributes = ASTAttributes;
    adapt->nAttributes = NUM_ATTRIBUTES;
	adapt->nImages = NUM_IMAGES;
    adapt->pImages = ASTImages;

    adapt->PutVideo = NULL;
  
    adapt->PutStill = NULL;
    adapt->GetVideo = NULL;
    adapt->GetStill = NULL;
    adapt->StopVideo = ASTStopVideo;
    adapt->SetPortAttribute = ASTSetPortAttribute;
    adapt->GetPortAttribute = ASTGetPortAttribute;
    adapt->QueryBestSize = ASTQueryBestSize;
    adapt->PutImage = ASTPutImage;
    adapt->QueryImageAttributes = ASTQueryImageAttributes;


    pPriv->currentBuf   = 0;
    pPriv->linear       = NULL;
    pPriv->fbAreaPtr    = NULL;
    pPriv->fbSize = 0;
	pPriv->videoStatus  = 0;

    pPriv->colorKey     = 0x000101fe;
    pPriv->brightness   = 0;
    pPriv->contrast     = 128;
    pPriv->saturation   = 0;
    pPriv->hue          = 0;

    /* gotta uninit this someplace */
#if defined(REGION_NULL)
    REGION_NULL(pScreen, &pPriv->clip);
#else
    REGION_INIT(pScreen, &pPriv->clip, NullBox, 0);
#endif

	pAST->adaptor = adapt;
	
	pAST->xvBrightness = MAKE_ATOM(astxvbrightness);
	pAST->xvContrast   = MAKE_ATOM(astxvcontrast);
	pAST->xvColorKey   = MAKE_ATOM(astxvcolorkey);
	pAST->xvSaturation = MAKE_ATOM(astxvsaturation);
	pAST->xvHue 	   = MAKE_ATOM(astxvhue);
	pAST->xvGammaRed   = MAKE_ATOM(astxvgammared);
    pAST->xvGammaGreen = MAKE_ATOM(astxvgammagreen);
    pAST->xvGammaBlue  = MAKE_ATOM(astxvgammablue);
    
    return adapt;
}

void ASTInitVideo(ScreenPtr pScreen)
{
    ScrnInfoPtr pScrn = xf86Screens[pScreen->myNum];
    XF86VideoAdaptorPtr *adaptors, *newAdaptors = NULL;
    XF86VideoAdaptorPtr ASTAdaptor = NULL;
    int num_adaptors;

    ASTAdaptor = ASTSetupImageVideo(pScreen);
    
    num_adaptors = xf86XVListGenericAdaptors(pScrn, &adaptors);

    if(ASTAdaptor) 
    {
        if(!num_adaptors) 
        {
            num_adaptors = 1;
            adaptors = &ASTAdaptor;
        }
        else 
        {
            newAdaptors = xalloc((num_adaptors + 1) * sizeof(XF86VideoAdaptorPtr*));
            if(newAdaptors) 
            {
                memcpy(newAdaptors, adaptors, num_adaptors *
                                        sizeof(XF86VideoAdaptorPtr));
                newAdaptors[num_adaptors] = ASTAdaptor;
                adaptors = newAdaptors;
                num_adaptors++;
            }
        }
    }

    if(num_adaptors)
        xf86XVScreenInit(pScreen, adaptors, num_adaptors);

    if(newAdaptors)
        xfree(newAdaptors);

}
#endif /* AstVideo */