File: minihwc.c

package info (click to toggle)
glide 2002.04.10ds1-16
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 59,540 kB
  • sloc: ansic: 290,125; asm: 23,305; sh: 8,089; pascal: 3,854; makefile: 1,276; perl: 73
file content (7316 lines) | stat: -rw-r--r-- 242,533 bytes parent folder | download | duplicates (8)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
/*
** THIS SOFTWARE IS SUBJECT TO COPYRIGHT PROTECTION AND IS OFFERED ONLY
** PURSUANT TO THE 3DFX GLIDE GENERAL PUBLIC LICENSE. THERE IS NO RIGHT
** TO USE THE GLIDE TRADEMARK WITHOUT PRIOR WRITTEN PERMISSION OF 3DFX
** INTERACTIVE, INC. A COPY OF THIS LICENSE MAY BE OBTAINED FROM THE 
** DISTRIBUTOR OR BY CONTACTING 3DFX INTERACTIVE INC(info@3dfx.com). 
** THIS PROGRAM IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER 
** EXPRESSED OR IMPLIED. SEE THE 3DFX GLIDE GENERAL PUBLIC LICENSE FOR A
** FULL TEXT OF THE NON-WARRANTY PROVISIONS.  
** 
** USE, DUPLICATION OR DISCLOSURE BY THE GOVERNMENT IS SUBJECT TO
** RESTRICTIONS AS SET FORTH IN SUBDIVISION (C)(1)(II) OF THE RIGHTS IN
** TECHNICAL DATA AND COMPUTER SOFTWARE CLAUSE AT DFARS 252.227-7013,
** AND/OR IN SIMILAR OR SUCCESSOR CLAUSES IN THE FAR, DOD OR NASA FAR
** SUPPLEMENT. UNPUBLISHED RIGHTS RESERVED UNDER THE COPYRIGHT LAWS OF
** THE UNITED STATES.  
** 
** COPYRIGHT 3DFX INTERACTIVE, INC. 1999, ALL RIGHTS RESERVED
**
** $Header: /cvsroot/glide/glide3x/h5/minihwc/minihwc.c,v 1.4 2000/11/16 19:26:03 joseph Exp $
** $Log: 
**  92   3dfx      1.71.1.6.1.4.1.711/08/00 Drew McMinn     Added
**       FX_GLIDE_BRIGHTNESS and FX_GLIDE_CONTRAST modifiers
**  91   3dfx      1.71.1.6.1.4.1.610/11/00 Brent           Forced check in to
**       enforce branching.
**  90   3dfx      1.71.1.6.1.4.1.509/15/00 troy thornton   added code to allow
**       grquerryresolutions to check the refresh rate of the monitor before
**       returning a valid screen mode
**  89   3dfx      1.71.1.6.1.4.1.408/29/00 Jonny Cochrane  Some 8x FSAA code
**  88   3dfx      1.71.1.6.1.4.1.308/07/00 Andy Hanson     Fixed up lfb cfg
**       registers.  Variable bpp was being used without being properly
**       initialized.  Cleaned up source, and put some safety strncpy's for
**       errorString.  Sprintf's are still unsafe.
**  87   3dfx      1.71.1.6.1.4.1.207/21/00 Adam Briggs     ack: the display driver
**       is always returning 1 for the AGPINFO escape whether or not an AGP fifo
**       exists... make sure we use a memory fifo if the agp fifo is zero bytes
**       long
**  86   3dfx      1.71.1.6.1.4.1.107/06/00 Adam Briggs     fixed Ken's AA
**       screenshot function for 32bit & 2-sample AA
**  85   3dfx      1.71.1.6.1.4.1.006/22/00 troy thornton   added
**       FX_GLIDE_USE_APP_GAMMA env. var.
**  84   3dfx      1.71.1.6.1.406/20/00 Joseph Kain     Fixed errors introduced by
**       my previous merge.
**  83   3dfx      1.71.1.6.1.306/20/00 Joseph Kain     Changes to support the
**       Napalm Glide open source release.  Changes include cleaned up offensive
**       comments and new legal headers.
**  82   3dfx      1.71.1.6.1.206/16/00 Adam Briggs     win2k & winnt unmap the
**       board when we release the windowed mode context
**  81   3dfx      1.71.1.6.1.106/07/00 Adam Briggs     allowed NT4 to run in
**       multichip mode
**  80   3dfx      1.71.1.6.1.005/24/00 Kenneth Dyke    Updated MacOS screenshot
**       SLI/AA handling.
**  79   3dfx      1.71.1.6    05/23/00 Adam Briggs     Added multichip support for
**       win2k
**  78   3dfx      1.71.1.5    05/23/00 Kenneth Dyke    Added some MacOS related
**       fixes.
**  77   3dfx      1.71.1.4    05/18/00 Adam Briggs     Changed win9x VDD name to
**       h5vdd.
**  76   3dfx      1.71.1.3    05/12/00 Stephane Huaulme made Mac compile happy by
**       keeping local storage under 32K
**  75   3dfx      1.71.1.2    05/11/00 Stephane Huaulme fixed a few Macintosh bugs
**  74   3dfx      1.71.1.1    05/09/00 Kenneth Dyke    Added code to calculate
**       chip values on Napalm.
**  73   3dfx      1.71.1.0    05/02/00 Kenneth Dyke    Fixed a really effing
**       stupid typo that broke FSAA screenshots. :(
**  72   3dfx      1.71        04/25/00 Kenneth Dyke    Made FX_GLIDE_NO_HW a lot
**       more robust.
**  71   3dfx      1.70        04/21/00 Kenneth Dyke    FX_GLIDE_NO_HW support.
**  70   3dfx      1.69        04/16/00 Kenneth Dyke    Force some configuration
**       parameters on 4-way boards.
**  69   3dfx      1.68        04/13/00 Kenneth Dyke    Added support for new-style
**       two-sample AA.
**  68   3dfx      1.67        04/10/00 Kenneth Dyke    Added code to take
**       full-precision screenshots.
**  67   3dfx      1.66        04/03/00 Kenneth Dyke    Refined startup & shutdown
**       hardware idle.
**  66   3dfx      1.65        03/30/00 Kenneth Dyke    Even better fifo init code
**       to guard against hangs.
**  65   3dfx      1.64        03/29/00 Adam Briggs     i got in before ken.
**  64   3dfx      1.63        03/28/00 Kenneth Dyke    More paranoia for fifo init
**       code.
**  63   3dfx      1.62        03/27/00 Kenneth Dyke    DOS Glide support for
**       two-chip (and maybe four-chip) Napalm boards.
**  62   3dfx      1.61        03/26/00 Adam Briggs     added code to divine the
**       proper registry path for win2k hwcGetEnv
**  61   3dfx      1.60        03/24/00 Kenneth Dyke    Improved Napalm DOS Glide
**       support.
**       Reset FBI & 2D when Glide starts up.
**  60   3dfx      1.59        03/21/00 Kenneth Dyke    Lots of video backend fixes
**       for SLI/AA/32-bit.
**  59   3dfx      1.58        03/15/00 Kenneth Dyke    Don't let the user do
**       something dumb. ;)
**  58   3dfx      1.57        03/14/00 Adam Briggs     let glide decide when to
**       use analog sli
**  57   3dfx      1.56        03/13/00 Kenneth Dyke    Removed A0 read abort
**       workaround.
**  56   3dfx      1.55        03/08/00 Kenneth Dyke    Keep track of whether or
**       not a board is "mapped" or not.
**  55   3dfx      1.54        03/07/00 Don Mullis      Generalize glide3 to handle
**       sub-byte-size texels.
** 
**  54   3dfx      1.53        03/07/00 Adam Briggs     make sure that we don't
**       request a bogus sli mode from the minivdd
**  53   3dfx      1.52        03/07/00 Kenneth Dyke    Fixed Win32 build breakage.
** 
**  52   3dfx      1.51        03/07/00 Stephane Huaulme implemented read and write
**       config reg (using hrm) for Macintosh
**  51   3dfx      1.50        03/07/00 Adam Briggs     fail tiled fifos in
**       windowed mode fifo alloc
**  50   3dfx      1.49        03/07/00 Kenneth Dyke    Do NT check earlier.  Force
**       number of chips to 1 for NT for now.
**  49   3dfx      1.48        03/03/00 Kenneth Dyke    Make sure code doesn't barf
**       for non-Napalm build.
**  48   3dfx      1.47        03/03/00 Kenneth Dyke    Fixed physical -> LFB
**       address calculation once and for all (I hope).  Added code to support SLI
**       read abort workaround.
**  47   3dfx      1.46        03/01/00 Kenneth Dyke    A bunch of fixes for AA LFB
**       accesses (and 32-bit LFB accesses).
** 
**  46   3dfx      1.45        02/29/00 Adam Briggs     ripped out all of the
**       half-baked Ext2 stuff
**  45   3dfx      1.44        02/28/00 Kenneth Dyke    Fixed Napalm FIFO sizing.
**  44   3dfx      1.43        02/24/00 Larry  warner   Don't turn off FIFO in
**       hwcRestoreVideo.  See Ken Dyke for details.
**  43   3dfx      1.42        02/22/00 Kenneth Dyke    Make sure we don't try to
**       enable AA mode on single-chip boards if the user doesn't actually ask for
**       AA.
**  42   3dfx      1.41        02/15/00 Kenneth Dyke    Fixed some incorrect
**       information passed to the minivdd.  Also fixed some MacOS build breakage.
**  41   3dfx      1.40        02/14/00 Kenneth Dyke    Make sure that we calculate
**       the right number of tiles we need when in SLI mode.  Get SLI band height
**       info from Glide rather than checking env var directly.
**  40   3dfx      1.39        02/14/00 Kenneth Dyke    Fix stupid typo.
**  39   3dfx      1.38        02/14/00 Kenneth Dyke    Added support for setting
**       number of chips via FX_GLIDE_NUM_CHIPS.  Also added temporary hack to set
**       PCI fifo threshold value.
**  38   3dfx      1.37        02/08/00 Kenneth Dyke    Further AA code cleanup. 
**       Disable overlay filter in SLI mode.
**  37   3dfx      1.36        02/07/00 Kenneth Dyke    MacOS & PC fixes for
**       multi-chip anti-aliasing.
**  36   3dfx      1.35        02/01/00 Kenneth Dyke    Change in HRM board info
**       struct.
**  35   3dfx      1.34        01/31/00 Adam Briggs     changed the IS_NAPALM macro
**       to cooperate with the display driver version of the same
**  34   3dfx      1.33        01/31/00 Kenneth Dyke    Add in 2 spample AA support
**       for MacOS.
**  33   3dfx      1.32        01/31/00 Adam Briggs     Changed all device ID magic
**       numbers to use those defined in fxhal.h & added IS_NAPALM macro to test
**       against device ID range
**  32   3dfx      1.31        01/28/00 Kenneth Dyke    Removed accidental extra
**       #endif after merge.
**  31   3dfx      1.30        01/28/00 Kenneth Dyke    Update MacOS minihwc code
**       for new HRM protocol.
** 
**  30   3dfx      1.29        01/24/00 Adam Briggs     only query for slave regs
**       when slave chips are present
**  29   3dfx      1.28        01/23/00 Adam Briggs     use the minivdd correctly
**       and 4 sample AA suddenly works
**  28   3dfx      1.27        01/22/00 Adam Briggs     made the build process stop
**       whining
**  27   3dfx      1.26        01/21/00 Adam Briggs     get the correct linear
**       mappings of slave regs
**  26   3dfx      1.25        01/19/00 Kenneth Dyke    Do proper Napalm fifo
**       padding.
**  25   3dfx      1.24        01/19/00 Adam Briggs     for some strange reason,
**       display driver escapes don't seem to work in DOS.
**  24   3dfx      1.23        01/19/00 Adam Briggs     Made minihwc use either
**       EXT_HWC or EXT_HWC_OLD depending on which one the display driver supports
**       so that a new glide can try to run on an old display driver.
**  23   3dfx      1.22        01/18/00 Kenneth Dyke    Fixed more issues with AA
**       buffers and chip configuration.
**  22   3dfx      1.21        01/16/00 Kenneth Dyke    Use new & improved register
**       bit names.
**  21   3dfx      1.20        01/16/00 Kenneth Dyke    Major fixes for 32-bit and
**       AA modes.  
**       Fix to disable FIFO when Glide shuts down.
**       Added code to temporarily move Napalm FIFO out of evil VGA space.
**  20   3dfx      1.19        01/05/00 Larry  warner   Use GetCurrentProcessId()
**       rather than GetCurrentProcess().
**  19   3dfx      1.18        01/03/00 Adam Briggs     added hwcGetGammaTable
**       function to allow OpenGL to later restore the original Gamma ramp.
**  18   3dfx      1.17        12/10/99 Leo Galway      Removed previous hi-res
**       mode information for Glide3. These modes were only necessary for
**       Cornerstone (or future hi-res) support in RT4.2 source branch and
**       proceeded to break the V3 and V2 builds (from 3dfx view), hence they have
**       been removed.
**  17   3dfx      1.16        12/09/99 Leo Galway      Added mode information for
**       1600x1280, 1792x1440, 1920x1080, 1920x1200, 2046x1536 (as a result of
**       glide3 being tested with Cornerstone modes). Although not all of these
**       modes are capable under Glide3, their inclusion prevents Glide3 test apps
**       from being displayed incorrectly in theses hi-res modes. 
**       Search for SUSTAINED_ENGINEERING_CHANGE_BEGIN. 
**  16   3dfx      1.15        11/30/99 Kenneth Dyke    Silently fail if HRM
**       version is not correct.
**  15   3dfx      1.14        11/29/99 Kenneth Dyke    Fixed DOS build breakage.
**  14   3dfx      1.13        11/23/99 Stephane Huaulme version conflict safety
**       net
**  13   3dfx      1.12        11/22/99 Kenneth Dyke    Added hwcIdleWinFifo().
**  12   3dfx      1.11        11/22/99 Adam Briggs     Merged revs 9 & 10 back in.
**        Also protected HMONITOR from being redefined.
**  11   3dfx      1.10        11/12/99 Don Mullis      Fix additional bugs found
**       by source code inspection.  
** 
**       Verified that PRS# 11145 & 10978  remain fixed.
** 
** 
**  10   3dfx      1.9         11/11/99 Michelle Tsui   set sfcEnd properly.
**  9    3dfx      1.8         11/09/99 Adam Briggs     Added support for getting
**       slave chip MMIO pointers from hwcMapBoard and hwcInitRegisters
**  8    3dfx      1.7         10/27/99 Anthony tai     initialize h3pixelSize for
**       DOS
**  7    3dfx      1.6         10/13/99 Anthony tai     back to the oem style unmap
**       memory to make wnt/w2k driver happy
**  6    3dfx      1.5         10/08/99 Anthony tai     fixed getenv with all caps
**  5    3dfx      1.4         10/08/99 Anthony tai     set v3 fifo to low address
**       by default to exercise napalm fifo space. to disable low address fifo, set
**       FX_GLIDE_V3FIFO=1
**  4    3dfx      1.3         10/08/99 Anthony tai     added env vars
**       "FX_GLIDE_DEVICEID"
**  3    3dfx      1.2         10/04/99 Matt McClure    Ported Glide Context
**       Switching code from V3_OEM_100.
**  2    3dfx      1.1         09/13/99 Anthony tai     check chip number
**  1    3dfx      1.0         09/11/99 StarTeam VTS Administrator 
** $
** 
** 175   9/09/99 6:42p Atai
** fixed 32bpp window app
** 
** 174   9/03/99 4:33p Atai
** reset aa/sli pci registers
** 
** 173   9/01/99 2:47p Atai
** for windows only
** 
** 172   8/31/99 5:10p Atai
** program cfgAALfbCtrl
** 
** 171   8/23/99 3:12p Kcd
** Lots of new MacOS 8 stuff.
** 
** 170   8/18/99 8:23p Adamb
** Put Anthony's multichip code back in--Still needs to be updated for
** evolving Ext2 interface, though.
** 
** 169   8/18/99 9:57a Sbrooks
** Fixed erroneous deletion.
** 
** 164   8/04/99 3:35p Atai
** 32 bpp happy
** 
** 163   7/19/99 2:51p Atai
** added variable for sli
** 
** 162   7/16/99 5:08p Sbrooks
** Fixes PRS 6869
** 
** 161   7/02/99 3:41p Kcd
** MacOS HRM mods.
** 
** 160   6/22/99 4:56p Sbrooks
** Now checks for ShareContextDWORD failure.  Was only checking for
** protocol failure.
** 
** 159   6/21/99 7:29p Kcd
** More MacOS work.
** 
** 158   6/21/99 1:25p Atai
** modify for h3pixelSize
** place fifo at 0x0 for Naplam
** 
** 157   6/17/99 4:23p Atai
** remove compiler errors and warnings for dos build
** 
** 156   6/17/99 3:15p Stb_sbrooks
** Fixes PRS 6682
** 
** 155   6/14/99 4:28p Atai
** more on 2nd buffer allocation
** 
** 154   6/14/99 3:17p Atai
** added secondary buffer info
** 
** 153   6/11/99 4:02p Stb_sbrooks
** 
** 151   6/07/99 3:10p Atai
** report as Banshee if it is an 8M board
** 
** 150   6/04/99 11:14a Kcd
** Disable surface stuff when not building for Glide3 on MacOS.
** 
** 149   6/02/99 2:48p Atai
** set min texture size to 0x200000 if FX_GLIDE_TMU_MEMSIZE=1
** 
** 148   5/28/99 11:49a Dow
** tm1/fifo page overlap fix.  Modified by Dow.  Checked in by Brooks.
** 
** 147   5/27/99 11:04a Dow
** Removed FIFO disable at end.
** 
** 146   5/26/99 5:51p Kcd
** MacOS fix for alt-TAB context stuff.
** 
** 145   5/13/99 2:28p Stb_gkincade
** Added user support for switching the video filter from 2x2 to 4x1
** 
** 144   5/06/99 6:37p Dow
** Fix for no alt-tab in driver
** 
** 143   4/25/99 1:04p Atai
** don't call HWCEXT_RELEASECONTEXT when glide release context in NT. The
** driver will restore vidProcCfg and it corrupt alt-entering full screen
** dos mode.
** 
** 142   4/23/99 5:10p Atai
** nt driver returned lostcontext address, not offset
** 
** 141   4/22/99 4:29p Dow
** Alt-Tab on NT
** 
** 140   4/20/99 10:55a Atai
** protect the dos build
** 
** 139   4/16/99 2:41p Kcd
** Mac fixes.
** 
** 138   4/15/99 5:32p Dow
** Alt TAb for NT + palette fix
** 
** 137   4/09/99 4:22p Dow
** Sandbox issues
** 
** 136   4/08/99 6:15p Atai
** added env var FX_GLIDE_REFRESH
** 
** 135   4/05/99 8:24p Dow
** Alt tab happiness--sorta
** 
** 134   4/05/99 10:38a Atai
** protect window only code
** 
** 133   4/04/99 7:13p Atai
** added cast
** 
** 132   4/04/99 7:14p Sreid
** Plumbing for gc->lostcontext flag
** 
** 129   4/01/99 7:52p Peter
** (temp?) fix for query context extescape return value
** 
** 128   4/01/99 10:30a Peter
** check status enum not boolean
** 
** 127   4/01/99 10:08a Peter
** forgot to protect extEscape, doh!
** 
** 126   3/31/99 9:01p Dow
** context check w/ driver
** 
** 125   3/25/99 2:30p Peter
** surface fifo allocation w/ desktop widths < 1024
** 
** 124   3/24/99 10:19a Peter
** required lockabilly
** 
** 123   3/23/99 6:48p Atai
** use max fifo size if 16M board
** 
** 122   3/17/99 3:46p Dow
** Luke Skywalker
** 
** 121   3/11/99 8:37p Peter
** update vidOverlayEndScreenCoord when the overlay dims != screen dims
** (w/ optional scaling)
** 
** 120   3/10/99 11:52a Peter
** initFifo enable hole counting parameter
** 
** 119   3/09/99 12:31p Kcd
** Added MacOS stuff.  Fixed refresh constant table (mis)use.
** 
** 118   3/05/99 10:06p Peter
** allocate independent state buffers in parallel w/ the command buffers
** 
** 117   3/03/99 3:52p Peter
** removed hemorrhaging GetDC and create glide private dc's for ExtEscape
** 
** 116   3/02/99 8:03p Dow
** 
** 115   2/27/99 12:24p Dow
** New resolutions
** 
** 114   2/22/99 5:06p Peter
** cleaned up monitor enum crap
** 
** 113   2/19/99 2:00p Atai
** fixed lfbBuffAddr for 800x600 triple buffering lfb access
** 
** 112   2/17/99 2:36p Peter
** removed extra dd call, fail agp fifo if no dd agp support, release
** window dc after enum
** 
** 111   2/13/99 1:57p Dow
** Added code for new resolutions
** 
** 110   2/08/99 6:42p Atai
** use the active window display as sst 0
** 
** 109   2/02/99 4:37p Peter
** hwGetSurfaceinfo gets depth, releasing memory fifo creation dd object
** 
** 108   1/25/99 6:37p Peter
** removed redundant macros
** 
** 107   1/22/99 4:28p Dow
** Fixed 1600x1200 the right way.
** 
** 106   1/22/99 3:02p Dow
** Turned off 2x2 filtering in 2x mode
** 
** 105   1/21/99 1:43p Dow
** Fencing for Pallette Download
** 
** 104   1/20/99 6:04p Peter
** cleaned up warning
** 
** 103   1/20/99 1:51p Dow
** Pithy workaround for PCI gamma problem
** 
** 102   1/14/99 11:38a Dow
** Left bits alone in vidproccfg
** 
** 101   1/11/99 8:22p Peter
** fixed stride vs width effage that I somehow convinced myself was right
** 
** 100   1/11/99 6:31p Dow
** Added Debugging
** 
** 99    1/04/99 11:58a Peter
** added windowed context support
** 
** 98    12/23/98 12:39p Peter
** hdc cleanup/hwcext_getlinearaddr is not idempotent
** 
** 97    12/22/98 5:43p Atai
** turn on 2x mode for vidProcCfg if greater than or equal to 1280
** 
** 96    12/22/98 3:29p Jeske
** use h3InitGetMemSize() instead so that we don't have to worry about it
** screwing up dramInit1 like h3InitSgram() did in the past...
** 
** 95    12/22/98 2:46p Atai
** fixed for Banshee/DOS draminit1 value
** 
** 94    12/22/98 1:07p Peter
** all dd surface pointers must go through linear map offset to get their
** hw relative offsets
** 
** 93    12/17/98 2:08p Jeske
** comment fix
** 
** 92    12/16/98 7:13p Peter
** query directdraw object for surface memory area caps and set the
** process id when getting the linear addresses via
** 
** 91    12/11/98 1:35p Peter
** window fifo serial # vs pixel cache
** 
** 90    12/09/98 5:17p Dow
** Fixed video scaling for lame resolutions
** 
** 89    12/07/98 2:18p Dow
** Added debug message for process handle
** 
** 88    12/07/98 11:32a Dow
** Fixed 2X resolutions
** 
** 87    12/06/98 11:04a Dow
** 
** 86    12/04/98 8:42a Dow
** Fixed broken DOS build AGAIN
** 
** 85    12/03/98 10:27p Dow
** Added stuff for hwcGetenv
** 
** 84    12/03/98 9:11p Dow
** Fixed resolution check
** 
** 83    12/02/98 9:35p Dow
** Query Resolutions
** 
** 82    12/02/98 2:41p Jeske
** ugh... text badness
** 
** 81    12/02/98 2:38p Jeske
** don't set the clocks unless they use the environment variable
** overrides, even for banshee...
** 
** 80    12/02/98 2:06p Dow
** Gamma Fully Implemented
** 
** 79    11/30/98 6:53p Peter
** video memory fifo's
** 
** 78    11/24/98 12:25p Mikec
** made multi-mon on win95 happy
** 
** 77    11/24/98 9:43a Atai
** detect multiple cards
** 
** 76    11/23/98 3:28p Atai
** fixed the refresh rate stuff
** 
** 75    11/20/98 4:48p Jeske
** avenger-dos, for now, make sure we don't call h3InitPlls() on avenger..
** 
** 74    11/19/98 1:51p Dow
** Fixed refresh/resolution issue
** 
** 73    11/18/98 8:04p Dow
** grxclk
** 
** 72    11/15/98 2:16a Atai
** set device id = 5. Hack for comdex
** 
** 71    11/10/98 6:29p Atai
** added min_tramSize for board information. min_tramSize = 0x200000 if
** device id is 3 or mem size is 4
** 
** 70    10/30/98 3:44p Dow
** Fixed Tiled/Linear color/aux bug
** 
** 69    10/29/98 5:15p Dow
** Fixed 512x384
** 
** 68    10/21/98 11:22a Peter
** dos happiness w/ the new chris pci library (nee tarolli)
** 
** 67    10/14/98 3:37p Dow
** Gamma stuff
** 
** 66    10/13/98 8:48p Dow
** Env Var for Board mem
** 
** 65    10/08/98 10:15a Dow
** Triple buffering fix
** 
** 64    9/18/98 3:08p Dow
** Fixed DOS build
** 
** 63    9/17/98 3:58p Dow
** Vidmode Stuff
** 
** 62    9/11/98 1:07p Peter
** rounding on raw lfb port addr
** 
** 61    9/02/98 1:34p Peter
** watcom warnings
** 
** 60    8/25/98 6:48p Dow
** Added scaling for low-res
** 
** 59    8/25/98 3:07p Dow
** Checked res of hwcRLSEXCLUSIVE
** 
** 58    8/06/98 7:49p Dow
** Moved detection of SDRAM
** 
** 57    8/02/98 5:00p Dow
** Glide Surface Extension
** 
** 56    7/29/98 3:34p Dow
** 
** 55    7/29/98 3:09p Dow
** SDRAM Fixes
** 
** 54    7/24/98 6:34p Dow
** Fixed DOS Build
** 
** 53    7/24/98 2:02p Dow
** AGP Stuff
** 
** 52    7/23/98 1:18a Dow
** Bump & Grind
** 
** 51    7/18/98 12:21a Jdt
** added state abuffer
** 
** 50    7/16/98 10:26p Dow
** GIW Stuff
** 
** 49    7/16/98 2:53p Dow
** Removed useless colBufferAddr frmo surface info
** 
** 48    7/15/98 4:09p Dow
** GIW Stuff & DOS Protection
** 
** 47    7/14/98 7:19p Dow
** protected some win32 stuff
** 
** 46    7/13/98 10:35p Jdt
** Implemented hwcAllocWinFifo, hwcExecuteWinFifo.
** 
** 45    7/08/98 5:45p Dow
** Moved fifo back up 
** 
** 44    7/02/98 12:11p Dow
** LFB fixes
** 
** 43    6/30/98 10:28a Dow
** Fixed fouled checkin
** 
** 41    6/25/98 6:45p Jdt
** Changes to remove the evil of dxdrvr.c
** 
** 40    6/25/98 12:16p Dow
** Added (protected) alternate FIFO layout
** 
** 39    6/16/98 6:11p Dow
** Rearranged texture memory
** 
** 38    6/16/98 9:49a Dow
** Fixed protected stuff
** 
** 37    6/16/98 9:35a Dow
** Comment -> GDBG_INFO conversion
** 
** 36    6/12/98 10:09a Jdt
** Fix broken dos build.
** 
** 35    6/11/98 7:44p Jdt
** Win98/NT5 Mulitmon 1st Pass
** 
** 34    6/10/98 9:49a Peter
** lfb buffer addressing
** 
** 33    6/09/98 10:09a Dow
** Init register performance tweaks.
** 
** 32    6/06/98 11:42a Dow
** Better buffer alignment for all resolutions.
** 
** 31    6/06/98 10:11a Dow
** Changed AUXPAD from 0 to 0x1000 to offset aux buffer.
** 
** 30    6/05/98 7:34p Dow
** Fixed 8x6-12x10 resolutions
** 
** 29    6/05/98 6:21p Jeske
** now everyone will dxClose(), not just windows
** 
** 28    6/05/98 6:37p Dow
** 1600x1200 perf tuning
** 
** 27    6/05/98 5:28p Jeske
** apparently we need to not call h3InitSetVideoMode() for this to work,
** will this work in non640x480 resolutions? we may need to fix that later
** 
** 26    6/05/98 3:27p Dow
** 1600x1200 Works
** 
** 25    6/04/98 9:36p Jeske
** now we leave VGA legacy decoding on in hwcInitRegisters so we can set
** video modes
** 
** 24    6/04/98 6:52p Dow
** Resolutions to 1600x1200
** 
** 23    6/03/98 1:52p Jeske
** added code to convert from Glide's ordinal refresh number to a refresh
** rate in Hz when calling h3InitSetVideoMode(). We really should specify 
** 
** 22    6/01/98 5:48p Jeske
** allow h3InitSetVideoMode to fail and handle it...
** 
** 21    5/31/98 9:02a Dow
** 800x600 Resolution
** 
** 20    5/28/98 6:34p Dow
** Fixed top scanline bug
** 
** 19    5/27/98 3:35p Mc
** Removed blocks of HW_IO_LOAD and HW_IO_STORE that chris put in.
** 
** 18    5/20/98 8:13p Dow
** device rev
** 
** 17    5/20/98 4:16p Dow
** Added env var for FIFO size
** 
** 16    5/15/98 2:46p Dow
** Attempt to patch back regs on NT
** 
** 15    5/13/98 4:26p Dow
** Protected obsolete IO code that was bodging NT
** 
** 14    4/27/98 2:30p Dow
** OpenProcess stuff
** 
** 13    4/22/98 5:29p Dow
** Added calls to HWCEXT_HWCSETEXCLUSIVE and HWCEXT_HWCRLSEXCLUSIVE
** 
** 12    4/16/98 10:14p Dow
** EXT_HWC is default init method
** 
** 11    4/13/98 5:49p Dow
** Turning theory into practice
** 
** 10    4/09/98 9:34p Dow
** synched with change in h3cinit
** 
** 9     4/08/98 12:25p Dow
** LfbMemoryConfig fix
** 
** 8     4/07/98 10:40p Dow
** LFB Fixes
** 
** 7     4/05/98 2:19p Dow
** DOS/WIN32 stepping on each others' dicks
** 
** 6     4/03/98 2:03p Dow
** DOS Glide modes
** 
** 5     3/28/98 10:51a Dow
** Fixes for FIFO bug
** 
** 4     3/20/98 1:11p Dow
** Now checking revision of chip
** 
** 3     3/20/98 11:43a Dow
** fifo placement for windows
** 
** 2     3/11/98 8:27p Dow
** WinGlide
** 
** 1     3/04/98 4:13p Dow
**
*/

#if !defined(GDBG_INFO_ON) || (GDBG_INFO_ON == 0)
#if defined(GDBG_INFO_ON)
#undef GDBG_INFO_ON
#endif /* defined(GDBG_INFO_ON) */
#define GDBG_INFO_ON
#endif /* !defined(GDBG_INFO_ON) || (GDBG_INFO_ON == 0) */

#include <stddef.h>
#include <stdlib.h>
#include <math.h>

#include <3dfx.h>

#ifdef HWC_EXT_INIT
#include "hwcext.h"
#else
#include <fxpci.h>
#endif

#if macintosh
#include <h3cinitdd_mac.h>
#endif
#include <h3cinit.h>
#include <minihwc.h>
#include "hwcio.h"
#include "setmode.h"

#ifdef __WIN32__
#define WIN32_LEAN_AND_MEAN
#include <windows.h>

#include <ddraw.h>
#include "qmodes.h"
#define IS_32
#define Not_VxD
#include <minivdd.h>
#include <vmm.h>
#include <configmg.h>

#endif

#ifdef macintosh
#include <GraphicsPrivHwc.h>
#include <hdwr_res_mgr.h>
#include <hrm_fifo.h>
#include <hrm_mode.h>
#include <hrm_mem.h>
#include <MacUtil.h>

#define GDX_SLIAA 1

static hrmGetTargetBoardInfoExtPtr _hrmGetTargetBoardInfo;

extern hrmGetVersionInfoPtr _hrmGetVersionInfo;
extern hrmSetExclusiveModePtr _hrmSetExclusiveMode;
extern hrmSetVideoModePtr _hrmSetVideoMode;
extern hrmReleaseExclusiveModePtr _hrmReleaseExclusiveMode;    
extern hrmAllocateBlockPtr _hrmAllocateBlock;
extern hrmFreeBlockPtr _hrmFreeBlock;
extern hrmAllocWinContextPtr _hrmAllocWinContext;
extern hrmFreeWinContextPtr _hrmFreeWinContext;
extern hrmExecuteWinFifoPtr _hrmExecuteWinFifo;
extern hrmGetDeviceConfigPtr _hrmGetDeviceConfig;
extern hrmGetAGPInfoPtr _hrmGetAGPInfo;
extern hrmWriteConfigRegisterPtr _hrmWriteConfigRegister;
extern hrmReadConfigRegisterPtr _hrmReadConfigRegister;
extern hrmGetSlaveRegsPtr _hrmGetSlaveRegs;
extern hrmSLIAAPtr _hrmSLIAA;

#if GLIDE3
#include <mac_sfc.h>
#endif
#endif

#define HWCEXT_PROTOCOL(mon) (hInfo.boardInfo[mon].hwcProtocol==-1)
#define HWCEXT_ESCAPE(mon) hInfo.boardInfo[mon].hwcEscape

/*
 * AJB HACK
 */
#define HWC_MINIVDD_HACK 1

#if defined(HWC_MINIVDD_HACK) && defined(HWC_EXT_INIT)
#define MINIVDDNAME "\\\\.\\H5VDD"
/*
 * This mess was snipped from win9x\dx\inc\h3g.h
 *
 * hence the '//' comments
 */

#define SLI_AA_ENABLE (6)
#define SLI_AA_DISABLE (7)

typedef struct dioc_data {
   DWORD dwDevNode;           // Device that we are interested in
   DWORD dwSpare;             // Spare DWORD currently used to pass IMASK
   } DIOC_DATA, * PDIOC_DATA;

typedef struct _sli_aa_chipinfo {
   DWORD dwChips;       // dwChips: Number of chips in multi-chip configuration (1-4)
   DWORD dwsliEn;       // dwsliEn: Sli is to be enabled (0,1)
   DWORD dwaaEn;        // dwaaEn: Anti-aliasing is to be enabled (0,1)
   DWORD dwaaSampleHigh;  // dwaaSampleHigh: 0->Enable 2-sample AA, 1->Enable 4-sample AA
   DWORD dwsliAaAnalog;   // dwsliAaAnalog: 0->Enable digital SLI/AA, 1->Enable analog Sli/AA
   DWORD dwsli_nlines;    // dwsli_nLines: Number of lines owned by each chip in SLI (2-128)
   DWORD dwCfgSwapAlgorithm; // Swap Buffer Algorithm
}  SLI_AA_CHIPINFO, * PSLI_AA_CHIPINFO;

typedef struct _sli_aa_meminfo {
   DWORD dwTotalMemory;       // In MB
   DWORD dwTileMark;          // In MB
   DWORD dwTileCmpMark;       // In MB
   DWORD dwaaSecondaryColorBufBegin;    // In MB
   DWORD dwaaSecondaryDepthBufBegin;    // In MB
   DWORD dwaaSecondaryDepthBufEnd;    // In MB
   DWORD dwBpp;                        // Bits Per Pixel
}  SLI_AA_MEMINFO, * PSLI_AA_MEMINFO; 

typedef struct sli_aa_request {
   SLI_AA_CHIPINFO ChipInfo;
   SLI_AA_MEMINFO MemInfo;
} SLI_AA_REQUEST, * PSLI_AA_REQUEST;
#endif

#ifdef GETENV
#undef GETENV
#endif

#define GETENV hwcGetenv

#define MAXFIFOSIZE        0x40000
#define MAXFIFOSIZE_16MB   0xff000

#define HWC_LFB_STRIDE     0x2000UL
#define HWC_RAW_LFB_STRIDE SST_RAW_LFB_ADDR_STRIDE_8K

       hwcInfo hInfo;

#define MAX_ERROR_SIZE 1024
static char errorString[MAX_ERROR_SIZE];
static FxU32 fenceVar;

FxU32 hwc_errncpy(char *dst,const char *src);

/* like strncpy, for the error string except it always null terminates */
FxU32 hwc_errncpy(char *dst,const char *src)
{
   FxU32 i,size=MAX_ERROR_SIZE;

   if (size==0)
      return 0;

   for(i=0;i<size;i++)
   {
      *dst++=*src++;
      if (src[-1]==0)
         return i;
   }
   dst[-1]=0;

   return (i-1);
}

#if defined(__WATCOMC__)
/*
 *  P6 Fence
 * 
 *  Here's the stuff to do P6 Fencing.  This is required for the
 *  certain things on the P6
 *
 * dpc - 21 may 1997 - FixMe!
 * This was yoinked from sst1/include/sst1init.h, and should be
 * merged back into something if we decide that we need it later.
 */
void 
p6Fence(void);
#pragma aux p6Fence = \
"xchg eax, fenceVar" \
modify [eax];


#define P6FENCE p6Fence()
#elif defined(__MSC__)
#define P6FENCE {_asm xchg eax, fenceVar}
#elif defined(__POWERPC__) && defined(__MWERKS__)
#define P6FENCE __sync()
#else
#error "P6 Fencing in-line assembler code needs to be added for this compiler"
#endif /* Compiler specific fence commands */

#if defined(HWC_EXT_INIT) || defined(HWC_GDX_INIT)
static FxU32
dummyContextDWORD;
#endif

static void
lostContext(void);

static FxU32
pow2Round(FxU32 val, FxU32 roundVal);

static FxU32
hwcBufferLfbAddr(const hwcBoardInfo *bInfo, FxU32 physAddress);

static FxU32
calcBufferSize(hwcBoardInfo* bInfo, FxU32 xres, FxU32 yres, FxBool tiled);  

static FxU32
calcBufferStride(hwcBoardInfo* bInfo, FxU32 xres, FxBool tiles);

static FxU32
calcBufferSizeInTiles(hwcBoardInfo* bInfo, FxU32 xres, FxU32 yres);

static FxU32
calcBufferHeightInTiles(hwcBoardInfo* bInfo, FxU32 yres);

static FxBool resolutionSupported[HWC_MAX_BOARDS][0x20][0x10];

/* 
** DOS-only stuff for multi-chip boards.
*/
extern void 
mapSlavePhysical(hwcBoardInfo *bInfo, FxU32 chipNum);

extern void
initSlave(hwcBoardInfo *bInfo, FxU32 chipNum);
        
/*
**  Function Prototypes
*/

static hwcBoardInfo *curBI = NULL;

#ifdef HWC_EXT_INIT

#ifndef HMONITOR_DECLARED // AJB- Make def compatible w/ vc6 headers
typedef void *HMONITOR;
#define HMONITOR_DECLARED
#endif
typedef BOOL (CALLBACK* MONITORENUMPROC)(HMONITOR, HDC, LPRECT, LPARAM);
typedef WINUSERAPI BOOL WINAPI
EnumDisplayMonitors_func( HDC             hdc,
                          LPCRECT         lprcClip,
                          MONITORENUMPROC lpfnEnum,
                          LPARAM          dwData);


typedef struct {
  HDC dc;
  HMONITOR mon;
} DevEnumRec;
static int num_monitor = 0;

static BOOL CALLBACK 
monitorEnum( HMONITOR handle, HDC dc, LPRECT rect, LPARAM param ) 
{
  BOOL rv = TRUE;
  hwcExtRequest_t ctxReq;
  hwcExtResult_t ctxRes;

  hInfo.boardInfo[num_monitor].hwcProtocol = -1;
  ctxReq.which = HWCEXT_GETDEVICECONFIG;
  GDBG_INFO(80, "monitorEnum:  ExtEscape:HWCEXT_GETDEVICECONFIG\n");

  /*
   * AJB- Figure out which escape code the display driver is using.
   *      This will allow yo-yos like me to use a new Glide DLL on
   *      an old (H3, for example) display driver.
   */
  if (ExtEscape(dc, EXT_HWC, sizeof(ctxReq), (LPSTR) &ctxReq, sizeof(ctxRes), (LPSTR) &ctxRes)) 
    HWCEXT_ESCAPE(num_monitor) = EXT_HWC ;
  else if (ExtEscape(dc, EXT_HWC_OLD, sizeof(ctxReq), (LPSTR) &ctxReq, sizeof(ctxRes), (LPSTR) &ctxRes)) 
    HWCEXT_ESCAPE(num_monitor) = EXT_HWC_OLD ;
  else
    HWCEXT_ESCAPE(num_monitor) = 0 ; /* if we don't have a display driver, we're hosed */
 
  if (HWCEXT_ESCAPE(num_monitor))
  { /**/
    FxI32 vendorID;
   
    vendorID = ctxRes.optData.deviceConfigRes.vendorID;

    if ( vendorID == 0x121a ) {
      DevEnumRec* 
        data = (DevEnumRec*)param;
      LPCSTR
        drvName = "DISPLAY",
        devName = NULL;

      /* If we're on a multi-mon capable system then we may have
       * different display type devices so we have to get the device
       * name explicitly for the CreateDC call.
       */
      if (handle != NULL) {
#define CCHDEVICENAME 32
        typedef struct {
          DWORD cbSize;
          RECT  rcMonitor;
          RECT  rcWork;
          DWORD dwFlags;
          TCHAR szDevice[CCHDEVICENAME];
        } MONITORINFOEX, *LPMONITORINFOEX;
        typedef BOOL (CALLBACK* GetMonitorInfoProc)(HMONITOR, LPMONITORINFOEX);
        static GetMonitorInfoProc monitorInfoProc = NULL;

        if (monitorInfoProc == NULL) {
          HMODULE user32 = GetModuleHandle("user32");

          if (user32 != NULL) {
            monitorInfoProc = (GetMonitorInfoProc)GetProcAddress(user32, "GetMonitorInfoA");
          }
        }

        if (monitorInfoProc != NULL) {
          MONITORINFOEX monInfo;

          monInfo.cbSize = sizeof(monInfo);
          if ((*monitorInfoProc)(handle, &monInfo)) {
            devName = monInfo.szDevice;
            drvName = NULL;
          }
        }
      }

      /* XXX AJB MAYHEM XXX
       * (Try) to get the devnode of this device
       * so we can use DevIoctls to talk to the
       * minivdd.
       */
      {
        QDEVNODE QDevNode;
        QIN Qin;

        Qin.dwSubFunc = QUERYDEVNODE;

        if (ExtEscape(dc, QUERYESCMODE, sizeof(Qin), (LPSTR) &Qin, sizeof(QDevNode), (LPSTR) &QDevNode)) 
          hInfo.boardInfo[num_monitor].devNode = QDevNode.dwDevNode ;
        else
          hInfo.boardInfo[num_monitor].devNode = 0 ;
      }

      /* Make a private 'copy' of the dc so that we're not affected by
       * other people dorking with dc's etc. 
       *
       * FixMe: Is there a better way to do this? I did not see a
       * CopyDC or anything like that.  
       */
      dc = CreateDC(drvName,
                    devName,
                    NULL,
                    NULL);

      data[num_monitor].dc = dc;
      data[num_monitor].mon = handle;      

      num_monitor++;
      rv = (num_monitor < HWC_MAX_BOARDS);

    }
  }

  return rv;
} /* monitorEnum */

/*
** Use the active window display as the first sst device
*/
static BOOL CALLBACK 
displayMonitor( HMONITOR handle, HDC dc, LPRECT rect, LPARAM param ) 
{
  BOOL rv = TRUE;
  hwcExtRequest_t ctxReq;
  hwcExtResult_t  ctxRes;

  ctxReq.which = HWCEXT_GETDEVICECONFIG;
  GDBG_INFO(80, "displayMonitor:  ExtEscape:HWCEXT_GETDEVICECONFIG\n");

  if (  ExtEscape(dc, HWCEXT_ESCAPE(0), sizeof(ctxReq), (LPSTR) &ctxReq, sizeof(ctxRes), (LPSTR) &ctxRes) ) { /**/
    FxI32 vendorID;

    vendorID = ctxRes.optData.deviceConfigRes.vendorID;

    if ( ctxRes.optData.deviceConfigRes.vendorID == 0x121a ) {
      DevEnumRec*
        data   = (DevEnumRec*) param;
      FxI32 
        i;

      for (i = 0; i < num_monitor; i++) {
        HDC      *return_dc   = ( HDC* ) data + (2*i);
        HMONITOR *return_hmon = ( HMONITOR* ) data + (2*i+1);

        if ((data[i].dc == dc) && (data[i].mon == handle)) {
          data[i].dc = data[0].dc;
          data[i].mon = data[0].mon;

          data[0].dc = dc;
          data[0].mon = handle;

          break;
        }
      }
      rv = FALSE;
    }
  } 
  return rv;
} /* displayMonitor */
#endif

hwcInfo *
hwcInit(FxU32 vID, FxU32 dID)
{
#define FN_NAME "hwcInit"
#ifdef HWC_EXT_INIT
  {
    DevEnumRec
      data[HWC_MAX_BOARDS*2];
    int monitor;

    OSVERSIONINFO ovi;

    ovi.dwOSVersionInfoSize = sizeof ( ovi );
    GetVersionEx ( &ovi );

    GDBG_INFO(80, "%s\n", FN_NAME);
    errorString[0] = '\0';

    /* find glide compatible devices */
    GDBG_INFO(80, "%s:  Finding Glide compatible devices\n", FN_NAME);
    {
      /* Grab the DC of the Desktop. */
      HDC hdc = GetDC(NULL);
      HMODULE user32 = GetModuleHandle( "user32.dll" );

      for (monitor = 0; monitor < HWC_MAX_BOARDS; monitor++) {
        data[monitor].dc  = NULL;
        data[monitor].mon = NULL;
      }
      num_monitor = 0;

      if ( user32 ) {
        EnumDisplayMonitors_func*
          enumDisplayMonitors = (void*)GetProcAddress( user32, "EnumDisplayMonitors" );
        
        if ( enumDisplayMonitors ) { 
          HWND
            curWindow = GetActiveWindow();
          
          GDBG_INFO(80, "%s:  multi-monitor capable OS ( NT5/W98 )\n", FN_NAME);
          enumDisplayMonitors( hdc, 0, monitorEnum, (LPARAM)data );
          
          /*
          ** use the active window display (if there is one yet
          ** associated w/ the current thread) as sst 0 
          */
          if (curWindow != NULL) {
            HDC curWindowDC = GetDC(curWindow);
            
            if (curWindowDC != NULL) {
              enumDisplayMonitors( curWindowDC, 0, displayMonitor, (LPARAM)data );
              ReleaseDC(curWindow, curWindowDC);
            }
          }
        } else { /* for win95/nt4, assume we have one board */
          monitorEnum(NULL, hdc, NULL, (LPARAM)&data);
        }
      }

      ReleaseDC(NULL, hdc);
    }

    hInfo.nBoards = 0;
    for (monitor = 0; monitor < num_monitor; monitor++) {
     hwcExtRequest_t ctxReq;
     hwcExtResult_t  ctxRes;
      HDC 
        hdc = data[monitor].dc;
      HMONITOR
        hmon = data[monitor].mon;
      int 
        status;

      hInfo.nBoards++;
      hInfo.boardInfo[monitor].boardNum     = monitor;
      hInfo.boardInfo[monitor].hdc          = hdc;
      hInfo.boardInfo[monitor].hMon         = hmon;
/*      hInfo.boardInfo[monitor].extContextID = ctxRes.Ext.optData.allocContextRes.contextID; */

      if (ovi.dwPlatformId == VER_PLATFORM_WIN32_NT) {
        hInfo.boardInfo[monitor].osNT = FXTRUE;
        GDBG_INFO(80, FN_NAME ":  OS:  NT\n");
      } else {
        hInfo.boardInfo[monitor].osNT = FXFALSE;
        GDBG_INFO(80, FN_NAME ":  OS:  9X\n");
      }

      ctxReq.which = HWCEXT_GETDEVICECONFIG;
      GDBG_INFO(80, FN_NAME ":  ExtEscape:HWCEXT_GETDEVICECONFIG.\n");

      status = ExtEscape(hdc, HWCEXT_ESCAPE(0), /**/
                         sizeof(ctxReq), (void *) &ctxReq,
                         sizeof(ctxRes), (void *) &ctxRes); 
      
      hInfo.boardInfo[monitor].pciInfo.vendorID = 
        ctxRes.optData.deviceConfigRes.vendorID;
      hInfo.boardInfo[monitor].pciInfo.deviceID = 
        ctxRes.optData.deviceConfigRes.deviceID;
      hInfo.boardInfo[monitor].devRev = 
        ctxRes.optData.deviceConfigRes.chipRev;
      hInfo.boardInfo[monitor].h3Mem = 
        (ctxRes.optData.deviceConfigRes.fbRam >> 20);

#ifdef FX_GLIDE_NAPALM

      if (GETENV("FX_GLIDE_DEVICEID")) {
        FxU32 deviceid = atoi(GETENV("FX_GLIDE_DEVICEID"));
        hInfo.boardInfo[monitor].pciInfo.deviceID = deviceid;
      }

      if (IS_NAPALM(hInfo.boardInfo[monitor].pciInfo.deviceID))
      {
        hInfo.boardInfo[monitor].pciInfo.devNum =
           ctxRes.optData.deviceConfigRes.devNum;
        hInfo.boardInfo[monitor].pciInfo.isMaster =
           ctxRes.optData.deviceConfigRes.isMaster;
        hInfo.boardInfo[monitor].pciInfo.numChips =
           ctxRes.optData.deviceConfigRes.numChips;
        if ((hInfo.boardInfo[monitor].pciInfo.numChips > 4) || 
            (hInfo.boardInfo[monitor].pciInfo.numChips < 0))
          hInfo.boardInfo[monitor].pciInfo.numChips = 0;
      }
#endif /* FX_GLIDE_NAPALM */
            
      hInfo.boardInfo[monitor].pciInfo.initialized = 1;
      hInfo.boardInfo[monitor].h3pixelSize = 2;
      hInfo.boardInfo[monitor].h3nwaySli = 1;

      if (hInfo.boardInfo[monitor].h3Mem == 8) {
        hInfo.boardInfo[monitor].pciInfo.deviceID = SST_DEVICE_ID_H3 ;
      }

      hInfo.boardInfo[monitor].min_tramSize = 
        ((hInfo.boardInfo[monitor].h3Mem == 4 ) ||
         (hInfo.boardInfo[monitor].pciInfo.deviceID == SST_DEVICE_ID_H3)) ? 0x200000 : 0x400000;
      
      if (GETENV("FX_GLIDE_TMU_MEMSIZE")) {
        FxU32 tmu_mem = atoi(GETENV("FX_GLIDE_TMU_MEMSIZE"));
        if (tmu_mem == 1) {
          hInfo.boardInfo[monitor].min_tramSize = 0x200000;
        }
      }

      if(GETENV("FX_GLIDE_NUM_CHIPS")) {
        FxU32 numChips;
        numChips = atoi(GETENV("FX_GLIDE_NUM_CHIPS"));
        /* Don't do anything stupid... */
        if(numChips < 1)
          numChips = 1;
        if(numChips <= hInfo.boardInfo[monitor].pciInfo.numChips) {
          hInfo.boardInfo[monitor].pciInfo.numChips = numChips;
        }
      }

      if (GETENV("FX_GLIDE_FBRAM")) {
        hInfo.boardInfo[monitor].h3Mem = atoi(GETENV("FX_GLIDE_FBRAM"));      
      }

      checkResolutions((int *) resolutionSupported[monitor], 
                       (FxU32) sizeof(resolutionSupported[0][0]) / sizeof(FxBool),
                       (void *) hInfo.boardInfo[monitor].hMon);
    }
  }
#elif defined(HWC_GDX_INIT)
   {
      FxU32 i, j = 0, numTargets;
    
      /* Grab hrm extensions we need. */
      _hrmGetVersionInfo = hrmGetExtension("hrmGetVersionInfo");
      _hrmSetExclusiveMode = hrmGetExtension("hrmSetExclusiveMode");
      _hrmSetVideoMode = hrmGetExtension("hrmSetVideoMode");
      _hrmReleaseExclusiveMode = hrmGetExtension("hrmReleaseExclusiveMode");
      _hrmGetTargetBoardInfo = hrmGetExtension("hrmGetTargetBoardInfoExt");
      _hrmAllocateBlock = hrmGetExtension("hrmAllocateBlock");
      _hrmFreeBlock = hrmGetExtension("hrmFreeBlock");
      _hrmAllocWinContext = hrmGetExtension("hrmAllocWinContext");
      _hrmFreeWinContext = hrmGetExtension("hrmFreeWinContext");
      _hrmExecuteWinFifo = hrmGetExtension("hrmExecuteWinFifo");
      _hrmGetDeviceConfig = hrmGetExtension("hrmGetDeviceConfig");
      _hrmGetAGPInfo = hrmGetExtension("hrmGetAGPInfo");
      _hrmWriteConfigRegister = hrmGetExtension("hrmWriteConfigRegister");
      _hrmReadConfigRegister = hrmGetExtension("hrmReadConfigRegister");
      _hrmGetSlaveRegs = hrmGetExtension("hrmGetSlaveRegs");
      _hrmSLIAA = hrmGetExtension("hrmSLIAA");
      
      /* Have to bail out now if these aren't available. */
      if(!(_hrmSetExclusiveMode && _hrmSetVideoMode && 
         _hrmReleaseExclusiveMode && _hrmGetTargetBoardInfo && _hrmGetVersionInfo))
         return NULL;
    
      /* safety net: no exec if not compatible */
      {
         hrmVersionInfo_t        theVersion;
         
         _hrmGetVersionInfo( &theVersion );
         if ( theVersion.major >= 1 && theVersion.minor >= 6 )
         {
            numTargets = hrmGetNumTargets();
         }
         else
         {
            hwc_errncpy(errorString, "Current version of 3dfx Hardware Resource Manager is not compatible with this version of Glide\n");
            GDBG_INFO(80, "%s:  ERROR... Current version of 3dfx Hardware Resource Manager is not compatible\n", FN_NAME);
            numTargets = 0;
         }
      }
    
      for(i = 0; i < numTargets; i++)
      {
         hrmBoard_t *board;
         hrmBoardInfo_t boardInfo;
      
         board = hrmGetTargetAtIndex(i);
      
         /* Set the size of the struct we're passing in so the HRM has a clue
            what kind of info to return in case the HRM's struct grows in the
            future. */
         boardInfo.size = sizeof(boardInfo);
         _hrmGetTargetBoardInfo(board,&boardInfo);
      
         hInfo.nBoards++;
      
         /* Note that we use hMon for something different than the HRM does. */
         /* We use it to store the reference back to the hrm board this data came
         frome.  The HRM uses hMon to store the GDHandle of the board.  However,
         since we really do need the GDHandle too (for grDeviceQuery), we stash that in hdc. */

         hInfo.boardInfo[j].hMon = board;
         hInfo.boardInfo[j].hdc  = (void *)boardInfo.driverRefNum;
         hInfo.boardInfo[j].h3pixelSize = 2;
         hInfo.boardInfo[j].h3nwaySli = 1;
         hInfo.boardInfo[j].h3Mem = boardInfo.h3Mem;
         hInfo.boardInfo[j].devRev = boardInfo.deviceRev;
         hInfo.boardInfo[j].pciInfo.vendorID = boardInfo.vendorID;
         hInfo.boardInfo[j].pciInfo.deviceID = boardInfo.deviceID;
         hInfo.boardInfo[j].pciInfo.pciBaseAddr[0] = boardInfo.pciBaseAddr[0];
         hInfo.boardInfo[j].pciInfo.pciBaseAddr[1] = boardInfo.pciBaseAddr[1];
         hInfo.boardInfo[j].pciInfo.pciBaseAddr[2] = boardInfo.pciBaseAddr[2];
         hInfo.boardInfo[j].pciInfo.initialized = 1;
         hInfo.boardInfo[j].pciInfo.devNum = boardInfo.devNum;
         hInfo.boardInfo[j].pciInfo.isMaster = boardInfo.isMaster;
         hInfo.boardInfo[j].pciInfo.numChips = boardInfo.numChips;
         hInfo.boardInfo[j].pciInfo.swizzleOffset[0] = boardInfo.swizzleOffset[0];                   
         hInfo.boardInfo[j].pciInfo.swizzleOffset[1] = boardInfo.swizzleOffset[1];                   
         hInfo.boardInfo[j].pciInfo.swizzleOffset[2] = boardInfo.swizzleOffset[2];                   
         hInfo.boardInfo[j].pciInfo.swizzleOffset[3] = boardInfo.swizzleOffset[3];                   

         if (GETENV("FX_GLIDE_FBRAM")) {
            hInfo.boardInfo[j].h3Mem = atoi(GETENV("FX_GLIDE_FBRAM"));      
         }

#ifdef FX_GLIDE_NAPALM
         if (GETENV("FX_GLIDE_DEVICEID"))
         {
            FxU32 deviceid = atoi(GETENV("FX_GLIDE_DEVICEID"));
            hInfo.boardInfo[j].pciInfo.deviceID = deviceid;
         }
         if(GETENV("FX_GLIDE_NUM_CHIPS"))
         {
            FxU32 numChips;
            numChips = atoi(GETENV("FX_GLIDE_NUM_CHIPS"));
            /* Don't do something stupid... */
            if(numChips <= hInfo.boardInfo[j].pciInfo.numChips)
            {
               hInfo.boardInfo[j].pciInfo.numChips = numChips;
            }
         }
#endif
         j++;
      }
   }
#else /* HWC_GDX_INIT */
  {
    int i, chip;
    FxU32 bn;

    pciOpen();

    hInfo.nBoards = 0;

    errorString[0] = '\0';

    for (i = 0; i < HWC_MAX_BOARDS; i++) {
      hInfo.boardInfo[i].pciInfo.initialized = 0;
      if (pciFindCardMulti(vID, dID, &bn, i)) {
        hInfo.nBoards++;
        hInfo.boardInfo[i].boardNum = 0;
        hInfo.boardInfo[i].deviceNum = bn;

        hInfo.boardInfo[i].pciInfo.initialized = 1;
        hInfo.boardInfo[i].pciInfo.vendorID = vID;
        hInfo.boardInfo[i].pciInfo.deviceID = dID;
        hInfo.boardInfo[i].pciInfo.numChips = 1;
        hInfo.boardInfo[i].pciInfo.devNum = 0;
        hInfo.boardInfo[i].pciInfo.isMaster = 1;

        hInfo.boardInfo[i].h3pixelSize = 2;
        hInfo.boardInfo[i].h3pixelSample = 1;
        hInfo.boardInfo[i].h3nwaySli = 1;

        /* 
         * NOTE: in the code above we learn about memsize here:
         *   hInfo.boardInfo[i].h3Mem
         * 
         * However, in DOS, since we have not mapped the board yet, we have
         * to wait until later. (see hwcInitRegisters())  - dwj
         */

        /* Get some board Info */
        pciGetConfigData( PCI_REVISION_ID, bn, &hInfo.boardInfo[i].devRev);

        /* Get all the base addresses */
        pciGetConfigData(PCI_BASE_ADDRESS_0, bn,
                         &hInfo.boardInfo[i].pciInfo.pciBaseAddr[0]);
        pciGetConfigData(PCI_BASE_ADDRESS_1, bn,
                         &hInfo.boardInfo[i].pciInfo.pciBaseAddr[1]);
        pciGetConfigData(PCI_IO_BASE_ADDRESS, bn,
                         &hInfo.boardInfo[i].pciInfo.pciBaseAddr[2]);
        pciGetConfigData(PCI_ROM_BASE_ADDRESS, bn,
                         &hInfo.boardInfo[i].pciInfo.pciBaseAddr[3]);
      
        if (GETENV("FX_GLIDE_DEVICEID")) {
          FxU32 deviceid = atoi(GETENV("FX_GLIDE_DEVICEID"));
          hInfo.boardInfo[i].pciInfo.deviceID = deviceid;
        }

        /* Evilness. Try to auto-detect how many chips we have by trying to
         * read the vendor/deviceID register back from chips 1 through 3. */
        if(IS_NAPALM(hInfo.boardInfo[i].pciInfo.deviceID)) {
          FxU32 device_vendor;

          /* Detect two-chip board */
          device_vendor = hwcReadConfigRegister(&hInfo.boardInfo[i], 1, offsetof(SstPCIConfigRegs, deviceID_vendorID));
          if((device_vendor & 0xFFFF) == 0x121a && (IS_NAPALM((device_vendor >> 16)))) {
            hInfo.boardInfo[i].pciInfo.numChips = 2;
            
            /* Map in the slave's physical memory */
            mapSlavePhysical(&hInfo.boardInfo[i], 1);                       
             
            /* Detect four-chip board */  
            device_vendor = hwcReadConfigRegister(&hInfo.boardInfo[i], 3, offsetof(SstPCIConfigRegs, deviceID_vendorID));
            if((device_vendor & 0xFFFF) == 0x121a && (IS_NAPALM((device_vendor >> 16)))) {
              hInfo.boardInfo[i].pciInfo.numChips = 4;
              /* Map in last two chips */
              mapSlavePhysical(&hInfo.boardInfo[i], 2);
              mapSlavePhysical(&hInfo.boardInfo[i], 3);
            }
          }            

          for(chip = 1; chip < hInfo.boardInfo[i].pciInfo.numChips; chip++) {
            hInfo.boardInfo[i].pciInfo.pciBaseAddr[(chip << 2) + 0] = 
              hwcReadConfigRegister(&hInfo.boardInfo[i], chip, offsetof(SstPCIConfigRegs, memBaseAddr0));
            hInfo.boardInfo[i].pciInfo.pciBaseAddr[(chip << 2) + 1] = 
              hwcReadConfigRegister(&hInfo.boardInfo[i], chip, offsetof(SstPCIConfigRegs, memBaseAddr1));
            hInfo.boardInfo[i].pciInfo.pciBaseAddr[(chip << 2) + 2] = 
              hwcReadConfigRegister(&hInfo.boardInfo[i], chip, offsetof(SstPCIConfigRegs, ioBaseAddr));
          }
        }        
            
        if(GETENV("FX_GLIDE_NUM_CHIPS")) {
          FxU32 numChips;
          numChips = atoi(GETENV("FX_GLIDE_NUM_CHIPS"));
          /* Don't do something stupid... */
          if(numChips <= hInfo.boardInfo[i].pciInfo.numChips) {
            hInfo.boardInfo[i].pciInfo.numChips = numChips;
          }
        }      
      }
    }
  
  }
#endif /* HWC_EXT_INIT */
  if (hInfo.nBoards)
    return &hInfo;
  else
    return NULL;

#undef FN_NAME
} /* hwcInit */

FxBool
hwcMapBoard(hwcBoardInfo *bInfo, FxU32 bAddrMask)
{
#define FN_NAME "hwcMapBoard"

  if (bInfo->pciInfo.initialized == FXFALSE) {
    sprintf(errorString, "%s:  Called before hwcInit\n", FN_NAME);
    return FXFALSE;
  }

  bInfo->linearInfo.initialized = FXTRUE;

#ifdef HWC_EXT_INIT
  {
    hwcExtRequest_t ctxReq;
    hwcExtResult_t  ctxRes; 
      
    bInfo->procHandle = (FxU32) GetCurrentProcessId();
    GDBG_INFO(80, FN_NAME ":  procHandle:  0x%x\n", bInfo->procHandle);

    ctxReq.which = HWCEXT_GETLINEARADDR;
    ctxReq.optData.linearAddrReq.devNum = 0;
    ctxReq.optData.linearAddrReq.pHandle = bInfo->procHandle;
    GDBG_INFO(80, FN_NAME ":  ExtEscape:HWCEXT_GETLINEARADDR\n");

    ExtEscape((HDC) bInfo->hdc, HWCEXT_ESCAPE(bInfo->boardNum), sizeof(ctxReq), (void *) &ctxReq, /**/
      sizeof(ctxRes), (void *) &ctxRes);

    if (ctxRes.resStatus != 1) {
      hwc_errncpy(errorString, "HWCEXT_GETLINEARADDR Failed");
      return FXFALSE;
    }
    bInfo->isMapped = FXTRUE;

    bInfo->linearInfo.linearAddress[0] =
      ctxRes.optData.linearAddressRes.baseAddresses[0];
    bInfo->linearInfo.linearAddress[1] =
      ctxRes.optData.linearAddressRes.baseAddresses[1];
    
    /* WTF????? */
    bInfo->pciInfo.pciBaseAddr[2] = 
      ctxRes.optData.linearAddressRes.baseAddresses[1];

    /*
    ** AJB - if there are slave chips, get slave chip regs
    */
    if (bInfo->pciInfo.numChips > 1)
    {
      FxU32 chip ;
      FxU32 i ;

      for (chip = 1 ;
           chip < bInfo->pciInfo.numChips ;
           chip++)
      {
        ctxReq.which = HWCEXT_GET_SLAVE_REGS ;
        ctxReq.optData.slaveRegReq.DeviceId = chip ;
        GDBG_INFO(80, FN_NAME ":  ExtEscape:HWCEXT_GET_SLAVE_REGS\n") ;

        ExtEscape((HDC) bInfo->hdc, HWCEXT_ESCAPE(bInfo->boardNum), sizeof(ctxReq), (void *) &ctxReq, sizeof(ctxRes), (void *) &ctxRes) ;

        if (ctxRes.resStatus != 1) 
        {
          hwc_errncpy(errorString, "HWCEXT_GET_SLAVE_REGS Failed") ;
          return FXFALSE ;
        }

        for (i = 0 ; /* Get back 4 register space mappings for each chip */
             i < 4 ;
             i++)
        {
          bInfo->linearInfo.linearAddress[(chip << 2) + i] = ctxRes.optData.slaveRegRes.Regs[i] ;
        }
      }
    }
  }
#elif defined(HWC_GDX_INIT)
        /* Pretty simple, because MacOS is basically lame */
  {
    FxU32
      bAddr;

    /* memory mapped register spaces */
    for (bAddr = 0; bAddr < 2; bAddr++) {
      if ((bAddrMask & (0x01UL << bAddr)) != 0x00UL) {
        bInfo->linearInfo.linearAddress[bAddr] = bInfo->pciInfo.pciBaseAddr[bAddr];
      }
    }
    /* FixMe: This gets used to set the pll's so I guess we need it here
     * unconditionally
     */
    bInfo->isMapped = FXTRUE;
    bInfo->linearInfo.linearAddress[2] = bInfo->pciInfo.pciBaseAddr[2];
    
    /* Sorry, ROM mapping on MacOS seems whacked out for some reason. */
    bInfo->linearInfo.linearAddress[3] = 0;

    if (bInfo->pciInfo.numChips > 1)
    {
      FxU32 chip ;
      FxU32 i ;
      FxU32 regs[4];
      
      for (chip = 1 ;
           chip < bInfo->pciInfo.numChips ;
           chip++)
      {
        _hrmGetSlaveRegs((hrmBoard_t *)bInfo->hMon, chip, regs);
          
        for (i = 0 ; /* Get back 4 register space mappings for each chip */
             i < 4 ;
             i++)
        {
          bInfo->linearInfo.linearAddress[(chip << 2) + i] = regs[i];
        }
      }
    }
    
  }
#else
  {
    FxU32
      bAddr, length;

    bInfo->isMapped = FXTRUE;

    if (IS_NAPALM(bInfo->pciInfo.deviceID))
      length = 32*1024*1024;
    else
      length = 16*1024*1024;
    
    /* memory mapped register spaces */
    for (bAddr = 0; bAddr < 2; bAddr++) {
      if ((bAddrMask & (0x01UL << bAddr)) != 0x00UL) {
        bInfo->linearInfo.linearAddress[bAddr] = 
          (AnyPtr)pciMapCardMulti(bInfo->pciInfo.vendorID, bInfo->pciInfo.deviceID,
                                 length, &bInfo->deviceNum, bInfo->boardNum, bAddr);
      }
    }

    /* FixMe: This gets used to set the pll's so I guess we need it here
     * unconditionally
     */
    bInfo->linearInfo.linearAddress[2] = 
      (AnyPtr)pciMapCardMulti(bInfo->pciInfo.vendorID, bInfo->pciInfo.deviceID,
                             length, &bInfo->deviceNum, bInfo->boardNum, 2);

    /* Does the caller want the rom bios? */
    if ((bAddrMask & 0x08UL) != 0x00UL) {
      bInfo->linearInfo.linearAddress[3] = 
        (AnyPtr)pciMapCardMulti(bInfo->pciInfo.vendorID, bInfo->pciInfo.deviceID,
                               0x1000000, &bInfo->deviceNum, bInfo->boardNum, 3);
    }

    /* Map in slaves too */
    if(bInfo->pciInfo.numChips > 1) {
      FxU32 chip;
      FxBool success;
      FxU32 length = 32*1024*1024;
        
      for(chip = 1 ; chip < bInfo->pciInfo.numChips; chip++) {
        /* The PCI library seemed a bit whacked for mapping in multi-function
         * devices, so I use the more low-level routines to map in the two 
         * physical memory chunks I need. */
        success = pciMapPhysicalToLinear(&bInfo->linearInfo.linearAddress[(chip << 2) + 0],
                                         bInfo->pciInfo.pciBaseAddr[(chip << 2) + 0],
                                         &length);
        if(!success) {
            /* We failed to map.  Punt. */
            bInfo->pciInfo.numChips = 1;
            break;
        }
        success = pciMapPhysicalToLinear(&bInfo->linearInfo.linearAddress[(chip << 2) + 1],
                                         bInfo->pciInfo.pciBaseAddr[(chip << 2) + 1],
                                         &length);
        if(!success) {
            /* We failed to map.  Punt. */
            bInfo->pciInfo.numChips = 1;
            break;
        }
      }
    }
  }
#endif  
  
  return FXTRUE;
#undef FN_NAME
} /* hwcMapBoard */

FxBool
hwcInitRegisters(hwcBoardInfo *bInfo) 
{
#define FN_NAME hwcInitRegisters
  FxU32
    grxSpeedInMHz, memSpeedInMHz,
    sgramMode, sgramMask, sgramColor;
  
  if (bInfo->linearInfo.initialized == FXFALSE) {
    sprintf(errorString, "%s:  Called before hwcMapBoard\n", FN_NAME);
    return FXFALSE;
  }
      
  bInfo->regInfo.initialized = FXTRUE;

  bInfo->regInfo.ioMemBase =
    bInfo->linearInfo.linearAddress[0] + SST_IO_OFFSET;
  bInfo->regInfo.cmdAGPBase =
    bInfo->linearInfo.linearAddress[0] + SST_CMDAGP_OFFSET;
  bInfo->regInfo.waxBase =
    bInfo->linearInfo.linearAddress[0] + SST_2D_OFFSET;
  bInfo->regInfo.sstBase =
    bInfo->linearInfo.linearAddress[0] + SST_3D_OFFSET;
  bInfo->regInfo.lfbBase =
    bInfo->linearInfo.linearAddress[0] + SST_LFB_OFFSET;

  /*
  // AJB: Init slave chip regs
  // Someday I may define these magic numbers.
  */
#if defined (HWC_EXT_INIT) ||  defined(HWC_GDX_INIT)
  {
    FxU32 chip ;

    for (chip = 1 ;
         chip < bInfo->pciInfo.numChips ;
         chip++)
    {
      bInfo->regInfo.slaveSstBase[chip - 1] = bInfo->linearInfo.linearAddress[(chip << 2) + 3] ;
      bInfo->regInfo.slaveCmdBase[chip - 1] = bInfo->linearInfo.linearAddress[(chip << 2) + 1] ;
      bInfo->regInfo.slaveIOBase[chip - 1]  = bInfo->linearInfo.linearAddress[(chip << 2) + 0] ;
    }
  }
#else 
  /* DOS is a bit weirder. In this case we have both memBase0 and memBase1's linear
   * addresses stored in linearAddress[0] and linearAddress[1], which is not what
   * the Windows and Mac code expect.  However, the important thing is really just
   * the slave* stuff in regInfo, so we fix that up here.
   */
  {
    FxU32 chip ;

    for (chip = 1 ;
         chip < bInfo->pciInfo.numChips ;
         chip++)
    {
      bInfo->regInfo.slaveSstBase[chip - 1] = bInfo->linearInfo.linearAddress[(chip << 2) + 0] + SST_3D_OFFSET;
      bInfo->regInfo.slaveCmdBase[chip - 1] = bInfo->linearInfo.linearAddress[(chip << 2) + 0] + SST_CMDAGP_OFFSET ;
      bInfo->regInfo.slaveIOBase[chip - 1]  = bInfo->linearInfo.linearAddress[(chip << 2) + 0];
      /* We need this for VGA crap, which Win32 and DOS don't need. */
      bInfo->regInfo.slaveIOPortBase[chip - 1] = bInfo->pciInfo.pciBaseAddr[(chip << 2) + 2] & ~0x1;
    }
  }

#endif

  bInfo->regInfo.rawLfbBase =
    bInfo->linearInfo.linearAddress[1];
#if __POWERPC__    
  bInfo->regInfo.ioPortBase = bInfo->pciInfo.pciBaseAddr[2] & ~0x1;
#else
  bInfo->regInfo.ioPortBase = (FxU16) bInfo->pciInfo.pciBaseAddr[2] & ~0x1;
#endif
  /* Figure out if it's SDRAM */
  {
    FxU32 dramInit1;
    
    HWC_IO_LOAD(bInfo->regInfo, dramInit1, dramInit1);
    bInfo->sdRAM = ((dramInit1 & SST_MCTL_TYPE_SDRAM) != 0x00UL);

    if (GETENV("SSTH3_SDRAM"))
      bInfo->sdRAM = FXTRUE;
  }

#if !defined(HWC_EXT_INIT) && !defined(HWC_GDX_INIT)
  {
    FxU32 
      pciInit0,
      pciCommandReg =
        BIT(0) |              /* enable i/o decode */
        BIT(1);               /* enable memory decode */
  
    /* Enable PCI memory and I/O decode */
    pciSetConfigData(PCI_COMMAND, bInfo->deviceNum, &pciCommandReg);
    
    HWC_IO_LOAD(bInfo->regInfo, pciInit0, pciInit0);
    pciInit0 |= SST_PCI_READ_WS | SST_PCI_WRITE_WS;
    HWC_IO_STORE(bInfo->regInfo, pciInit0, pciInit0);  
  }
#endif

  if (GETENV("SSTH3_SGRAM_MODE"))
    sgramMode = atoi(GETENV("SSTH3_SGRAM_MODE"));
  else if (GETENV("SSTH3_SGRAM_222") &&
    (atoi(GETENV("SSTH3_SGRAM_222")) != 0))
    sgramMode = 0x27;
  else
    sgramMode = 0x37;

  if (GETENV("SSTH3_SGRAM_MASK"))
    sgramMask = atoi(GETENV("SSTH3_SGRAM_MASK"));
  else
    sgramMask = 0xFFFFFFFF;

  if (GETENV("SSTH3_SGRAM_COLOR"))
    sgramColor = atoi(GETENV("SSTH3_SGRAM_COLOR"));
  else
    sgramColor = 0;

  if (GETENV("SSTH3_GRXCLOCK"))
    grxSpeedInMHz = atoi(GETENV("SSTH3_GRXCLOCK"));
  else
    grxSpeedInMHz = 100;

  if (GETENV("SSTH3_MEMCLOCK"))
    memSpeedInMHz = atoi(GETENV("SSTH3_MEMCLOCK"));
  else
    memSpeedInMHz = 100;

#if !defined(HWC_ACCESS_DDRAW) && !defined(HWC_GDX_INIT)
  if (GETENV("HAL_NOINIT") == NULL || atoi(GETENV("HAL_NOINIT")) == 0) {

    /* 
     * final DOS initialiation
     */

    /* don't set the clocks unless they used the environment variables */

    if (GETENV("SSTH3_GRXCLOCK") || GETENV("SSTH3_MEMCLOCK")) {
     switch (bInfo->pciInfo.deviceID) {
        case SST_DEVICE_ID_H3: /* banshee */
           h3InitPlls(bInfo->regInfo.ioPortBase,  grxSpeedInMHz, memSpeedInMHz);
           break;
        case SST_DEVICE_ID_H4: /* voodoo3/avenger */
            break;
        case SST_DEVICE_ID_H4_OEM: /* voodoo3/avenger */
           break;
        default: /* unknown board type!!! */
           return FXFALSE;
     }
    }

    /* read back the memory size, since we 
     * don't know it under DOS  (see hwcInit) - dwj 
     */
    bInfo->h3Mem = h3InitGetMemSize(bInfo->regInfo.ioPortBase);
    /* Ugh, lame.  We can only report back 16MB to Glide since we can't
     * really map in all 64MB necessary for LFB accesses. */
    if(IS_NAPALM(bInfo->pciInfo.deviceID)) {
        if(bInfo->h3Mem > 16) {
            bInfo->h3Mem = 16;
        }
    }

    h3InitVga(bInfo->regInfo.ioPortBase, FXTRUE); 
  }
#endif
  
  return FXTRUE;

#undef FN_NAME
} /* hwcInitRegisters */

#define FIFOPAD         0x0000
#define AUXPAD          0x1000

FxBool
hwcAllocBuffers(hwcBoardInfo *bInfo, FxU32 nColBuffers, FxU32 nAuxBuffers) 
{
#define FN_NAME "hwcAllocBuffers"
  FxBool
    bufferAlignP, napalmfifo = FXTRUE;
  FxU32
    bNum,
    h3Mem = bInfo->h3Mem << 20,
    freeMem,
    bufStride, 
    bufSize;
  FxI32
    i,
    tramSize, fifoSize;

  if (bInfo->vidInfo.initialized == FXFALSE) {
    sprintf(errorString, "%s:  Called before video initialization\n", FN_NAME);
    return FXFALSE;
  }
    
  GDBG_INFO(80, "%s(0x%x, 0x%x, 0x%x)\n", FN_NAME, bInfo, nColBuffers, nAuxBuffers);

  /* I've decided on > 2 instead of == 3 because we may support more
    than 3 buffers in the future, and want 4 to set the
    triple-buffering bit in dramInit1, also */
  bInfo->vidInfo.tripleBuffering = (nColBuffers > 2);

  bInfo->vidInfo.stride = bufStride =
    calcBufferStride(bInfo, bInfo->vidInfo.xRes, bInfo->vidInfo.tiled);   

  /* We want to place the FIFO after the tram but before the color
     buffers with some pad */
  bufSize = calcBufferSize(bInfo, bInfo->vidInfo.xRes, bInfo->vidInfo.yRes,
    bInfo->vidInfo.tiled); 

  bInfo->buffInfo.bufStride = bufStride;
  bInfo->buffInfo.bufSize = bufSize;
  bInfo->buffInfo.bufLfbStride = HWC_LFB_STRIDE;

  if (bInfo->vidInfo.tiled) {
    bInfo->buffInfo.bufStrideInTiles = (bufStride >> 7);
    bInfo->buffInfo.bufSizeInTiles =
      calcBufferSizeInTiles(bInfo, bInfo->vidInfo.xRes, bInfo->vidInfo.yRes);
    bInfo->buffInfo.bufHeightInTiles =
      calcBufferHeightInTiles(bInfo, bInfo->vidInfo.yRes);
  }

  bInfo->buffInfo.initialized = FXTRUE;
  bInfo->buffInfo.nColBuffers = nColBuffers;
  bInfo->buffInfo.nAuxBuffers = nAuxBuffers;

  /* First, do the primary buffer allocation */        
  freeMem = h3Mem;

  if (nAuxBuffers > 0) {
    bInfo->buffInfo.auxBuffEnd0  =
    bInfo->buffInfo.auxBuffStart0 = freeMem;

    bInfo->buffInfo.auxBuffStart0 -= bufSize;

    /* auxBuffers start on odd pages, so we need to check to see if
     * it's on an even page and, if so, make it odd. 
     *
     * NB: We need to do the same sort of 'alignment' thing here as for
     * the color buffers.
     */
    bufferAlignP = ((bInfo->buffInfo.auxBuffStart0 & 0x1000UL) == 0);
    if (bufferAlignP) bInfo->buffInfo.auxBuffStart0 -= 0x1000;
    
    freeMem = bInfo->buffInfo.auxBuffStart0;
  }

  for (i = nColBuffers - 1; i >= 0; i--) {

    bInfo->buffInfo.colBuffStart0[i] = 
      bInfo->buffInfo.colBuffEnd0[i] = freeMem;

    bInfo->buffInfo.colBuffStart0[i] -= bufSize;

    /* As a memory access optmization colorBuffers start on even
     * pages, while aux buffers start on odd pages.  Thus we must
     * check to see if we're startding on an odd page here and, if so,
     * add a page to the start.  
     */
    bufferAlignP = ((bInfo->buffInfo.colBuffStart0[i] & 0x1000UL) != 0);
    if (bufferAlignP) bInfo->buffInfo.colBuffStart0[i] -= 0x1000;

    freeMem = bInfo->buffInfo.colBuffStart0[i];
  }

  /* Now we can calculate some other stuff... */
  bInfo->fbOffset = bInfo->primaryOffset = bInfo->buffInfo.colBuffStart0[0];

  /* if the secondary buffer is enabled */
  if (bInfo->buffInfo.enable2ndbuffer) {
    if (nAuxBuffers > 0) {
      bInfo->buffInfo.auxBuffEnd1  =
        bInfo->buffInfo.auxBuffStart1 = freeMem;

      bInfo->buffInfo.auxBuffStart1 -= bufSize;

      /* auxBuffers start on odd pages, so we need to check to see if
       * it's on an even page and, if so, make it odd. 
       *
       * NB: We need to do the same sort of 'alignment' thing here as for
       * the color buffers.
       */
      bufferAlignP = ((bInfo->buffInfo.auxBuffStart1 & 0x1000UL) == 0);
      if (bufferAlignP) bInfo->buffInfo.auxBuffStart1 -= 0x1000;
      
      freeMem = bInfo->buffInfo.auxBuffStart1;
    }
    
    for (i = nColBuffers - 1; i >= 0; i--) {
      
      bInfo->buffInfo.colBuffStart1[i] = 
        bInfo->buffInfo.colBuffEnd1[i] = freeMem;
      
      bInfo->buffInfo.colBuffStart1[i] -= bufSize;
      
      /* As a memory access optmization colorBuffers start on even
       * pages, while aux buffers start on odd pages.  Thus we must
       * check to see if we're startding on an odd page here and, if so,
       * add a page to the start.  
       */
      bufferAlignP = ((bInfo->buffInfo.colBuffStart1[i] & 0x1000UL) != 0);
      if (bufferAlignP) bInfo->buffInfo.colBuffStart1[i] -= 0x1000;
      
      freeMem = bInfo->buffInfo.colBuffStart1[i];
    }

    /* Now we can calculate some other stuff... */
    bInfo->fbOffset = bInfo->secondaryOffset = bInfo->buffInfo.colBuffStart1[0];
  }


  /*
  ** Napalm restricts its cmd fifo within 16MB range so
  ** we place it at low address 0x0.
  */
  if (IS_NAPALM(bInfo->pciInfo.deviceID)) {
    napalmfifo = FXTRUE;
  }

  if (getenv("FX_GLIDE_V3FIFO")) {
    napalmfifo = FXFALSE;
  }
  if ((IS_NAPALM(bInfo->pciInfo.deviceID)) && (napalmfifo)) {
    FxU32 pad = 96*1024; /* Get out of the way of VGA */

    if(GETENV("FX_GLIDE_FIFOEXTRA")) 
      pad = atoi(GETENV("FX_GLIDE_FIFOEXTRA"));

    bInfo->tramOffset = fifoSize = MAXFIFOSIZE_16MB + pad;

    tramSize =  bInfo->fbOffset - bInfo->tramOffset;
    if (tramSize < (FxI32)bInfo->min_tramSize) {
      /* Now we have to shrink the FIFO */
      tramSize = bInfo->min_tramSize;
      fifoSize = bInfo->fbOffset - bInfo->min_tramSize;
      /* We don't want a FIFO smaller than one page */
      if (fifoSize < (FxI32)(pad+4096)) {
        GDBG_INFO(80, "%s:  Not enough memory for resolution + min texture\n",
                  FN_NAME);
        sprintf(errorString, 
                "%s:  Not enough memory for resolution + min texture\n",
                FN_NAME);
        return FXFALSE;
      } 
    }
    
    bInfo->fifoInfo.fifoLength = (FxU32) fifoSize - pad;
    bInfo->fifoInfo.fifoStart = pad;
    bInfo->tramOffset = (FxU32) fifoSize;
    bInfo->tramSize = (FxU32) tramSize;
  }
  else {
    fifoSize = (bInfo->h3Mem > 8) ? MAXFIFOSIZE_16MB : MAXFIFOSIZE;
    tramSize =  bInfo->fbOffset - bInfo->tramOffset - fifoSize;
    if (tramSize < (FxI32)bInfo->min_tramSize) {
      /* Now we have to shrink the FIFO */
      tramSize = bInfo->min_tramSize;
      fifoSize = bInfo->fbOffset - bInfo->min_tramSize;
      /* We don't want a FIFO smaller than one page */
      if (fifoSize < 4096) {
        GDBG_INFO(80, "%s:  Not enough memory for resolution + min texture\n",
                  FN_NAME);
        sprintf(errorString, 
                "%s:  Not enough memory for resolution + min texture\n",
                FN_NAME);
        return FXFALSE;
      } 
    }
    
    bInfo->fifoInfo.fifoLength = (FxU32) fifoSize;
    bInfo->fifoInfo.fifoStart = bInfo->fbOffset - fifoSize;
    
    /* Huh? Why is this here? */
    bInfo->fifoInfo.fifoLength -= 0x2000;
    
    bInfo->tramSize = (FxU32) tramSize;
  }

  {
    for (bNum = 0; bNum < nColBuffers; bNum++) {
      bInfo->buffInfo.lfbBuffAddr0[bNum] = 
        hwcBufferLfbAddr(bInfo, bInfo->buffInfo.colBuffStart0[bNum]);
      /* Not really used, but here for consistancy */
      bInfo->buffInfo.lfbBuffAddr0End[bNum] = 
        hwcBufferLfbAddr(bInfo, bInfo->buffInfo.colBuffEnd0[bNum]);
    }

    if (nAuxBuffers > 0) {
      bInfo->buffInfo.lfbBuffAddr0[nColBuffers] =
        hwcBufferLfbAddr(bInfo, bInfo->buffInfo.auxBuffStart0);
      /* I'm not sure if this is right or not... */
      bInfo->buffInfo.lfbBuffAddr0End[nColBuffers] = 
        hwcBufferLfbAddr(bInfo, bInfo->buffInfo.auxBuffEnd0);
    }
  }

  bInfo->buffInfo.initialized = FXTRUE;

  GDBG_INFO(80, "%s:  Board Info:\n", FN_NAME);
  GDBG_INFO(80, "\thdc:             0x%x\n", bInfo->hdc);
/*  GDBG_INFO(80, "\textContextID:    0x%x\n", bInfo->extContextID); */
  GDBG_INFO(80, "\tdevRev:          0x%x\n", bInfo->devRev);
  GDBG_INFO(80, "\tfbOffset:        0x%x\n", bInfo->fbOffset);
  GDBG_INFO(80, "\tprimaryOffset:   0x%x\n", bInfo->primaryOffset);
  GDBG_INFO(80, "\tsecondaryOffset: 0x%x\n", bInfo->secondaryOffset);
  GDBG_INFO(80, "\th3Rev:           0x%x\n", bInfo->h3Rev);
  GDBG_INFO(80, "\th3Mem:           0x%x\n", bInfo->h3Mem);
  GDBG_INFO(80, "\tboardNum:        0x%x\n", bInfo->boardNum);
  GDBG_INFO(80, "\tdeviceNum:       0x%x\n", bInfo->deviceNum);

  GDBG_INFO(80, "%s:  Buffer Info:\n", FN_NAME);
  GDBG_INFO(80, "\tbufSize:         0x%x\n", bInfo->buffInfo.bufSize);
  GDBG_INFO(80, "\tbufSizeInTiles:  0x%x\n", bInfo->buffInfo.bufSizeInTiles);
  GDBG_INFO(80, "\tbufStride:       0x%x\n", bInfo->buffInfo.bufStride);
  GDBG_INFO(80, "\tbufStrideInTiles:0x%x\n", bInfo->buffInfo.bufStrideInTiles);
  GDBG_INFO(80, "\tbufHeightInTiles:0x%x\n", bInfo->buffInfo.bufHeightInTiles);
  GDBG_INFO(80, "\tnColBuffers:     0x%x\n", bInfo->buffInfo.nColBuffers);
  for (i = 0; i < (FxI32) nColBuffers; i++) {
    GDBG_INFO(80, "\tcolBuff0[%d] Start:    0x%x\n", i, bInfo->buffInfo.colBuffStart0[i]);
    GDBG_INFO(80, "\tcolBuff0[%d] End:      0x%x\n", i, bInfo->buffInfo.colBuffEnd0[i]);
  }
  for (i = 0; i < (FxI32) nColBuffers; i++) {
    GDBG_INFO(80, "\tcolBuff1[%d] Start:    0x%x\n", i, bInfo->buffInfo.colBuffStart1[i]);
    GDBG_INFO(80, "\tcolBuff1[%d] End:      0x%x\n", i, bInfo->buffInfo.colBuffEnd1[i]);
  }
  for (i = 0; i < (FxI32) nColBuffers; i++) {
    GDBG_INFO(80, "\tcolBuff0Lfb[%d] Start: 0x%x\n", i, bInfo->buffInfo.lfbBuffAddr0[i]);
    GDBG_INFO(80, "\tcolBuff0Lfb[%d] End:   0x%x\n", i, bInfo->buffInfo.lfbBuffAddr0End[i]);
  }
  GDBG_INFO(80, "\tnAuxBuffers:     0x%x\n", bInfo->buffInfo.nAuxBuffers);
  GDBG_INFO(80, "\tauxBuffStart0:    0x%x\n", bInfo->buffInfo.auxBuffStart0);
  GDBG_INFO(80, "\tauxBuffEnd0:      0x%x\n", bInfo->buffInfo.auxBuffEnd0);
  GDBG_INFO(80, "\tauxBuffStart1:    0x%x\n", bInfo->buffInfo.auxBuffStart1);
  GDBG_INFO(80, "\tauxBuffEnd1:      0x%x\n", bInfo->buffInfo.auxBuffEnd1);
  GDBG_INFO(80, "\tauxBuffStart0Lfb: 0x%x\n", bInfo->buffInfo.lfbBuffAddr0[nColBuffers]);
  GDBG_INFO(80, "\tauxBuffEnd0Lfb:   0x%x\n", bInfo->buffInfo.lfbBuffAddr0End[nColBuffers]);

  GDBG_INFO(80, "%s:  FIFO Info:\n", FN_NAME);
  GDBG_INFO(80, "\tfifoStart:       0x%x\n", bInfo->fifoInfo.fifoStart);
  GDBG_INFO(80, "\tfifoLength:      0x%x\n", bInfo->fifoInfo.fifoLength);

  GDBG_INFO(80, "%s:  TRAM Info:\n", FN_NAME);
  GDBG_INFO(80, "\ttramOffset:      0x%x\n", bInfo->tramOffset);
  GDBG_INFO(80, "\ttramSize:        0x%x\n", bInfo->tramSize);
  GDBG_INFO(80, "\tMin TramSize:    0x%x\n", bInfo->min_tramSize);

  return FXTRUE;
#undef FN_NAME
} /* hwcAllocBuffers */

void hwcIdleHardwareWithTimeout(hwcBoardInfo *bInfo)
{
  FxU32 
    miscInit0, miscInit1, status, statusSlave, idle, timeout, i;

  /* Wait for hardware to idle. */
  idle = 0;
  timeout = 0;

checkforidle:
  do {
    if(idle > 0) {
      GDBG_INFO(80,"waiting for idle...\n");
    }
    HWC_IO_LOAD(bInfo->regInfo, status, status);
    for(i = 1; i < bInfo->pciInfo.numChips; i++) {
      HWC_IO_LOAD_SLAVE(i, bInfo->regInfo, status, statusSlave);
      status |= statusSlave;
    }
    /* Make sure we see an idle 3 times in a row from all chips. */
    if(status & SST_BUSY) {
     idle = 0;
    } else {
     idle++;
    }
    timeout++;
    /* Nothing the hardware does should take as long as reading the
     * status registers a billion times... */
    if(timeout >= 1000000000) {
      break;
    }        
  } while(idle < 3);  

  if(timeout >= 1000000000) {
    GDBG_INFO(80,"Hardware timeout on idle, resetting...\n");
    /* Reset FBI, 2D, and command streams. */
    HWC_IO_LOAD(bInfo->regInfo, miscInit0, miscInit0);
    /* Also be sure to make sure miscInit1's addressing is correct on Napalm */
    HWC_IO_STORE(bInfo->regInfo, miscInit0, (miscInit0 & ~BIT(30)) | SST_GRX_RESET | SST_2D_RESET);
    HWC_IO_LOAD(bInfo->regInfo, miscInit1, miscInit1);
    HWC_IO_STORE(bInfo->regInfo, miscInit1, miscInit1 | SST_CMDSTREAM_RESET);

    /* Give it a little time to propagate */
    for(idle = 0; idle < 100; idle++) {
      HWC_IO_LOAD(bInfo->regInfo, status, status);    
    }  
    /* Let hardware out of reset */
    HWC_IO_STORE(bInfo->regInfo, miscInit1, miscInit1);
    HWC_IO_STORE(bInfo->regInfo, miscInit0, miscInit0);
    
    /* Give it a little time to propagate */
    for(idle = 0; idle < 100; idle++) {
      HWC_IO_LOAD(bInfo->regInfo, status, status);    
    }  

    /* And make sure it's really idle... */
    goto checkforidle;
  }
}
            
FxBool
hwcInitFifo(hwcBoardInfo *bInfo, FxBool enableHoleCounting)
{
#define FN_NAME "hwcInitFifo"
  FxBool
    agpEnable = FXFALSE;  
  FxU32
    cagpRegs;                   /* pointer to Cmd/AGP regs */
#if 0
  /* scratch for the 'fill the fifo' debugging trick */
  FxU32 *filler;
#endif

  if (bInfo->regInfo.initialized == FXFALSE) {
    sprintf(errorString, "%s:  Called before hwcMapBoard\n", FN_NAME);
    return FXFALSE;
  }
  cagpRegs = bInfo->regInfo.cmdAGPBase;

  if (bInfo->buffInfo.initialized == FXFALSE) {
    sprintf(errorString, "%s:  Called before hwcInitBuffers\n", FN_NAME);
    return FXFALSE;
  }

  hwcIdleHardwareWithTimeout(bInfo);

  /* disable the CMD fifo */
  HWC_CAGP_STORE(bInfo->regInfo, cmdFifo0.baseSize, 0);

#if 0
  /* Debugging.  Fill the command fifo with something so we can see if someone
   * else was playing in our sandbox. */
  for(filler = (FxU32 *)(bInfo->fifoInfo.fifoStart + bInfo->regInfo.rawLfbBase);
      filler < (FxU32 *)(bInfo->fifoInfo.fifoStart + bInfo->fifoInfo.fifoLength + bInfo->regInfo.rawLfbBase);
      filler++) {
    *filler = 0xdeadbeef;
  }
#endif

  HWC_CAGP_STORE(bInfo->regInfo, cmdFifo0.baseAddrL,
    bInfo->fifoInfo.fifoStart>>12);
  HWC_CAGP_STORE(bInfo->regInfo, cmdFifo0.readPtrL, bInfo->fifoInfo.fifoStart);
  HWC_CAGP_STORE(bInfo->regInfo, cmdFifo0.readPtrH, 0);
  HWC_CAGP_STORE(bInfo->regInfo, cmdFifo0.aMin, bInfo->fifoInfo.fifoStart-4);
  HWC_CAGP_STORE(bInfo->regInfo, cmdFifo0.aMax, bInfo->fifoInfo.fifoStart-4);
  
  HWC_CAGP_STORE(bInfo->regInfo, cmdFifo0.depth, 0);
  HWC_CAGP_STORE(bInfo->regInfo, cmdFifo0.holeCount, 0);
  /* Fifo LWM /HWM/ THRESHOLD */
  if (bInfo->pciInfo.deviceID == SST_DEVICE_ID_H3) { /* banshee */
    HWC_CAGP_STORE(bInfo->regInfo, cmdFifoThresh,
                   (0x09 << SST_HIGHWATER_SHIFT) | 0x2);
  } else {
    HWC_CAGP_STORE(bInfo->regInfo, cmdFifoThresh,
                   (0xf << SST_HIGHWATER_SHIFT) | 0x8);
  }

  /* Keep writes from actually going to the HW. */
  if(GETENV("FX_GLIDE_NO_HW")) {
    return FXTRUE;
  }

  HWC_CAGP_STORE(bInfo->regInfo, cmdFifo0.baseSize, (((bInfo->fifoInfo.fifoLength >> 12) - 1) | 
                                                     SST_EN_CMDFIFO |
                                                     (enableHoleCounting ? 0 : SST_CMDFIFO_DISABLE_HOLES) |
                                                     (agpEnable ?  SST_CMDFIFO_AGP : 0)));
  
  GDBG_INFO(80, "%s:  CMD FIFO placed at physical addr 0x%x\n", 
            FN_NAME,
            bInfo->fifoInfo.fifoStart);

  return FXTRUE;

#undef FN_NAME
} /* hwcInitFifo */

#if 0
/* Currently unused. */
static SstIORegs savedIORegs;
#endif

void
hwcInitVideoOverlaySurface(
  hwcRegInfo *rInfo,
    FxU32 enable,               /* 1=enable Overlay surface (OS), 1=disable */
    FxU32 stereo,               /* 1=enable OS stereo, 0=disable */
    FxU32 horizScaling,         /* 1=enable horizontal scaling, 0=disable */
    FxU32 dudx,                 /* horizontal scale factor (ignored if not */
      /* scaling) */
    FxU32 verticalScaling,      /* 1=enable vertical scaling, 0=disable */
    FxU32 dvdy,                 /* vertical scale factor (ignored if not */
      /* scaling) */
    FxU32 filterMode,           /* duh */
    FxU32 tiled,                /* 0=OS linear, 1=tiled */
    FxU32 pixFmt,               /* pixel format of OS */
    FxU32 clutBypass,           /* bypass clut for OS? */
    FxU32 clutSelect,           /* 0=lower 256 CLUT entries, 1=upper 256 */
    FxU32 startAddress,         /* board address of beginning of OS */
    FxU32 stride)               /* distance between scanlines of the OS, in */
  /* units of bytes for linear OS's and tiles for */
  /* tiled OS's */
{
  FxU32 doStride;
  FxU32 vidProcCfg;

  HWC_IO_LOAD((*rInfo), vidProcCfg, vidProcCfg);

  vidProcCfg &= ~(SST_OVERLAY_TILED_EN |
                  SST_OVERLAY_STEREO_EN |  
                  SST_OVERLAY_HORIZ_SCALE_EN |
                  SST_OVERLAY_VERT_SCALE_EN |
                  SST_OVERLAY_TILED_EN |
                  SST_OVERLAY_PIXEL_FORMAT |
                  SST_OVERLAY_CLUT_BYPASS |
                  SST_OVERLAY_CLUT_SELECT);

  if (enable)
    vidProcCfg |= SST_OVERLAY_EN;

  if (stereo)
    vidProcCfg |= SST_OVERLAY_STEREO_EN;

  if (horizScaling)
    vidProcCfg |= SST_OVERLAY_HORIZ_SCALE_EN;

  if (verticalScaling)
    vidProcCfg |= SST_OVERLAY_VERT_SCALE_EN;

  if (tiled) {
    vidProcCfg |= SST_OVERLAY_TILED_EN;
  }

  vidProcCfg |= pixFmt; /* pixFmt is preshifted */
  vidProcCfg &= ~SST_CURSOR_EN; /* Turn off HW Cursor */
  vidProcCfg |= SST_OVERLAY_TILED_EN; /* Overlay tile space enable */    


  if (clutBypass)
    vidProcCfg |= SST_OVERLAY_CLUT_BYPASS;

  if (clutSelect)
    vidProcCfg |= SST_OVERLAY_CLUT_SELECT;

  HWC_IO_STORE((*rInfo), vidProcCfg, vidProcCfg);

  /* */
  HWC_IO_LOAD((*rInfo), vidDesktopOverlayStride, doStride);
  doStride &= ~(SST_OVERLAY_LINEAR_STRIDE | SST_OVERLAY_TILE_STRIDE);

  stride <<= SST_OVERLAY_STRIDE_SHIFT;
  if (tiled)
    stride &= SST_OVERLAY_TILE_STRIDE;
  else
    stride &= SST_OVERLAY_LINEAR_STRIDE;
  doStride |= stride;

  HWC_IO_STORE((*rInfo), vidDesktopOverlayStride, doStride);

} /* hwcInitVideoOverlaySurface */

FxU32 
hwcInitLookupRefresh(FxU32 ord_refresh) 
{
#define FN_NAME "hwcInitLookupRefresh"
  FxU32 refresh_hz;

  switch(ord_refresh) {
  case(GR_REFRESH_60Hz):
    refresh_hz = 60;
    break;
  case(GR_REFRESH_70Hz):
    refresh_hz = 70;
    break;
  case(GR_REFRESH_72Hz):
    refresh_hz = 72;
    break;
  case(GR_REFRESH_75Hz):
    refresh_hz = 75;
    break;
  case(GR_REFRESH_80Hz):
    refresh_hz = 80;
    break;
  case(GR_REFRESH_85Hz):
    refresh_hz = 85;
    break;
  case(GR_REFRESH_90Hz):
    refresh_hz = 90;
    break;
  case(GR_REFRESH_100Hz):
    refresh_hz = 100;
    break;
  case(GR_REFRESH_120Hz):
    refresh_hz = 120;
    break;
  default:
    GDBG_ERROR(FN_NAME, "Unsupported Refresh Rate -- defaulting to 60hz\n");
    refresh_hz = 60;
    break;
  }
  return (refresh_hz);
#undef FN_NAME
} /* hwcInitLookupRefresh */

#ifdef HWC_ACCESS_DDRAW

#define LINEAR_STRIDE_ALIGN 16UL

static FxBool
_hwcLinear2HWAddr(const FxU32 linearAddr, 
                  const FxU32 linearBaseAddr,
                  const FxU32 linearStride,
                  const hwcBoardInfo* bInfo,
                  hwcSurfaceInfo* ret)
{
#define FN_NAME "_hwcLinear2HWAddr"
  FxU32
    pciStride,                  /* page stride */
    hwStride,                   /* tile stride */
    tileMark,                   /* delineation between linear and tiled */
    lpTileBase;                 /* linear addr of tileMark */
  FxBool
    retVal = FXFALSE,
    isTiled;                    /* is the surface tiled? */

  /* determine lfb baseAddress and hw offset to buffer */
  {
    hwcExtRequest_t ctxReq;
    hwcExtResult_t  ctxRes;

    /* query for tile watermark & compute tile characteristics */
    ctxReq.which = HWCEXT_GETDEVICECONFIG;
    GDBG_INFO(80, FN_NAME ":  ExtEscape:HWCEXT_GETDEVICECONFIG\n");

    retVal = (ExtEscape(bInfo->hdc, HWCEXT_ESCAPE(bInfo->boardNum),  /**/ 
                        sizeof(ctxReq), (LPSTR)&ctxReq, 
                        sizeof(ctxRes), (LPSTR)&ctxRes) > 0);
    if (!retVal) {
      hwc_errncpy(errorString, "HWCEXT_GETDEVICECONFIG failed");
      GDBG_INFO(80, "%s: %s.\n", FN_NAME, errorString);
      goto __errExit;
    }

    pciStride = ctxRes.optData.deviceConfigRes.pciStride;
    hwStride = ctxRes.optData.deviceConfigRes.hwStride;
    tileMark = ctxRes.optData.deviceConfigRes.tileMark;
    
    lpTileBase = linearBaseAddr + tileMark;
    isTiled = (linearAddr >= lpTileBase);
  }

  ret->pciStride = pciStride;
  ret->tileBase = tileMark;
  ret->lpSurface = linearAddr;
  ret->lpLFB = linearBaseAddr;
  ret->hwStride = hwStride;

  /* Compute things that depend on the offset wrt the tile mark */
  ret->isTiled = isTiled;
  if (ret->isTiled) {
    const FxU32
      tileStride = hwStride,
      tilePitch = pciStride,
      tileOffset = linearAddr - lpTileBase,
      y = tileOffset / tilePitch, 
      x = tileOffset - (y * tilePitch),
      tile = ((y / HWC_TILE_HEIGHT) * tileStride) + (x / HWC_TILE_WIDTH);

    ret->fbOffset = (tile << 12UL) + tileMark;
    ret->fbStride = ret->hwStride | SST_BUFFER_MEMORY_TILED;
  } else {
    /* NB: Banshee (and derivatives) have a 16-byte alignment
     * restriction on the stride and offset for color/aux buffers, but
     * it is left to the client to correctly adjust for this when
     * setting the values.  
     */
    ret->fbOffset = linearAddr - linearBaseAddr;
    ret->fbStride = linearStride;
  }

 __errExit:
  return retVal;
#undef FN_NAME
} /* _hwcLinear2HWAddr */

static FxU32
_hwcPixelFormatToBitDepth(const DDPIXELFORMAT* pixelFormat)
{
#define FN_NAME "_hwcPixelFormatToBitDepth"
  const DWORD
    formatFlags = pixelFormat->dwFlags;
  FxU32 
    retVal = 0x00UL;

  if (formatFlags & DDPF_FOURCC) {
    retVal = 4;
  } else if (formatFlags & DDPF_PALETTEINDEXED8) {
    retVal = 8;
  } else if (formatFlags & DDPF_RGB) {
    retVal = pixelFormat->dwRGBBitCount;
    if ((retVal == 0) || (retVal > 32)) {
      retVal = 0;
      GDBG_INFO(0, FN_NAME": Invalid surface rgb bit count(0x%X)\n",
                pixelFormat->dwRGBBitCount);
    }
  } else {
    GDBG_INFO(0, FN_NAME": Invalid surface pixel format flags(0x%X)\n",
              formatFlags);
  }

  return retVal;
#undef FN_NAME
} /* _hwcPixelFormatToBitDepth */

/*-------------------------------------------------------------------
  Function: hwcGetSurfaceInfo
  Date: 14-Jul-98
  Implementor(s): dow
  Description:
  Returns information about a Glide (or DDraw) surface

  Arguments:
  
  Return:
  -------------------------------------------------------------------*/
FxBool
hwcGetSurfaceInfo(const hwcBoardInfo* bInfo,
                  FxU32 *sfc, 
                  hwcSurfaceInfo *ret)
{
#define FN_NAME "hwcGetSurfaceInfo"
  /* AssUMe it's a DDraw surface for now */
  LPDIRECTDRAWSURFACE2
    surf = (LPDIRECTDRAWSURFACE2) sfc;
  DDSURFACEDESC
    desc;
  DWORD
    ddErr;
  FxBool 
    retVal;
  FxU32
    lfbBase,                    /* linear addr for base of LFB */
    lpSurface;                  /* Linear addr for the surface */

  /* Lock the surface and get some info */
  desc.dwSize = sizeof(desc);
  ddErr = IDirectDrawSurface2_Lock(surf, 0, &desc, 
                                   DDLOCK_WAIT | DDLOCK_SURFACEMEMORYPTR, 0);
  retVal = (ddErr == DD_OK);
  if (!retVal) {
    sprintf(errorString, "%s: IDirectDrawSurface2_Lock (0x%X)\n", 
            FN_NAME, ddErr);
    GDBG_INFO(80, "%s", errorString);
    goto __errExit;
  }

  /* Grab the memory pointer */
  lpSurface = (DWORD) desc.lpSurface;

  /* Unlock the surface */
  desc.dwSize = sizeof(desc);
  IDirectDrawSurface2_Unlock(surf, desc.lpSurface);

  /* Get surface dimensions here rather than re-getting the surface
   * description later since these should all be valid here.  
   */
  ret->height = desc.dwHeight;
  ret->width  = desc.dwWidth;
  ret->bitdepth  = _hwcPixelFormatToBitDepth(&desc.ddpfPixelFormat);
  retVal = (ret->bitdepth != 0x00UL);
  if (!retVal) {
    sprintf(errorString, "%s: Invalid surface pixel format (0x%X)\n", 
            FN_NAME, desc.ddpfPixelFormat.dwFlags);
    GDBG_INFO(80, "%s", errorString);
    goto __errExit;    
  }

  /* Get base addresses of the board */
  {
    hwcExtRequest_t ctxReq;
    hwcExtResult_t  ctxRes;

    /* This address was set when the board was mapped in hwcMapBoard */
    lfbBase = bInfo->linearInfo.linearAddress[1];
    
    /* The DirectDraw driver may have re-mapped memory different than
     * the 2d driver's hw mapping. We have to figure out the correct
     * hw address for packet offsets and color buffer stuff.  
     */ 

        ctxReq.which = HWCEXT_LINEAR_MAP_OFFSET;
        ctxReq.optData.mapInfoReq.mapAddr = lfbBase;
        ctxReq.optData.mapInfoReq.remapAddr = lpSurface;
        GDBG_INFO(80, FN_NAME ":  ExtEscape:HWCEXT_LINEAR_MAP_OFFSET\n");
    
      retVal = (ExtEscape(bInfo->hdc, HWCEXT_ESCAPE(bInfo->boardNum),     /**/
                          sizeof(ctxReq), (LPCSTR)&ctxReq,
                          sizeof(ctxRes), (LPSTR)&ctxRes) > 0);
      if (!retVal) {
        hwc_errncpy(errorString, "HWCEXT_LINEAR_MAP_OFFSET failed");
        GDBG_INFO(80, "%s: %s.\n", FN_NAME, errorString);
      }
      
      /* lpSurface is now an address relative to the 2d driver's base
       * address as returned by the HWCEXT_GETLINEARADDR callback.  
       */
      
        lpSurface = (lfbBase + ctxRes.optData.mapInfoRes.linAddrOffset);
  }
  if (!retVal) goto __errExit;

  /* Get the rest of the information about the hw relative address
   * from the linear address's location in memory.
   */
  retVal = _hwcLinear2HWAddr(lpSurface, 
                             lfbBase,
                             desc.lPitch,
                             bInfo,
                             ret);

 __errExit:  
  return retVal;
#undef FN_NAME
} /* hwcGetSurfaceInfo */

FxU32
hwcAllocWinContext(hwcBoardInfo* bInfo)
{
#define FN_NAME "hwcAllocWinContext"
  FxU32
    retVal = 0x00UL;

  hwcExtRequest_t ctxReq;
  hwcExtResult_t  ctxRes;

  /* Allocate a context with the Driver */
  ctxReq.which = HWCEXT_ALLOCCONTEXT;
  ctxReq.optData.allocContextReq.protocolRev = HWCEXT_PROTOCOLREV;
  ctxReq.optData.allocContextReq.appType = HWCEXT_ABAPPTYPE_WIND;
  GDBG_INFO(80, FN_NAME ":  ExtEscape:HWCEXT_ALLOCCONTEXT\n");

  if (ExtEscape(bInfo->hdc, HWCEXT_ESCAPE(bInfo->boardNum), /**/
                sizeof(ctxReq), (LPSTR)&ctxReq,
                sizeof(ctxRes), (LPSTR)&ctxRes) < 1) {
    hwc_errncpy(errorString, FN_NAME": HWCEXT_ALLOCCONTEXT failed");
  } else {
    retVal = ctxRes.optData.allocContextRes.contextID;
  }    

  return retVal;
#undef FN_NAME
} /* hwcAllocWinContext */

FxBool
hwcFreeWinContext(hwcBoardInfo* bInfo,
                  FxU32         winContextId)
{
#define FN_NAME "hwcFreeWinContext"
  hwcExtRequest_t ctxReq;
  hwcExtResult_t  ctxRes;

  ctxReq.which = HWCEXT_RELEASECONTEXT;
  ctxReq.optData.releaseContextReq.contextID = winContextId;
  GDBG_INFO(80, FN_NAME ":  ExtEscape:HWCEXT_RELEASECONTEXT\n");

  bInfo->isMapped = FXFALSE ;

  return (ExtEscape(bInfo->hdc, HWCEXT_ESCAPE(bInfo->boardNum),     /**/
                      sizeof(ctxReq), (void*)&ctxReq,
                      sizeof(ctxRes), (void*)&ctxRes) > 0);
#undef FN_NAME
} /* hwcFreeWinContext */

static HRESULT CALLBACK
enumSurfaceCallback(LPDIRECTDRAWSURFACE ddSurface, 
                    LPDDSURFACEDESC ddDesc, 
                    LPVOID procData)
{
  HRESULT retVal = DDENUMRET_OK;

  if (((ddDesc->dwFlags & DDSD_CAPS) != 0x00UL) &&
      ((ddDesc->ddsCaps.dwCaps & DDSCAPS_PRIMARYSURFACE) != 0x00UL)) {

    *(DDSURFACEDESC*)procData = *ddDesc;
    retVal = DDENUMRET_CANCEL;
  }

  /* The surface's refcount is bumped so we need to release since we
   * really only care about the surface's properties.
   */
  IDirectDrawSurface_Release(ddSurface);

  return retVal;
}


FxBool 
hwcAllocWinFifo(hwcBoardInfo* bInfo, 
                HwcWinFifo*   fifo,
                FxU32*        surface)
{
#define FN_NAME "hwcAllocWinFifo"
  FxBool 
    retVal = FXFALSE;
  FxU32 fifoType;

  hwcExtRequest_t ctxReq;
  hwcExtResult_t  ctxRes;

  DDSURFACEDESC
    primaryDesc;


  /* Set undefined fifo type to start, and always clear the serial
   * number for this context.
   */
  fifo->fifoType = 0xFFFFFFFFUL;

  /* Check to see that we have valid surface owner to hang
   * the command fifo surface off of.
   */
  retVal = (surface != NULL);
  if (retVal) {
    LPDIRECTDRAW
      objDD = NULL;
    LPDIRECTDRAWSURFACE
      objSentinal = NULL,
      objFifo = NULL;
    DDSURFACEDESC
      fifoDesc,
      sentinalDesc;
    DWORD
      surfaceWidth;

    /* Get the surface owner so that we can try to allocate a new
     * surface for the fifo. On windows this will be a direct draw
     * object, and we need a dd4 object for agp surfaces.
     */
    {
      LPDIRECTDRAWSURFACE2
        objSurface = NULL;
      
      /* Make sure that this is a Surface2 object so that we can get
       * the DirectDraw object that owns this surface and piggy back
       * our objects ontop of it.
       */
      retVal = (IDirectDrawSurface_QueryInterface((LPDIRECTDRAWSURFACE)surface, 
                                                  &IID_IDirectDrawSurface2,
                                                  &objSurface) == DD_OK);
      if (!retVal) {
        GDBG_INFO(80, "%s: Require atleast IDirectDrawSurface2.\n", FN_NAME);
        goto __errSurfaceFifo;
      }
      
      /* Get the dd object for the surface creation */
      retVal = (IDirectDrawSurface2_GetDDInterface(objSurface, &objDD) == DD_OK);
      if (!retVal) {
        GDBG_INFO(80, "%s: Could not acquire DirectDraw object.\n", FN_NAME);
        goto __errSurfaceDDObj;
      }

                                    
  __errSurfaceDDObj:
      if (objSurface != NULL) IDirectDrawSurface_Release(objSurface);
      if (!retVal) goto __errSurfaceFifo;
    }

    /* Is the 2d command fifo in agp or local frame buffer space? */
    memset(&ctxReq, 0, sizeof(ctxReq));
    memset(&ctxRes, 0, sizeof(ctxRes));
 
    ctxReq.which = HWCEXT_FIFOINFO;
    GDBG_INFO(80, FN_NAME ":  ExtEscape:HWCEXT_FIFOINFO\n");

    retVal = (ExtEscape((HDC)bInfo->hdc, HWCEXT_ESCAPE(bInfo->boardNum),       /**/
                        sizeof(ctxReq), (void*)&ctxReq,
                        sizeof(ctxRes), (void*)&ctxRes) > 0);
    if (!retVal) {
      GDBG_INFO(80, "%s: HWCEXT_FIFOINFO failed to determine current 2d fifo type.\n",
                FN_NAME);
      goto __errSurfaceFifo;
    }

    fifoType = ctxRes.optData.fifoInfoRes.fifoType;

    /* Basic surface type for the fifo */
    memset(&fifoDesc, 0, sizeof(fifoDesc));
    fifoDesc.dwSize  = sizeof(fifoDesc);
    fifoDesc.dwFlags = (DDSD_CAPS | 
                        DDSD_WIDTH | DDSD_HEIGHT |
                        DDSD_PITCH | 
                        DDSD_PIXELFORMAT);

    /* We want the command fifo someplace that the hw can get to
     * directly. Whether this is is local to the board or agp is
     * controlled by where the 2d driver has its fifo.  
     */
    fifoDesc.ddsCaps.dwCaps = (DDSCAPS_OFFSCREENPLAIN |
                               DDSCAPS_VIDEOMEMORY);

    {
      DDCAPS
        ddCaps;
      /* Figure out the things that the current DirectDraw driver
       * knows about. We need to know whether it can support creating
       * agp and wider than primary surfaces.  
       */
      memset(&ddCaps, 0, sizeof(ddCaps));
      ddCaps.dwSize = sizeof(ddCaps);
      
      retVal = (IDirectDraw_GetCaps(objDD, &ddCaps, NULL) == DD_OK);
      if (!retVal) {
        GDBG_INFO(80, "%s: Could not determine if DirectDraw handles separate memory types.\n",
                  FN_NAME);
        goto __errSurfaceFifo;
      }
      
      /* Make the fifo type match the 2d fifo type if the driver can
       * handle different memory types.  
       */

      switch (fifoType) {        
      case HWCEXT_FIFO_AGP:
        if ((ddCaps.dwCaps2 & DDCAPS2_NONLOCALVIDMEM) != 0x00UL) {
          fifoDesc.ddsCaps.dwCaps |= DDSCAPS_NONLOCALVIDMEM;
        } else {
          GDBG_INFO(80, "%s: AGP fifo w/o DirectDraw support for AGP surfaces.\n", FN_NAME);
          retVal = FXFALSE;
        }
        break;

      case HWCEXT_FIFO_FB:
        if ((ddCaps.ddsCaps.dwCaps & DDSCAPS_LOCALVIDMEM) != 0x00UL) 
          fifoDesc.ddsCaps.dwCaps |= DDSCAPS_LOCALVIDMEM;
        break;
        
      case HWCEXT_FIFO_HOST:
      default:
        GDBG_INFO(80, "%s: Unknown driver fifo type.\n", FN_NAME);
        retVal = FXFALSE;
        break;
      }
      if (!retVal) goto __errSurfaceFifo;

      /* Get the primary surface so that we can figure out other whacked
       * surface creation constraints taht we have to adhere to. 
       */
      primaryDesc.dwSize = 0x00UL;
      retVal = (IDirectDraw_EnumSurfaces(objDD,
                                         DDENUMSURFACES_DOESEXIST | DDENUMSURFACES_ALL,
                                         NULL, 
                                         &primaryDesc,
                                         enumSurfaceCallback) == DD_OK);
      if (!retVal || (primaryDesc.dwSize == 0x00UL)) {
        GDBG_INFO(80, "%s: Could not find primary surface.\n", FN_NAME);
        goto __errSurfaceFifo;
      }

      /* If the DirectDraw driver supports wide surfaces then we can
       * specify what will align well w/ the underlying hw's page
       * size.  Otherwise we need to check the primary surface's
       * dimensions to fit the 'old' rule that no surface's dimensions
       * can exceed the primary's. After we allocate the surface we
       * check to make sure that the width and stride are the 'same'
       * since it is probably not a good thing to use the 'slop' when
       * the stride > width.
       */
      if ((ddCaps.dwCaps2 & DDCAPS2_WIDESURFACES) == 0x00UL) {
        retVal = ((primaryDesc.dwFlags & DDSD_WIDTH) != 0x00UL);
        if (!retVal) {
          GDBG_INFO(80, "%s: Primary surface does not have width.\n", FN_NAME);
          goto __errSurfaceFifo;
        }
        surfaceWidth = primaryDesc.dwWidth;
      } else {
        GDBG_INFO(80, "%s: DirectDraw supports wide surfaces.\n", FN_NAME);
        surfaceWidth = (0x1000UL >> 2UL);
      }
    }

    /* Allocate a sentinal surface so that the client can 'know' when
     * a given fifo segment has actually been executed by reading a
     * client specified serial # out of the buffer. This only needs to
     * be big enough to hold the size of a serial #, but we need to
     * work around some sort of whacked agp bug when reading back. See
     * hwcExecuteStatusWinFifo() for details.
     */
      fifoDesc = primaryDesc;
      fifoDesc.ddsCaps.dwCaps = (DDSCAPS_OFFSCREENPLAIN |
                               DDSCAPS_VIDEOMEMORY);
      fifoDesc.dwFlags = (DDSD_CAPS | 
                        DDSD_WIDTH | DDSD_HEIGHT |
                        DDSD_PITCH | 
                        DDSD_PIXELFORMAT);

      sentinalDesc = fifoDesc;
        {
                int Size;
                switch( sentinalDesc.ddpfPixelFormat.dwRGBBitCount )
                {
                        case 8:
                                Size = 16;
                                break;
                        case 16:
                                Size = 8;
                                break;
                        case 24:
                                Size = 6;
                                break;
                        default:        
                                Size = 4;
                }
            sentinalDesc.dwHeight = Size;
                sentinalDesc.dwWidth  = Size;
        }    
    retVal = (IDirectDraw_CreateSurface(objDD,
                                        &sentinalDesc,
                                        &objSentinal,
                                        0) == DD_OK);
    if (!retVal) {
      GDBG_INFO(80, "%s: Could not allocate surface for serial #'s.\n", FN_NAME);
      goto __errSurfaceFifo;
    }

    /* Make stride and width the 'same' so that we get the entire
     * surface as teh command fifo for the hw to just jsr to.
     */
    fifoDesc.dwWidth = surfaceWidth;
    fifoDesc.lPitch  = (fifoDesc.dwWidth*(fifoDesc.ddpfPixelFormat.dwRGBBitCount>>3) );

    /* Try to allocate a surface that contains some # of command
     * stream and persistant state buffers. This is
     * allocated in hw page units (4k) rather than the client
     * allocation units, but that should be transparent since
     * the client will just not use the extra slop.
     */
#define MAX(__a, __b) (((__a) > (__b)) ? (__a) : (__b))
    {
      const FxU32
        allocFifo  = MAX(fifo->cmdBuf.allocUnit, 0x1000UL),
        allocState = MAX(fifo->stateBuf.allocUnit, 0x1000UL),
        allocUnit  = pow2Round(allocFifo + allocState + 0xFFFUL, 0x1000UL);
      const char*
        numAllocStr = GETENV("FX_WINFIFO_INIT_ALLOC");
      FxU32
        numAlloc   = ((numAllocStr == NULL)
                      ? 0x8UL
                      : atoi(numAllocStr));
      DWORD 
        ddErr;

      while(numAlloc > 0) {
        fifoDesc.dwHeight = (allocUnit * numAlloc) / fifoDesc.lPitch;
        ddErr = IDirectDraw_CreateSurface(objDD,
                                          &fifoDesc,
                                          &objFifo,
                                          0);

        if (ddErr == DD_OK)
        {
          /* AJB- Check for tiled fifo */
          hwcSurfaceInfo       theSurfaceInfo ; 
       
          hwcGetSurfaceInfo(bInfo, (DWORD*)objFifo, &theSurfaceInfo) ;
          retVal = (theSurfaceInfo.isTiled == FXFALSE) ;
        }

        if (retVal) break;

        if ((ddErr != DDERR_OUTOFVIDEOMEMORY) ||
            (ddErr != DDERR_OUTOFMEMORY)) break;

        /* Try a smaller allocation */
        numAlloc--;
      }
      if (!retVal) {
        GDBG_INFO(80, "%s: Could not get cmdFifo DirectDraw surface. (0x%X)\n",
                  FN_NAME, ddErr);
        goto __errSurfaceFifo;
      }

      /* Fill in the fifo type for lock. */
      fifo->fifoType = fifoType;
      
      /* Do the lock so that we can write the sentinal, but the
       * client is responsible for locking before use.
       */
          fifo->surfaceFifo     = (FxU32*)objFifo;
          fifo->surfaceSentinal = (FxU32*)objSentinal;

      retVal = hwcLockWinFifo(bInfo, fifo);
      if (!retVal) goto __errSurfaceFifo;
      
      /* Write bogus serial #. */
      *(volatile FxU32*)fifo->sentinalBufferAddr = 0x0UL;    
      hwcUnlockWinFifo(bInfo, fifo);
      
      /* Its now safe to overwrite the client allocUnit's to the
       * rounded allocation units because we've finally done all of
       * the stuff that could fail.
       */
      fifo->cmdBuf.size = allocFifo * numAlloc;
      fifo->cmdBuf.allocUnit = allocFifo;
      
      fifo->stateBuf.size = allocState * numAlloc;
      fifo->stateBuf.allocUnit = allocState;      
    }
#undef MAX
    
 __errSurfaceFifo:
    /* Free our directdraw objects if something bad happened. */
    if (!retVal) {
      if (objSentinal != NULL) IDirectDrawSurface_Release(objSentinal);
      if (objFifo != NULL) IDirectDrawSurface_Release(objFifo);
    }
    if (objDD != NULL) IDirectDraw_Release(objDD);
  }

  /* Could not allocate directly accessible fifo so setup the host
   * memory backed fifo which will get dumped at execute time.  
   */
  if (!retVal && (bInfo->hdc != 0x00UL)) {
    fifo->fifoType          = HWCEXT_FIFO_HOST;

    fifo->cmdBuf.hwOffset    = 0x00UL;
    fifo->cmdBuf.size   = fifo->cmdBuf.allocUnit;
    fifo->stateBuf.hwOffset  = 0x00UL;
    fifo->stateBuf.size = fifo->stateBuf.allocUnit;

    /* This can never fail since the client is responsible for
     * allocating this memory.  
     */
    retVal = FXTRUE;
  }

  GDBG_INFO(80, "%s: retVal(0x%X) Type(0x%X)\n", 
            FN_NAME, retVal, fifo->fifoType);

  return retVal;
#undef FN_NAME
} /* hwcAllocWinFifo */

FxBool
hwcLockWinFifo(hwcBoardInfo* bInfo,
               HwcWinFifo* fifo)
{
#define FN_NAME "hwcLockWinFifo"
  FxBool 
    retVal = FXFALSE;

  if (fifo->fifoType == HWCEXT_FIFO_HOST) {
    retVal = FXTRUE;
  } else if ((fifo->fifoType == HWCEXT_FIFO_FB) ||
             (fifo->fifoType == HWCEXT_FIFO_AGP)) {
    DDSURFACEDESC
      fifoDesc,
      sentinalDesc;

    if (fifo->lockCount > 0) goto __alreadyLocked;
    if ((fifo->surfaceFifo == NULL) ||
        (fifo->surfaceSentinal == NULL)) goto __errFifoLock;

    /* Get base pointer to the fifo surfaces.
     *
     * NB: In theory we should leave these locked for the duration of
     * the of the fifo lock and we would need to set the
     * DDLOCK_NOSYSLOCK flag when doing the lock. However, when we do
     * this type of lock the directDraw driver re-maps the physical
     * address to a new set of linear address pages. So we take advantage
     * of the fact taht the current implementation will not move memory
     * behind our backs outside of a surface lock.
     */
#define HWC_DIRECTDRAW_DRIVER_NOSYSLOCK_FLAGS 0 
    fifoDesc.dwSize = sizeof(fifoDesc);
    retVal = (IDirectDrawSurface_Lock((LPDIRECTDRAWSURFACE)fifo->surfaceFifo,
                                      NULL, 
                                      &fifoDesc, 
                                      HWC_DIRECTDRAW_DRIVER_NOSYSLOCK_FLAGS |
                                      DDLOCK_SURFACEMEMORYPTR | DDLOCK_WAIT,
                                      NULL) == DD_OK);

    /* NB: Since there's no working DDLOCK_NOSYSLOCK we unlock the surface
     * here, and rely on the current implementation to leave the linear 
     * mapping to the hw intact after the unlocking.
     */
    IDirectDrawSurface_Unlock((LPDIRECTDRAWSURFACE)fifo->surfaceFifo, NULL);
    if (!retVal) {
      hwc_errncpy(errorString, "Could not lock cmdFifo surface");
      GDBG_INFO(80, "%s: %s.\n", FN_NAME, errorString);
      goto __errFifoLock;
    }

    sentinalDesc.dwSize  = sizeof(sentinalDesc);
    retVal = (IDirectDrawSurface_Lock((LPDIRECTDRAWSURFACE)fifo->surfaceSentinal, 
                                      NULL, 
                                      &sentinalDesc, 
                                      HWC_DIRECTDRAW_DRIVER_NOSYSLOCK_FLAGS |
                                      DDLOCK_SURFACEMEMORYPTR | DDLOCK_WAIT, 
                                      NULL) == DD_OK);

    /* NB: Since there's no working DDLOCK_NOSYSLOCK we unlock the surface
     * here, and rely on the current implementation to leave the linear 
     * mapping to the hw intact after the unlocking.
     */
    IDirectDrawSurface_Unlock((LPDIRECTDRAWSURFACE)fifo->surfaceSentinal, NULL);
    if (!retVal) {
      hwc_errncpy(errorString, "Could not lock serial # surface");
      GDBG_INFO(80, "%s: %s.\n", FN_NAME, errorString);
      goto __errFifoLock;
    }

    fifo->cmdBuf.baseAddr   = (FxU32)fifoDesc.lpSurface;
    fifo->stateBuf.baseAddr = (fifo->cmdBuf.baseAddr + 
                                      fifo->cmdBuf.size);
    fifo->sentinalBufferAddr       = (FxU32)sentinalDesc.lpSurface;

    /* The DirectDraw driver may have re-mapped memory different than
     * the 2d driver's hw mapping. We have to figure out the correct
     * hw address for packet offsets and color buffer stuff.  
     */
    {
      hwcExtRequest_t ctxReq;
      hwcExtResult_t  ctxRes;

      const FxU32
        lfbBase = bInfo->linearInfo.linearAddress[1]; /* lfb space */
      FxU32
        tileMark;      
      
      /* query for tile watermark & compute tile characteristics */
      ctxReq.which = HWCEXT_GETDEVICECONFIG;
      GDBG_INFO(80, FN_NAME ":  ExtEscape:HWCEXT_GETDEVICECONFIG\n");
      
      retVal = (ExtEscape((HDC)bInfo->hdc, HWCEXT_ESCAPE(bInfo->boardNum), /**/
                          sizeof(ctxReq), (LPSTR)&ctxReq, 
                          sizeof(ctxRes), (LPSTR)&ctxRes) > 0);
      if (!retVal) {
        hwc_errncpy(errorString, "HWCEXT_GETDEVICECONFIG failed");
        GDBG_INFO(80, "%s: %s.\n", FN_NAME, errorString);
        goto __errFifoLock;
      }
      
      tileMark = ctxRes.optData.deviceConfigRes.tileMark;
      

      {
        struct remapRec {
          FxU32  remapAddr;
          FxU32* remapOffset;
          FxU32  surfaceType;
        } remapAddrList[] = {
          {    fifo->cmdBuf.baseAddr,      &fifo->cmdBuf.hwOffset, fifo->fifoType },
          {  fifo->stateBuf.baseAddr,    &fifo->stateBuf.hwOffset, fifo->fifoType },
          { fifo->sentinalBufferAddr, &fifo->sentinalBufferOffset, HWCEXT_FIFO_FB }
        };
        FxU32 i;

        for(i = 0; i < sizeof(remapAddrList) / sizeof(remapAddrList[0]); i++) {
          FxU32 hwOffset;

          ctxReq.which = HWCEXT_LINEAR_MAP_OFFSET;
          ctxReq.optData.mapInfoReq.mapAddr = lfbBase;
          ctxReq.optData.mapInfoReq.remapAddr = remapAddrList[i].remapAddr;
          GDBG_INFO(80, FN_NAME ":  ExtEscape:HWCEXT_LINEAR_MAP_OFFSET\n");

          retVal = (ExtEscape((HDC)bInfo->hdc, HWCEXT_ESCAPE(bInfo->boardNum), /**/
                              sizeof(ctxReq), (LPCSTR)&ctxReq,
                              sizeof(ctxRes), (LPSTR)&ctxRes) > 0);
          if (!retVal) {
            hwc_errncpy(errorString, "HWCEXT_LINEAR_MAP_OFFSET failed");
            GDBG_INFO(80, "%s: %s.\n", FN_NAME, errorString);
            goto __errFifoLock;
          }

          /* Make sure we have the right offset for tiled/linear addresses */
          hwOffset = ctxRes.optData.mapInfoRes.linAddrOffset;
          
          if ((remapAddrList[i].surfaceType == HWCEXT_FIFO_FB) && (hwOffset >= tileMark)) {
            hwcSurfaceInfo surfaceInfo;

            retVal = _hwcLinear2HWAddr(remapAddrList[i].remapAddr, 
                                       remapAddrList[i].remapAddr - hwOffset,
                                       0x00UL,
                                       bInfo,
                                       &surfaceInfo);
            if (!retVal) goto __errFifoLock;
            hwOffset = surfaceInfo.fbOffset;
          }
          *remapAddrList[i].remapOffset = hwOffset;
        }
      }
    }

   __alreadyLocked:
    /* Finally, declare success */
    retVal = FXTRUE;
    
   __errFifoLock:
    ;
  }

  if (retVal) fifo->lockCount++;

  return retVal;
#undef FN_NAME
} /* hwcLockWinFifo */

FxBool
hwcUnlockWinFifo(hwcBoardInfo* bInfo,
                 HwcWinFifo* fifo)
{
#define FN_NAME "hwcUnlockWinFifo"
  FxBool
    retVal = ((fifo->lockCount > 0) &&
              ((fifo->fifoType == HWCEXT_FIFO_HOST) ||
               (fifo->fifoType == HWCEXT_FIFO_FB) ||
               (fifo->fifoType == HWCEXT_FIFO_AGP)));

  if (retVal) {
    fifo->lockCount--;

    if (fifo->lockCount == 0) {
      if ((fifo->fifoType == HWCEXT_FIFO_FB) ||
          (fifo->fifoType == HWCEXT_FIFO_AGP)) {
        /* Do nothing for now since the surfaces were unlocked in
         * hwcLockWinFifo since we're not using the NOSYSLOCK flags
         * when doing the DirectDraw surface lock.  
         */
      }
    }
  }

  return retVal;
#undef FN_NAME
} /* hwcUnlockWinFifo */

FxBool
hwcFreeWinFifo( hwcBoardInfo* bInfo,
                HwcWinFifo* fifo )
{
#define FN_NAME "hwcFreeWinFifo"

  /* What type of fifo do we have? */
  if ((fifo->fifoType == HWCEXT_FIFO_FB) ||
      (fifo->fifoType == HWCEXT_FIFO_AGP)) {
    if (fifo->surfaceFifo != NULL) {
      LPDIRECTDRAWSURFACE
        objFifo = (LPDIRECTDRAWSURFACE)fifo->surfaceFifo;

      IDirectDrawSurface_Release(objFifo);

      fifo->surfaceFifo = NULL;
      fifo->cmdBuf.baseAddr = 
      fifo->cmdBuf.hwOffset = 
      fifo->cmdBuf.size = 
      fifo->stateBuf.baseAddr = 
      fifo->stateBuf.hwOffset = 0x00UL;
    }
    
    if (fifo->surfaceSentinal != NULL) {
      LPDIRECTDRAWSURFACE
        objSentinal = (LPDIRECTDRAWSURFACE)fifo->surfaceSentinal;

      IDirectDrawSurface_Release(objSentinal);

      fifo->surfaceSentinal = NULL;
      fifo->sentinalBufferAddr =
      fifo->sentinalBufferOffset = 0x00UL;
    }
  }
  
  fifo->fifoType = HWCEXT_FIFO_INVALID;

  return FXTRUE;
#undef FN_NAME
} /* hwcFreeWinFifo */

FxBool
hwcExecuteWinFifo(hwcBoardInfo*     bInfo, 
                  const FxU32       winContextId,
                  const HwcWinFifo* fifo,
                  const FxU32       serialNumber)
{
#define FN_NAME "hwcExecuteWinFifo"

  hwcExtRequest_t ctxReq;
  hwcExtResult_t  ctxRes;

  memset( &ctxReq, 0, sizeof( ctxReq ) );
  memset( &ctxRes, 0, sizeof( ctxRes ) );

  ctxReq.which = HWCEXT_EXECUTEFIFO;
  ctxReq.contextID = winContextId;

  ctxReq.optData.executeFifoReq.fifoType     = fifo->fifoType;

  ctxReq.optData.executeFifoReq.fifoPtr      = fifo->cmdBuf.baseAddr;
  ctxReq.optData.executeFifoReq.fifoSize     = fifo->cmdBuf.size >> 2UL;
  ctxReq.optData.executeFifoReq.statePtr     = fifo->stateBuf.baseAddr;
  ctxReq.optData.executeFifoReq.stateSize    = fifo->stateBuf.size >> 2UL;
  ctxReq.optData.executeFifoReq.serialNumber = serialNumber;

  if (fifo->fifoType != HWCEXT_FIFO_HOST) {
    ctxReq.optData.executeFifoReq.fifoOffset     = fifo->cmdBuf.hwOffset;
    ctxReq.optData.executeFifoReq.stateOffset    = fifo->stateBuf.hwOffset;
    ctxReq.optData.executeFifoReq.sentinalOffset = fifo->sentinalBufferOffset;
  }
  GDBG_INFO(80, FN_NAME": Id(0x%X) state(0x%X) cmd(0x%X)\n",
          winContextId, 
          ctxReq.optData.executeFifoReq.stateSize,
          ctxReq.optData.executeFifoReq.fifoSize);
  GDBG_INFO(80, FN_NAME ":  ExtEscape:HWCEXT_EXECUTEFIFO\n");

  return ( ExtEscape( (HDC)bInfo->hdc, HWCEXT_ESCAPE(bInfo->boardNum),  /**/
                      sizeof( ctxReq ), (void*)&ctxReq, 
                      sizeof( ctxRes ), (void*)&ctxRes )  > 0 );
#undef FN_NAME
} /* hwcExecuteWinFifo */

FxU32
hwcExecuteStatusWinFifo(hwcBoardInfo*     bInfo,
                        const HwcWinFifo* fifo,
                        const FxU32       serialNumber)
{
#define FN_NAME "hwcExecuteStatusWinFifo"
  FxU32
    retVal = ~0x00UL;

  switch(fifo->fifoType) {
  /* Host fifo always executes synchronously */
  case HWCEXT_FIFO_HOST:
    retVal = serialNumber;
    break;

  case HWCEXT_FIFO_FB:
  case HWCEXT_FIFO_AGP:
    {
      volatile FxU32*
        bufAddr = (volatile FxU32*)fifo->sentinalBufferAddr;

      /* We need to do some extra reads here so that we make sure taht
       * the data we're returning is coherent w/ the actual frame
       * buffer due to the intervening pixel cache. The cache is,
       * currently, 4 dwords, and appears to be aligned on this
       * boundary as well so reading 4 dwords away should be flushing.
       *
       * NB: The surface for the serial # was allocated big enough to
       * handle this so we would not have to worry about it here.  
       */
      retVal = bufAddr[0];
      retVal = bufAddr[0 + 4];
      retVal = bufAddr[0];
    }
    break;

  case HWCEXT_FIFO_INVALID:
  default:
    GDBG_ERROR(FN_NAME, "Invalid fifoType");
    break;
  }

  return retVal;
#undef FN_NAME
} /* hwcExecuteStatusWinFifo */

#endif /* HWC_ACCESS_DDRAW */

#ifdef HWC_ACCESS_GDX

#if GLIDE3
FxBool
hwcGetSurfaceInfo(const hwcBoardInfo* bInfo,
                  FxU32 *sfc, 
                  hwcSurfaceInfo *ret)
{
  GrSurfaceDesc_t desc;
  
  hrmDeviceConfig_t config;
  
  _hrmGetDeviceConfig((hrmBoard_t *)bInfo->hMon, &config);
  
  ret->tileBase  = config.tileMark;
  ret->lpLFB     = config.lfbBase;
  ret->pciStride = config.pciStride;
  ret->hwStride  = config.hwStride;
  
  gdxSurfaceGetDesc(sfc, &desc);
  
  ret->lpSurface = desc.surface;
  ret->width = desc.width;
  ret->height = desc.height;
  ret->bitdepth = desc.bytesPerPixel * 8;
  ret->fbStride = desc.pitch;
  ret->fbOffset = ret->lpSurface - ret->lpLFB;
  ret->isTiled = (ret->fbOffset >= ret->tileBase) ? FXTRUE : FXFALSE;
  
  return FXTRUE;
} /* hwcGetSurfaceInfo */
#endif

FxU32
hwcAllocWinContext(hwcBoardInfo* bInfo)
{       
  return _hrmAllocWinContext((hrmBoard_t *)bInfo->hMon);  
} /* hwcAllocWinContext */

FxBool
hwcFreeWinContext(hwcBoardInfo* bInfo,
                  FxU32         winContextId)
{
  _hrmFreeWinContext((hrmBoard_t *)bInfo->hMon, winContextId);
  return FXTRUE;  
} /* hwcFreeWinContext */

#if GLIDE3
FxBool 
hwcAllocWinFifo(hwcBoardInfo* bInfo, 
                HwcWinFifo*   fifo,
                FxU32*        surface)
{
#define FN_NAME "hwcAllocWinFifo"
  FxBool 
    retVal = FXFALSE;

  /* Set undefined fifo type to start, and always clear the serial
   * number for this context.
   */
  fifo->fifoType = 0xFFFFFFFFUL;

  /* Check to see that we have valid surface owner to hang
   * the command fifo surface off of.
   */
  retVal = (surface != NULL);
  if (retVal) {
    hrmBoard_t *theBoard;
    GrSurface_t objSentinal = NULL,
                objFifo = NULL;
    GrSurfaceDesc_t
                fifoDesc,
                sentinalDesc;
                 
    /* We always create our surfaces based on the bInfo */
    theBoard = (hrmBoard_t *)bInfo->hMon;

    memset(&fifoDesc, 0, sizeof(fifoDesc));

    /* Allocate a sentinal surface so that the client can 'know' when
     * a given fifo segment has actually been executed by reading a
     * client specified serial # out of the buffer. This only needs to
     * be big enough to hold the size of a serial #, but we need to
     * work around some sort of whacked agp bug when reading back. See
     * hwcExecuteStatusWinFifo() for details.
     */
    sentinalDesc = fifoDesc;

    sentinalDesc.height = 4*4;
    sentinalDesc.width  = 4;
    sentinalDesc.bytesPerPixel = 1;
    
    objSentinal = gdxSurfaceAlloc(bInfo, theBoard, &sentinalDesc);

    
    if (!objSentinal) {
      GDBG_INFO(80, "%s: Could not allocate surface for serial #'s.\n", FN_NAME);
      retVal = FXFALSE;
      goto __errSurfaceFifo;
    }

        /* Assume for now that 2D command fifo is in local framebuffer space */
 
    /* Make pitch and width the same so that indexing is easy. 
     * Setup the allocation in hw page unit sizes. (4k bytes)
     */
    fifoDesc.pitch      = 0x1000UL;
    fifoDesc.width  = (fifoDesc.pitch >> 2UL);
    fifoDesc.bytesPerPixel = 4;
    
    /* Try to allocate a surface that contains some # of command
     * stream buffers and one persistant state buffer. This is
     * allocated in hw page units (4k) rather than the client
     * allocation units, but that should be transparent since
     * the client will just not use the extra slop.
     */
#define MAX(__a, __b) (((__a) > (__b)) ? (__a) : (__b))
    {
      const FxU32
        allocFifo  = MAX(fifo->cmdBuf.allocUnit, 0x1000UL),
        allocState = MAX(fifo->stateBuf.allocUnit, 0x1000UL),
        allocUnit  = pow2Round(allocFifo + allocState + 0xFFFUL, 0x1000UL);
      const char*
        numAllocStr = GETENV("FX_WINFIFO_INIT_ALLOC");
      FxU32
        numAlloc   = ((numAllocStr == NULL)
                      ? 0x8UL
                      : atoi(numAllocStr));

      while(numAlloc > 0) {
        fifoDesc.height = (allocUnit * numAlloc) / fifoDesc.pitch;
        objFifo = NULL;
        /* objFifo = gdxSurfaceAlloc(theBoard,&fifoDesc); */
        if(objFifo)
                break;

        /* Try a smaller allocation */
        numAlloc--;
      }
      if(!objFifo) {
        GDBG_INFO(80, "%s: Could not get cmdFifo GDX Surface.\n",
                  FN_NAME);
        retVal = FXFALSE;
        goto __errSurfaceFifo;
      }
      
      /* Its now safe to overwrite the client allocUnit's to the
       * rounded allocation units because we've finally done all of
       * the stuff that could fail.
       */
      fifo->cmdBuf.size = allocFifo * numAlloc;
      fifo->cmdBuf.allocUnit = allocFifo;

      fifo->stateBuf.size = allocState * numAlloc;
      fifo->stateBuf.allocUnit = allocState;
    }
#undef MAX
      
        retVal = FXTRUE;
    /* Fill in some more of the return buffer info, but were not quite
     * done and ready to declare success until we lock the fifo down.  
     */
    fifo->fifoType = HWCEXT_FIFO_FB;

    fifo->surfaceFifo     = (FxU32*)objFifo;
    fifo->surfaceSentinal = (FxU32*)objSentinal;

    /* Do the lock so that we can write the sentinal, but the
     * client is responsible for locking before use.
     */
    if (hwcLockWinFifo(bInfo, fifo)) {
      /* Write bogus serial # */
      *(volatile FxU32*)fifo->sentinalBufferAddr = 0x0UL;
    
      hwcUnlockWinFifo(bInfo, fifo);
    }
    
 __errSurfaceFifo:
    /* Free our directdraw objects if something bad happened. */
    if (!retVal) {
      if (objSentinal != NULL) gdxSurfaceFree(objSentinal);
      if (objFifo != NULL) gdxSurfaceFree(objFifo);
    }
  }

  /* Could not allocate directly accessible fifo so setup the host
   * memory backed fifo which will get dumped at execute time.  
   */
  if (!retVal) {
    fifo->fifoType          = HWCEXT_FIFO_HOST;

    fifo->cmdBuf.hwOffset    = 0x00UL;
    fifo->cmdBuf.size   = fifo->cmdBuf.allocUnit;
    fifo->stateBuf.hwOffset  = 0x00UL;
    fifo->stateBuf.size = fifo->stateBuf.allocUnit;

    /* This can never fail since the client is responsible for
     * allocating this memory.  
     */
    retVal = FXTRUE;
  }

  return retVal;
#undef FN_NAME
}                

FxBool
hwcLockWinFifo(hwcBoardInfo* bInfo,
               HwcWinFifo* fifo)
{
#define FN_NAME "hwcLockWinFifo"
  FxBool 
    retVal = FXFALSE;

  if (fifo->fifoType == HWCEXT_FIFO_HOST) {
    retVal = FXTRUE;
  } else if ((fifo->fifoType == HWCEXT_FIFO_FB) ||
             (fifo->fifoType == HWCEXT_FIFO_AGP)) {
       
    GrSurfaceDesc_t 
        fifoDesc,
        sentinalDesc;
              
    if (fifo->lockCount > 0) goto __alreadyLocked;
    if ((fifo->surfaceFifo == NULL) ||
        (fifo->surfaceSentinal == NULL)) goto __errFifoLock;

    /* Get base pointer to the fifo surfaces.
     */
     
    gdxSurfaceGetDesc(fifo->surfaceFifo,&fifoDesc);
    gdxSurfaceGetDesc(fifo->surfaceSentinal,&sentinalDesc);
    
    /* Since there's no remapping crap in MacOS, this is easy. */
    fifo->cmdBuf.baseAddr               = fifoDesc.surface; 
    fifo->stateBuf.baseAddr     = fifo->cmdBuf.baseAddr + fifo->cmdBuf.size;
    fifo->sentinalBufferAddr    = sentinalDesc.surface;

        /* Compute hardware offsets as well */
    fifo->cmdBuf.hwOffset =
      fifo->cmdBuf.baseAddr - bInfo->regInfo.rawLfbBase;
    fifo->stateBuf.hwOffset =
      fifo->stateBuf.baseAddr - bInfo->regInfo.rawLfbBase;
    fifo->sentinalBufferOffset =
      fifo->sentinalBufferAddr - bInfo->regInfo.rawLfbBase;
                
    __alreadyLocked:

    /* Finally, declare success */
    retVal = FXTRUE;
    
   __errFifoLock:
    ;
  }
  
  if (retVal) fifo->lockCount++;
  
  return retVal;
#undef FN_NAME
} /* hwcLockWinFifo */

FxBool
hwcUnlockWinFifo(hwcBoardInfo* bInfo,
                 HwcWinFifo* fifo)
{
#define FN_NAME "hwcUnlockWinFifo"
  FxBool
    retVal = ((fifo->lockCount > 0) &&
              ((fifo->fifoType == HWCEXT_FIFO_HOST) ||
               (fifo->fifoType == HWCEXT_FIFO_FB) ||
               (fifo->fifoType == HWCEXT_FIFO_AGP)));

  if (retVal) {
    fifo->lockCount--;

    if (fifo->lockCount == 0) {
      if ((fifo->fifoType == HWCEXT_FIFO_FB) ||
          (fifo->fifoType == HWCEXT_FIFO_AGP)) {
        /* Don't currently do anything since surfaces don't get moved 
         * around yet on MacOS.
         */
      }
    }
  }

  return retVal;
#undef FN_NAME
} /* hwcUnlockWinFifo */

FxBool
hwcFreeWinFifo( hwcBoardInfo* bInfo,
                HwcWinFifo* fifo )
{
#define FN_NAME "hwcFreeWinFifo"

  /* What type of fifo do we have? */
  if ((fifo->fifoType == HWCEXT_FIFO_FB) ||
      (fifo->fifoType == HWCEXT_FIFO_AGP)) {
    if (fifo->surfaceFifo != NULL) {
        gdxSurfaceFree(fifo->surfaceFifo);

      fifo->surfaceFifo = NULL;
      fifo->cmdBuf.baseAddr = 
      fifo->cmdBuf.hwOffset = 
      fifo->cmdBuf.size = 
      fifo->stateBuf.baseAddr = 
      fifo->stateBuf.hwOffset = 0x00UL;
    }
    
    if (fifo->surfaceSentinal != NULL) {
        gdxSurfaceFree(fifo->surfaceSentinal);

      fifo->surfaceSentinal = NULL;
      fifo->sentinalBufferAddr =
      fifo->sentinalBufferOffset = 0x00UL;
    }
  }
  
  fifo->fifoType = HWCEXT_FIFO_INVALID;

  return FXTRUE;
#undef FN_NAME
} /* hwcFreeWinFifo */

FxBool
hwcExecuteWinFifo(hwcBoardInfo*     bInfo, 
                  const FxU32       winContextId,
                  const HwcWinFifo* fifo,
                  const FxU32       serialNumber)
{
  OSErr       myErr;
  hrmExecuteFifoRequest_t executeFifoReq;
  
  executeFifoReq.contextID = winContextId;
  executeFifoReq.fifoType     = fifo->fifoType;
  executeFifoReq.fifoPtr      = fifo->cmdBuf.baseAddr;
  executeFifoReq.fifoSize     = fifo->cmdBuf.size >> 2UL;
  executeFifoReq.statePtr     = fifo->stateBuf.baseAddr;
  executeFifoReq.stateSize    = fifo->stateBuf.size >> 2UL;
  executeFifoReq.serialNumber = serialNumber;
  
  if (fifo->fifoType != HWCEXT_FIFO_HOST) {
    executeFifoReq.fifoOffset     = fifo->cmdBuf.hwOffset;
    executeFifoReq.stateOffset    = fifo->stateBuf.hwOffset;
    executeFifoReq.sentinalOffset = fifo->sentinalBufferOffset;
  }
  
  myErr = _hrmExecuteWinFifo((hrmBoard_t *)bInfo->hMon,&executeFifoReq);
  
  return myErr == noErr ? FXTRUE : FXFALSE;

  
} /* hwcExecuteWinFifo */

FxU32
hwcExecuteStatusWinFifo(hwcBoardInfo*     bInfo,
                        const HwcWinFifo* fifo,
                        const FxU32       serialNumber)
{
#define FN_NAME "hwcExecuteStatusWinFifo"
  FxU32
    retVal = ~0x00UL;

  switch(fifo->fifoType) {
  /* Host fifo always executes synchronously */
  case HWCEXT_FIFO_HOST:
    retVal = serialNumber;
    break;

  case HWCEXT_FIFO_FB:
  case HWCEXT_FIFO_AGP:
    {
      volatile FxU32*
        bufAddr = (volatile FxU32*)fifo->sentinalBufferAddr;

      /* We need to do some extra reads here so that we make sure taht
       * the data we're returning is coherent w/ the actual frame
       * buffer due to the intervening pixel cache. The cache is,
       * currently, 4 dwords, and appears to be aligned on this
       * boundary as well so reading 4 dwords away should be flushing.
       *
       * NB: The surface for the serial # was allocated big enough to
       * handle this so we would not have to worry about it here.  */
      retVal = (bufAddr[0]);
      retVal = (bufAddr[0 + 4]);
      retVal = (bufAddr[0]);
    }
    break;

  case HWCEXT_FIFO_INVALID:
  default:
    GDBG_ERROR(FN_NAME, "Invalid fifoType");
    break;
  }
  
  return retVal;
#undef FN_NAME
}                        
#endif

/* #define LINEAR_STRIDE_ALIGN 16UL */
/* #define TILE_BIT            0x00008000UL */

#endif /* HWC_ACCESS_GDX */

FxBool
hwcInitVideo(hwcBoardInfo *bInfo, FxBool tiled, FxVideoTimingInfo *vidTiming,
             FxU32 pixFmt, FxBool overlay)
{
#define FN_NAME "hwcInitVideo"
#if HWC_EXT_INIT
  FxI32 status;
#endif  
  FxU32
    stride= (tiled) ? bInfo->buffInfo.bufStrideInTiles : bInfo->vidInfo.stride;
  FxU32
    scrWidth, scrHeight,
    ovlWidth, ovlHeight,
    vidProcCfg, vidScreenSize, vidOverlayEndScreenCoord,
    vidOverlayDudx, vidOverlayDvdy,
    pixelShift, bpp,
    dramInit1;

  FxBool
    lfbMemoryConfig,
    miscInit0;

  float
    scale;

#ifdef HWC_EXT_INIT 
    hwcExtRequest_t ctxReq;
    hwcExtResult_t  ctxRes;
#endif
  
   {
      FxU32 refresh;
      static FxU32 refConstToRefreshHz[] =
      {
         60,                       /* GR_REFRESH_60Hz   */
         70,                       /* GR_REFRESH_70Hz   */
         72,                       /* GR_REFRESH_72Hz   */
         75,                       /* GR_REFRESH_75Hz   */
         80,                       /* GR_REFRESH_80Hz   */
         90,                       /* GR_REFRESH_90Hz   */
         100,                      /* GR_REFRESH_100Hz  */
         85,                       /* GR_REFRESH_85Hz   */
         120,                      /* GR_REFRESH_120Hz  */
         0
      };

      if (bInfo->vidInfo.vRefresh > GR_REFRESH_120Hz)
         refresh = 0;
      else
         refresh = bInfo->vidInfo.vRefresh;

      refresh = refConstToRefreshHz[refresh]; /* Make sure we use the table, otherwise
                                               we will always pass 0Hz to setVideoMode */
      if (GETENV("FX_GLIDE_REFRESH"))
         refresh = atoi(GETENV("FX_GLIDE_REFRESH"));

      if ( !setVideoMode( (void*)bInfo->vidInfo.hWnd, 
                        bInfo->vidInfo.xRes,
                        bInfo->vidInfo.yRes,
                        bInfo->h3pixelSize,
                        refresh,
                        bInfo->hMon ) )
      {
         GDBG_INFO(80, "%s:  dxOpen() failed!\n", FN_NAME);
         return FXFALSE;
      }
#if SET_SWIZZLEHACK
      setLfbSwizzleMode(bInfo->regInfo.rawLfbBase,bInfo->regInfo.ioMemBase,8);
#endif
   }

#ifdef HWC_EXT_INIT
   ctxReq.which = HWCEXT_HWCSETEXCLUSIVE;
   ctxReq.optData.linearAddrReq.devNum = 0;
   GDBG_INFO(80, FN_NAME ":  ExtEscape:HWCEXT_HWCSETEXCLUSIVE\n");
  
   ExtEscape((HDC) bInfo->hdc, HWCEXT_ESCAPE(bInfo->boardNum), sizeof(ctxReq), (void *) &ctxReq, /**/
            sizeof(ctxRes), (void *) &ctxRes);
  
   status = ctxRes.resStatus;
  
   if (status != 1)
   {
      hwc_errncpy(errorString,"HWCEXT_HWCSETEXCLUSIVE Failed");
      return FXFALSE;
   }

#else
  /* This is off for now until the rest of the alt-tab type things are done. */
#if 0
  /* Before letting glide party on the hw check to see if we're on a
   * system w/ a 2d environment, and make sure taht its happy about us
   * doing this before dorking w/ things that are going to make it
   * unhappy.  
   */
   if (Dpmi2DEnvironmentP())
   {
      bInfo->hdc = DpmiDeviceContextGet("3DFXVB");
      if (bInfo->hdc == 0x00UL)
         return FXFALSE;

      if (!DpmiDeviceContextDispatch(bInfo->hdc, FxDCIsFullscreenP))
         return FXFALSE;
      if (!DpmiDeviceContextDispatch(bInfo->hdc, FxDCExclusiveLock))
         return FXFALSE;
   }
#endif
#endif
  
   switch(pixFmt)
   {
      case SST_OVERLAY_PIXEL_RGB565D:
      case SST_OVERLAY_PIXEL_RGB565U:
         pixelShift = 1;
         bpp=16;
         break;
      case SST_OVERLAY_PIXEL_RGB1555U:
      case SST_OVERLAY_PIXEL_RGB1555D:        
         pixelShift = 1;
         bpp=15;
         break;
      case SST_OVERLAY_PIXEL_RGB32U:
         pixelShift = 2;
         bpp=32;
         break;
      default:
         GDBG_INFO(80, "%s:  Invalid overlay pixel format: %08lx failed!\n", FN_NAME, pixFmt);
         return FXFALSE;        
   }
   HWC_IO_STORE(bInfo->regInfo, vidOverlayDudxOffsetSrcWidth,
      ((bInfo->vidInfo.xRes << pixelShift) << 19));

   /* Video pixel buffer threshold */
   {
      FxU32 vidPixelBufThold;
      FxU32 thold = 32;

      if (GETENV("SSTVB_PIXTHOLD"))
         thold = atoi(GETENV("SSTVB_PIXTHOLD"));

      thold &= 0x3f;

      vidPixelBufThold = (thold | (thold << 6) | (thold << 12));

      HWC_IO_STORE(bInfo->regInfo, vidPixelBufThold, vidPixelBufThold);
   }

#ifdef __WIN32__
   if (vidTiming)
   {
      hwcExtRequest_t ctxReq;
      hwcExtResult_t ctxRes;

      if( HWCEXT_PROTOCOL(bInfo->boardNum) )
      {
         ctxReq.which = HWCEXT_VIDTIMING;
         ctxReq.optData.vidTimingReq.vidTiming = (void *) vidTiming;
         GDBG_INFO(80, FN_NAME ":  ExtEscape:HWCEXT_VIDTIMING\n");
         ExtEscape((HDC) bInfo->hdc, HWCEXT_ESCAPE(bInfo->boardNum), sizeof(ctxReq), (void *) &ctxReq, /**/
         sizeof(ctxRes), (void *) &ctxRes);
      }
      /* Ignore failure */
   }
#endif

#ifdef __DOS32__
  /* Now call the cinit code */

  h3InitVideoOverlaySurface(
    bInfo->regInfo.ioPortBase,
    FXTRUE,                     /* 1=enable Overlay surface (OS), 1=disable */
    FXFALSE,                    /* 1=enable OS stereo, 0=disable */
    FXFALSE,                    /* 1=enable horizontal scaling, 0=disable */
    0,                          /* horizontal scale factor (ignored if not) */
    FXFALSE,                    /* 1=enable vertical scaling, 0=disable */
    0,                          /* vertical scale factor (ignored if not) */
    0,                          /* Filter mode */
    FXTRUE,                     /* tiled */
    pixFmt,                     /* pixel format of OS */
    FXTRUE,                    /* bypass clut for OS? */
    0,                          /* 0=lower 256 CLUT entries, 1=upper 256 */
    bInfo->buffInfo.colBuffStart0[0],/* board address of beginning of OS */
    stride);                    /* distance between scanlines of the OS, in
                                   units of bytes for linear OS's and tiles for
                                   tiled OS's */
  HWC_IO_STORE(bInfo->regInfo, vidOverlayStartCoords, 0);
  HWC_IO_STORE(bInfo->regInfo, vidOverlayEndScreenCoord,
    (bInfo->vidInfo.yRes  << SST_OVERLAY_Y_SHIFT) |
    (bInfo->vidInfo.xRes & SST_OVERLAY_X) );
#else
  hwcInitVideoOverlaySurface(
    &bInfo->regInfo,
    FXTRUE,                     /* 1=enable Overlay surface (OS), 1=disable */
    FXFALSE,                    /* 1=enable OS stereo, 0=disable */
    FXFALSE,                    /* 1=enable horizontal scaling, 0=disable */
    0,                          /* horizontal scale factor (ignored if not) */
    FXFALSE,                    /* 1=enable vertical scaling, 0=disable */
    0,                          /* vertical scale factor (ignored if not) */
    0,                          /* Filter mode */
    FXTRUE,                     /* tiled */
    pixFmt,                     /* pixel format of OS */
    FXFALSE,                    /* bypass clut for OS? */
    0,                          /* 0=lower 256 CLUT entries, 1=upper 256 */
    bInfo->buffInfo.colBuffStart0[0],/* board address of beginning of OS */
    stride);                    /* distance between scanlines of the OS, in
                                   units of bytes for linear OS's and tiles for
                                   tiled OS's */
  HWC_IO_STORE(bInfo->regInfo, vidOverlayStartCoords, 0);
  
#endif
  
  /* 
     Setup video scaling for half-modes
   */

  /* Get some important info */
  HWC_IO_LOAD(bInfo->regInfo, vidScreenSize, vidScreenSize);
  HWC_IO_LOAD(bInfo->regInfo, vidProcCfg, vidProcCfg);
  HWC_IO_LOAD(bInfo->regInfo, vidOverlayEndScreenCoord, vidOverlayEndScreenCoord);

  scrWidth = (vidScreenSize >> SST_VIDEO_SCREEN_WIDTH_SHIFT) & 0xfff;
  scrHeight = (vidScreenSize >> SST_VIDEO_SCREEN_HEIGHT_SHIFT) & 0xfff;

  ovlWidth = ((vidOverlayEndScreenCoord) >> SST_OVERLAY_X_SHIFT) & 0xfff;
  ovlHeight = ((vidOverlayEndScreenCoord) >> SST_OVERLAY_Y_SHIFT) & 0xfff;  

  ovlWidth += 1;
  ovlHeight += 1;

  /* Check to see if the screen and overlay dimensions match. 
   * There are two cases that can happen in reality.
   *
   * scrXXX > appXXX: This is a 'real' case, and the overlay dimension
   * needs to mag scaled so that it fits the requested size.
   *
   * (scrXXX == appXXX) && (ovlXXX != scrXXX): This is a somewhat artificial
   * case where someone left the overlay set to some value, and these did
   * not get reset in the setVideoMode processing. (For example, if the user is
   * running an application which bus masters data directly to our video overlay
   * when launching a glide application). In this case we need to fiddle w/ the
   * overlay dimension so that it matches the requested resolution.
   *
   * (scrXXX < appXXX): If setVideoMode is actually working correctly, this cannot
   * happen because that code has to know that we can't do min scaling.
   */

  vidOverlayDudx = 0UL;
  if (scrWidth > bInfo->vidInfo.xRes) {
    vidProcCfg |= SST_OVERLAY_HORIZ_SCALE_EN;

    ovlWidth = scrWidth;

    scale = ((float) bInfo->vidInfo.xRes) / ((float) ovlWidth);

    vidOverlayDudx = (FxU32) (scale * ((float) (1 << 20)));
    HWC_IO_STORE(bInfo->regInfo, vidOverlayDudx, vidOverlayDudx);
  } else if (ovlWidth != scrWidth) {
    ovlWidth = scrWidth;
  }

  HWC_IO_STORE(bInfo->regInfo, vidOverlayDudx, vidOverlayDudx);

  vidOverlayDvdy = 0UL;
  if (scrHeight > bInfo->vidInfo.yRes) {
    vidProcCfg |= SST_OVERLAY_VERT_SCALE_EN;

    ovlHeight = scrHeight;

    scale = ((float) bInfo->vidInfo.yRes) / ((float) ovlHeight);

    vidOverlayDvdy = (FxU32) (scale * ((float) (1 << 20)));
    HWC_IO_STORE(bInfo->regInfo, vidOverlayDvdy, vidOverlayDvdy);
  } else if (ovlHeight != scrHeight) {
    ovlHeight = scrHeight;
  }

  HWC_IO_STORE(bInfo->regInfo, vidOverlayDvdy, vidOverlayDvdy);

  vidOverlayEndScreenCoord = (((ovlHeight - 1) << SST_OVERLAY_Y_SHIFT) |
                              ((ovlWidth - 1) << SST_OVERLAY_X_SHIFT));
  HWC_IO_STORE(bInfo->regInfo, vidOverlayEndScreenCoord, vidOverlayEndScreenCoord);

  vidProcCfg &= ~SST_OVERLAY_FILTER_MODE;
  /* 4/30/99 srogers
  ** Adding user support for switching the video filter from 2x2 to 4x1
  */

   if (NULL == GETENV("SSTH3_OVERLAYMODE"))
   {
      /* We are in optimal mode by default */
      if(bInfo->vidInfo.xRes < 1024)
         vidProcCfg |= SST_OVERLAY_FILTER_2X2;
      else
         vidProcCfg |= SST_OVERLAY_FILTER_4X4;
   }
   else
   {
      switch(atoi(GETENV("SSTH3_OVERLAYMODE")))
      {
         default:
         case 1: /* Optimal */
            if(bInfo->vidInfo.xRes < 1024)
               vidProcCfg |= SST_OVERLAY_FILTER_2X2;
            else
               vidProcCfg |= SST_OVERLAY_FILTER_4X4;
            break;
         case 2: /* Normal */
            vidProcCfg |= SST_OVERLAY_FILTER_4X4;
            break;
         case 3: /* High */
            /* make sure that if 2x video mode is enabled, we use the 4x1 filter. */
            if(vidProcCfg & SST_VIDEO_2X_MODE_EN)
               vidProcCfg |= SST_OVERLAY_FILTER_4X4;
            else
               vidProcCfg |= SST_OVERLAY_FILTER_2X2;
            break;
         case -1: /* Disabled */
            break;
      }
   }      
  
  if (bInfo->h3pixelSample < 2)
  {
    vidScreenSize &= ~SST_VIDEO_SCREEN_DESKTOPADDR_FIFO_ENABLE;
    HWC_IO_STORE(bInfo->regInfo, vidScreenSize, vidScreenSize);
    vidProcCfg &= ~(SST_CHROMA_EN|SST_DESKTOP_EN);
  }
  else if (bInfo->h3pixelSample > 1 && bInfo->buffInfo.enable2ndbuffer)
  {
    vidScreenSize |= SST_VIDEO_SCREEN_DESKTOPADDR_FIFO_ENABLE;

    /*
    ** vidProcCfg
    */

    /* enable Chroma Keying */
    vidProcCfg |= SST_CHROMA_EN;

    /* enable desktop surface */
    vidProcCfg |= SST_DESKTOP_EN;

    /* Overlay surface is already enabled above */

    /* set up desktop pixel format */
    /* Also turn off all filtering, as it seems to screw up multi-chip configs. */
    vidProcCfg &= ~(SST_DESKTOP_PIXEL_FORMAT|SST_OVERLAY_FILTER_MODE);
    switch(vidProcCfg & SST_OVERLAY_PIXEL_FORMAT) {
      case SST_OVERLAY_PIXEL_RGB32U:
        vidProcCfg |= SST_DESKTOP_PIXEL_RGB32;
        bpp = 32;
        break;
      case SST_OVERLAY_PIXEL_RGB565D:
      case SST_OVERLAY_PIXEL_RGB565U:
        vidProcCfg |= SST_DESKTOP_PIXEL_RGB565;
        bpp = 16;
        break;
      case SST_OVERLAY_PIXEL_RGB1555D:
      case SST_OVERLAY_PIXEL_RGB1555U:
        vidProcCfg |= SST_DESKTOP_PIXEL_RGB1555U;
        bpp = 15;
        break;
      default:
        GDBG_INFO(80,"Unknown overlay pixel format: %d\n",
          (vidProcCfg & SST_OVERLAY_PIXEL_FORMAT) >> SST_OVERLAY_PIXEL_FORMAT_SHIFT);
    }

    /* Make sure desktop is tiled */
    vidProcCfg |= SST_DESKTOP_TILED_EN;

    HWC_IO_STORE(bInfo->regInfo, vidScreenSize, vidScreenSize);

  } 

  /* Sorry, can only use 4x1 filter in this mode. */
  if ( bInfo->h3nwaySli > 1 ) {
    if(vidProcCfg & SST_OVERLAY_FILTER_MODE) {        
      vidProcCfg &= ~SST_OVERLAY_FILTER_MODE;
      vidProcCfg |= SST_OVERLAY_FILTER_4X4;
    }
  }      
  
  /* Disable video filter in 32-bit mode */
  if(bpp == 32 || bInfo->h3pixelSample > 2) {
    vidProcCfg &= ~SST_OVERLAY_FILTER_MODE;
  }  

  HWC_IO_STORE(bInfo->regInfo, vidProcCfg, vidProcCfg);

  GDBG_INFO(80, FN_NAME ":  Video Overlay Info:\n\
            Screen Width =       0x%x (%d) \n\
            Screen Height =      0x%x (%d) \n\
            Render Width =      0x%x (%d) \n\
            Render Height =     0x%x (%d) \n",
            ovlWidth, ovlWidth, ovlHeight, ovlHeight, 
            bInfo->vidInfo.xRes, bInfo->vidInfo.xRes, 
            bInfo->vidInfo.yRes, bInfo->vidInfo.yRes);
  
  /* Get miscInit0 for y-sub  */
  HWC_IO_LOAD(bInfo->regInfo, miscInit0, miscInit0);

  /* Clear out relavent bits */
  miscInit0 &= ~SST_YORIGIN_TOP;
  miscInit0 |= ((bInfo->vidInfo.yRes - 1)  << SST_YORIGIN_TOP_SHIFT);

  HWC_IO_STORE(bInfo->regInfo, miscInit0, miscInit0);
  
  /* 
  if (IS_NAPALM(bInfo->pciInfo.deviceID)) {
    HWC_IO_STORE(bInfo->regInfo, lfbMemoryConfig, SST_RAW_LFB_UPDATE_CONTROL);
  } 
  */
   
  /* Set up lfbMemoryConfig */
  lfbMemoryConfig =
    SST_RAW_LFB_TILE_BEGIN_PAGE_MUNGE((bInfo->buffInfo.colBuffStart0[0] >> 12))
      | HWC_RAW_LFB_STRIDE
        | (bInfo->buffInfo.bufStrideInTiles << SST_RAW_LFB_TILE_STRIDE_SHIFT);

  GDBG_INFO(80, FN_NAME ":  Setting lfbMemoryConfig to %08ulx\n",
            lfbMemoryConfig);

  HWC_IO_STORE(bInfo->regInfo, lfbMemoryConfig, lfbMemoryConfig);
  
  if (IS_NAPALM(bInfo->pciInfo.deviceID)) {
    HWC_IO_STORE(bInfo->regInfo, lfbMemoryConfig, SST_RAW_LFB_WRITE_CONTROL);
  }
  

  /* Filthy memclock hack */
  if (GETENV("H3_MEM_CLOCK")) {
    int mHz;
    FxU32 pllVal;
    mHz = atoi(GETENV("H3_MEM_CLOCK"));

    switch (mHz) {
    case 50:
      pllVal = 0x2806;
      break;
      
    case 75:
      pllVal = 0x7125;
      break;
      
    case 80:
      pllVal = 0x7925;
      break;

    case 100:
      pllVal = 0x2805;
      break;

    default:
      pllVal = 0;
      gdbg_printf("%s:  Bogus MEMCLOCK setting!\n", FN_NAME);
      break;
    }

    if (pllVal) {
      HWC_IO_STORE(bInfo->regInfo, pllCtrl1, pllVal);
      HWC_IO_STORE(bInfo->regInfo, pllCtrl2, pllVal);
      gdbg_printf("%s:  Setting memory clock to %d MHz\n", FN_NAME,
        mHz);
    }

  }

  /* Set up dramInit1 for triple or double buffering */
  HWC_IO_LOAD(bInfo->regInfo, dramInit1, dramInit1);
  if (bInfo->vidInfo.tripleBuffering)
    dramInit1 |= SST_TRIPLE_BUFFER_EN;
  else
    dramInit1 &= ~SST_TRIPLE_BUFFER_EN;

  HWC_IO_STORE(bInfo->regInfo, dramInit1, dramInit1);

  HWC_IO_STORE(bInfo->regInfo, vidMaxRGBDelta,/* bpp == 15 ? 0x101010 : */ 0x100810);

  HWC_IO_STORE( bInfo->regInfo, vidDesktopOverlayStride,
                ( bInfo->buffInfo.bufStrideInTiles << 16 ) |
                  bInfo->buffInfo.bufStrideInTiles );

  /* initialize pci registers */
#ifdef FX_GLIDE_NAPALM
  /* Force certain things on 4-way baords */
  if(bInfo->pciInfo.numChips == 4) {
    /* For 4-way SLI we must use analog SLI */
    if(bInfo->h3nwaySli == 4) {
      bInfo->h3analogSli = FXTRUE;
    } else if(bInfo->h3nwaySli == 2 && bInfo->h3pixelSample == 4) {
      /* Force digital AA with analog SLI */
      bInfo->h3analogSli = FXFALSE;        
    }    
  }  

#ifdef HWC_EXT_INIT

#ifdef HWC_MINIVDD_HACK
  /*
   * Since I am a lazy bastard, try to use the minivdd to setup SLI/AA mode for
   * multi-chip configurations.
   */
  if (((IS_NAPALM(bInfo->pciInfo.deviceID)) &&
       (bInfo->pciInfo.numChips > 1)) &&
      ((bInfo->h3nwaySli > 1) ||
       (bInfo->h3pixelSample > 2) ||
       (bInfo->h3pixelSample == 2 && !bInfo->buffInfo.enable2ndbuffer)))
  {
    if (bInfo->osNT)
    {
      ctxReq.which = HWCEXT_SLI_AA_REQUEST ;

      /* Request SLI or AA enable */
      ctxReq.optData.sliAAReq.ChipInfo.dwaaEn             = (bInfo->h3pixelSample > 1) ;
      ctxReq.optData.sliAAReq.ChipInfo.dwsliEn            = (bInfo->h3nwaySli > 1) ;

      ctxReq.optData.sliAAReq.ChipInfo.dwsliAaAnalog      = bInfo->h3analogSli ;
      ctxReq.optData.sliAAReq.ChipInfo.dwsli_nlines       = bInfo->h3sliBandHeight;
      ctxReq.optData.sliAAReq.ChipInfo.dwCfgSwapAlgorithm = 1 ; /* What the *F* is this about? */

      /* Fill out the memory configuration. */
      ctxReq.optData.sliAAReq.MemInfo.dwTotalMemory       = bInfo->h3Mem * 1024 * 1024 ;
      ctxReq.optData.sliAAReq.MemInfo.dwTileMark          = bInfo->buffInfo.colBuffStart0[0] ;
      ctxReq.optData.sliAAReq.MemInfo.dwTileCmpMark       = bInfo->buffInfo.colBuffStart0[0] ;

      /* Fill out SLI mode information. */
      ctxReq.optData.sliAAReq.ChipInfo.dwChips            = bInfo->pciInfo.numChips ;

      /* Fill out AA mode information. */
      /* 8xaa */
   	  ctxReq.optData.sliAAReq.ChipInfo.dwaaSampleHigh     = 0;
	  if(bInfo->h3pixelSample == 4)
      	ctxReq.optData.sliAAReq.ChipInfo.dwaaSampleHigh   = 1;
	  else if(bInfo->h3pixelSample == 8)
       	ctxReq.optData.sliAAReq.ChipInfo.dwaaSampleHigh   = 2;

      ctxReq.optData.sliAAReq.MemInfo.dwaaSecondaryColorBufBegin  = bInfo->buffInfo.colBuffStart1[0] ;
      ctxReq.optData.sliAAReq.MemInfo.dwaaSecondaryDepthBufBegin  = bInfo->buffInfo.lfbBuffAddr0[bInfo->buffInfo.nColBuffers];
      ctxReq.optData.sliAAReq.MemInfo.dwaaSecondaryDepthBufEnd    = bInfo->buffInfo.lfbBuffAddr0End[bInfo->buffInfo.nColBuffers];
      ctxReq.optData.sliAAReq.MemInfo.dwBpp = bpp;

      ExtEscape((HDC)bInfo->hdc, HWCEXT_ESCAPE(bInfo->boardNum), 
                sizeof(ctxReq), (LPSTR) &ctxReq,
                sizeof(ctxRes), (LPSTR) &ctxRes);

      /* the w2k miniport doesn't copy this value to the slave chips */
      /* so for now re-write it here */
      HWC_IO_STORE(bInfo->regInfo, vidScreenSize, vidScreenSize);
    }
     else
    {
    DIOC_DATA DIOC_Data;
    SLI_AA_REQUEST Sli_AA_Request;
    HANDLE hDevice;

    /* Request SLI or AA enable */
    Sli_AA_Request.ChipInfo.dwaaEn             = (bInfo->h3pixelSample > 1) ;
    Sli_AA_Request.ChipInfo.dwsliEn            = (bInfo->h3nwaySli > 1) ;

    /* 8xaa */
    Sli_AA_Request.ChipInfo.dwsliAaAnalog      = bInfo->h3analogSli ;
    Sli_AA_Request.ChipInfo.dwsli_nlines       = bInfo->h3sliBandHeight;
    Sli_AA_Request.ChipInfo.dwCfgSwapAlgorithm = 1 ; /* What the *F* is this about? */

    /* Fill out the memory configuration. */
    Sli_AA_Request.MemInfo.dwTotalMemory       = bInfo->h3Mem * 1024 * 1024 ;
    Sli_AA_Request.MemInfo.dwTileMark          = bInfo->buffInfo.colBuffStart0[0] ;
    Sli_AA_Request.MemInfo.dwTileCmpMark       = bInfo->buffInfo.colBuffStart0[0] ;

    /* Fill out SLI mode information. */
    Sli_AA_Request.ChipInfo.dwChips            = bInfo->pciInfo.numChips ;

    /* Fill out AA mode information. */
    /* 8xaa */
    Sli_AA_Request.ChipInfo.dwaaSampleHigh     = 0;
    if(bInfo->h3pixelSample == 4)
      	Sli_AA_Request.ChipInfo.dwaaSampleHigh = 1;
    else if(bInfo->h3pixelSample == 8)
       	Sli_AA_Request.ChipInfo.dwaaSampleHigh = 2;
 
    Sli_AA_Request.MemInfo.dwaaSecondaryColorBufBegin  = bInfo->buffInfo.colBuffStart1[0] ;
    Sli_AA_Request.MemInfo.dwaaSecondaryDepthBufBegin  = bInfo->buffInfo.lfbBuffAddr0[bInfo->buffInfo.nColBuffers];
    Sli_AA_Request.MemInfo.dwaaSecondaryDepthBufEnd    = bInfo->buffInfo.lfbBuffAddr0End[bInfo->buffInfo.nColBuffers];
    Sli_AA_Request.MemInfo.dwBpp = bpp;

    /*
     * Call the MiniVDD
     */
    hDevice = CreateFile(MINIVDDNAME, 0, 0, NULL, 0, 0, NULL);
    if (INVALID_HANDLE_VALUE != hDevice)
    {
      DIOC_Data.dwDevNode = bInfo->devNode ;
      DIOC_Data.dwSpare = (DWORD)&Sli_AA_Request;
      DeviceIoControl(hDevice, SLI_AA_ENABLE, &DIOC_Data, sizeof(DIOC_Data), NULL, 0x0, NULL, NULL);
    }
    CloseHandle(hDevice);
    }

    /* The minivdd screws with lfbMemoryConfig, so we have to fix it. */
    HWC_IO_STORE(bInfo->regInfo, lfbMemoryConfig, lfbMemoryConfig);
    HWC_IO_STORE(bInfo->regInfo, lfbMemoryConfig, SST_RAW_LFB_WRITE_CONTROL);

    /* This will automagically get broadcast to all chips. */
    HWC_IO_STORE(bInfo->regInfo, vidMaxRGBDelta, bpp == 15 ? 0x101010 : 0x100810);
  }
   else
#endif
  if ((IS_NAPALM(bInfo->pciInfo.deviceID)) &&
      (bInfo->h3pixelSample == 2))
  {
    hwcExtRequest_t
      ctxReq;
    hwcExtResult_t
      ctxRes;
    FxU32 
      function_number;
    FxBool
      retVal = FXFALSE;
                          
    ctxReq.which = HWCEXT_PCI_OP;
                              
    for (function_number = 0; function_number < bInfo->pciInfo.numChips; function_number++) {

      /* All these are the same for each config cycle */
      ctxReq.optData.pciOpReq.DeviceId 
        = function_number & 0x3;
      ctxReq.optData.pciOpReq.Operation
        = HWCEXT_PCI_WRITE;

      /*
      **  Set up cfgSliLfbCtrl
      */

      ctxReq.optData.pciOpReq.Offset
        = offsetof(SstPCIConfigRegs, cfgSliLfbCtrl);

      ctxReq.optData.pciOpReq.Value = 0;
        //= SST_SLI_LFB_CPU_WRITE_ENABLE |
        //SST_SLI_LFB_DISPATCH_WRITE_ENABLE |
        //SST_SLI_LFB_READ_ENABLE;

      retVal = ExtEscape((HDC)bInfo->hdc, HWCEXT_ESCAPE(bInfo->boardNum), 
                         sizeof(ctxReq), (LPSTR) &ctxReq,
                         sizeof(ctxRes), (LPSTR) &ctxRes);
                                       
      /*
      ** Set up cfgAALfbCtrl
      */
      /* Why are we doing this?
       */
      ctxReq.optData.pciOpReq.Offset
        = offsetof(SstPCIConfigRegs, cfgAALfbCtrl);

      ctxReq.optData.pciOpReq.Value
        = SST_AA_LFB_CPU_WRITE_ENABLE |
          SST_AA_LFB_DISPATCH_WRITE_ENABLE |
          SST_AA_LFB_READ_ENABLE |
          bInfo->buffInfo.colBuffStart1[0];

      GDBG_INFO(80, "storing cfgAALfbCtrl: %08lx\n",ctxReq.optData.pciOpReq.Value);

      /* Pixel Format */
      switch (bInfo->h3pixelSize) {
      case 4:
        ctxReq.optData.pciOpReq.Value |= SST_AA_LFB_READ_FORMAT_32BPP;
        break;
      case 2:
        ctxReq.optData.pciOpReq.Value |= SST_AA_LFB_READ_FORMAT_16BPP;
        break;
      }

      /* Perhaps this should change for 2-sample AA?  */
      if (bInfo->h3pixelSample == 4)
        ctxReq.optData.pciOpReq.Value |= SST_AA_LFB_RD_DIVIDE_BY_FOUR;

      retVal = ExtEscape((HDC)bInfo->hdc, HWCEXT_ESCAPE(bInfo->boardNum), 
                         sizeof(ctxReq), (LPSTR) &ctxReq,
                         sizeof(ctxRes), (LPSTR) &ctxRes);
      
      /*
      **  Set Up cfgAADepthBufferAperture
      */
      ctxReq.optData.pciOpReq.Offset
        = offsetof(SstPCIConfigRegs, cfgAADepthBufferAperture);


      ctxReq.optData.pciOpReq.Value
//        = ( ((bInfo->buffInfo.auxBuffStart0 >> 12) << SST_AA_DEPTH_BUFFER_APERTURE_BEGIN_SHIFT) |
//            ((bInfo->buffInfo.auxBuffEnd0 >> 12)   << SST_AA_DEPTH_BUFFER_APERTURE_END_SHIFT));
        = ( ((bInfo->buffInfo.lfbBuffAddr0[bInfo->buffInfo.nColBuffers] >> 12) << SST_AA_DEPTH_BUFFER_APERTURE_BEGIN_SHIFT) |
            ((bInfo->buffInfo.lfbBuffAddr0End[bInfo->buffInfo.nColBuffers] >> 12)   << SST_AA_DEPTH_BUFFER_APERTURE_END_SHIFT));

      retVal = ExtEscape((HDC)bInfo->hdc, HWCEXT_ESCAPE(bInfo->boardNum), 
                         sizeof(ctxReq), (LPSTR) &ctxReq,
                         sizeof(ctxRes), (LPSTR) &ctxRes);
      
      if (bInfo->h3pixelSample == 2) {
        /*
        ** set up cfgVideoCtrl0
        */
        ctxReq.optData.pciOpReq.Offset
          = offsetof(SstPCIConfigRegs, cfgVideoCtrl0);

        ctxReq.optData.pciOpReq.Value =
          SST_CFG_ENHANCED_VIDEO_EN | SST_CFG_VIDEO_LOCALMUX_SEL |
          SST_CFG_DIVIDE_VIDEO_BY_2;

        retVal = ExtEscape((HDC)bInfo->hdc, HWCEXT_ESCAPE(bInfo->boardNum), 
                           sizeof(ctxReq), (LPSTR) &ctxReq,
                           sizeof(ctxRes), (LPSTR) &ctxRes);

        /*
        ** set up cfgVideoCtrl1
        */
        ctxReq.optData.pciOpReq.Offset
          = offsetof(SstPCIConfigRegs, cfgVideoCtrl1);

        ctxReq.optData.pciOpReq.Value = 0;

        retVal = ExtEscape((HDC)bInfo->hdc, HWCEXT_ESCAPE(bInfo->boardNum), 
                           sizeof(ctxReq), (LPSTR) &ctxReq,
                           sizeof(ctxRes), (LPSTR) &ctxRes);

        /*
        ** set up cfgVideoCtrl2
        */
        ctxReq.optData.pciOpReq.Offset
          = offsetof(SstPCIConfigRegs, cfgVideoCtrl2);

        ctxReq.optData.pciOpReq.Value = 0; //SST_CFG_SLI_COMPAREMASK_AAFIFO;

        retVal = ExtEscape((HDC)bInfo->hdc, HWCEXT_ESCAPE(bInfo->boardNum), 
                           sizeof(ctxReq), (LPSTR) &ctxReq,
                           sizeof(ctxRes), (LPSTR) &ctxRes);

      }
    }
  }

  /*
  **  Let's make sure we aren't a bunch of pigeffers.
  */
  if (bInfo->h3pixelSample > 1 || bInfo->h3nwaySli > 1) { /* and thus it must be Napalm */

    FxU32
      tileLinearMark,
      aaMark,
      cfgAALfbCtrl,
      cfgDepthBufferAperture,
      locLFBMemCfg,
      lfbTileCompare,
      strideInTiles,
      chipNum;
    hwcExtRequest_t ctxReq;
    hwcExtResult_t ctxRes;

    for(chipNum = 0; chipNum < bInfo->pciInfo.numChips; chipNum++) {
      /* Load */
      if(chipNum == 0) {
        HWC_IO_STORE(bInfo->regInfo, lfbMemoryConfig, SST_RAW_LFB_UPDATE_CONTROL);
        HWC_IO_LOAD(bInfo->regInfo, lfbMemoryConfig, locLFBMemCfg);
        HWC_IO_STORE(bInfo->regInfo, lfbMemoryConfig, SST_RAW_LFB_UPDATE_CONTROL|SST_RAW_LFB_READ_CONTROL);
        HWC_IO_LOAD(bInfo->regInfo, lfbMemoryConfig, lfbTileCompare);
        HWC_IO_STORE(bInfo->regInfo, lfbMemoryConfig, SST_RAW_LFB_UPDATE_CONTROL);
      } else {
        HWC_IO_STORE_SLAVE(chipNum, bInfo->regInfo, lfbMemoryConfig, SST_RAW_LFB_UPDATE_CONTROL);
        HWC_IO_LOAD_SLAVE(chipNum, bInfo->regInfo, lfbMemoryConfig, locLFBMemCfg);
        HWC_IO_STORE_SLAVE(chipNum, bInfo->regInfo, lfbMemoryConfig, SST_RAW_LFB_UPDATE_CONTROL|SST_RAW_LFB_READ_CONTROL);
        HWC_IO_LOAD_SLAVE(chipNum, bInfo->regInfo, lfbMemoryConfig, lfbTileCompare);
        HWC_IO_STORE_SLAVE(chipNum, bInfo->regInfo, lfbMemoryConfig, SST_RAW_LFB_UPDATE_CONTROL);        
      }

      /* pull the tile aperture begin page bits out and shift them up by
        12 since they represent the 4K-aligned page */
      tileLinearMark = (SST_RAW_LFB_TILE_BEGIN_PAGE_UNMUNGE(locLFBMemCfg)) << 12;
      strideInTiles  = (locLFBMemCfg & SST_RAW_LFB_TILE_STRIDE) >> SST_RAW_LFB_TILE_STRIDE_SHIFT;

      ctxReq.which = HWCEXT_PCI_OP;
    
      /* All these are the same for each config cycle */
      ctxReq.optData.pciOpReq.DeviceId  = chipNum;
    
      ctxReq.optData.pciOpReq.Operation = HWCEXT_PCI_READ;

      ctxReq.optData.pciOpReq.Offset
          = offsetof(SstPCIConfigRegs, cfgAALfbCtrl);

      /*
        NB:  Some lazy bugger didn't check the return value!
        */
      ExtEscape((HDC)bInfo->hdc, HWCEXT_ESCAPE(bInfo->boardNum), 
                        sizeof(ctxReq), (LPSTR) &ctxReq,
                        sizeof(ctxRes), (LPSTR) &ctxRes);

      cfgAALfbCtrl = ctxRes.optData.pciOpRes.Value;

      /* Grab cfgAADepthBufferAperture Register */
      /* All these are the same for each config cycle */
      ctxReq.optData.pciOpReq.DeviceId  = chipNum;
    
      ctxReq.optData.pciOpReq.Operation = HWCEXT_PCI_READ;

      ctxReq.optData.pciOpReq.Offset
          = offsetof(SstPCIConfigRegs, cfgAADepthBufferAperture);

      /*
        NB:  Some lazy bugger didn't check the return value!
        */
      ExtEscape((HDC)bInfo->hdc, HWCEXT_ESCAPE(bInfo->boardNum), 
                        sizeof(ctxReq), (LPSTR) &ctxReq,
                        sizeof(ctxRes), (LPSTR) &ctxRes);

      cfgDepthBufferAperture = ctxRes.optData.pciOpRes.Value;

      /* Clear bits [31:26] and bits [3:0] */
      aaMark = cfgAALfbCtrl & ~(0xfc00000f);

      GDBG_INFO(80, FN_NAME ":  Offsets of buffers from respective bases %d:\n",chipNum);
      GDBG_INFO(80, "\tcfgAALfbCtrol:       %08lx\n",cfgAALfbCtrl);
      GDBG_INFO(80, "\tlocLFBMemCfg:        %08lx\n",locLFBMemCfg);
      GDBG_INFO(80, "\tlfbTileCompare:      %08lx\n",lfbTileCompare);
      GDBG_INFO(80, "\tstrideInTiles:       %08lx\n",strideInTiles);
      GDBG_INFO(80, "\ttileMark:            %08lx\n",tileLinearMark);
      GDBG_INFO(80, "\taaMark:              %08lx\n",aaMark);
      GDBG_INFO(80, "\tcolBufferStart0[0]:  %08lx\n",
                bInfo->buffInfo.colBuffStart0[0] - tileLinearMark);
      GDBG_INFO(80, "\tcolBufferStart0[1]:  %08lx\n",  
                bInfo->buffInfo.colBuffStart0[1] - tileLinearMark);
      GDBG_INFO(80, "\tauxBufferStart0:  %08lx\n",
                bInfo->buffInfo.auxBuffStart0 - tileLinearMark);

      GDBG_INFO(80, "\tcolBufferStart1[0]:  %08lx\n",
                bInfo->buffInfo.colBuffStart1[0] - aaMark);
      GDBG_INFO(80, "\tcolBufferStart1[1]:  %08lx\n",
                bInfo->buffInfo.colBuffStart1[1] - aaMark);
      GDBG_INFO(80, "\tauxBufferStart1:  %08lx\n",
                bInfo->buffInfo.auxBuffStart1 - aaMark);

      GDBG_INFO(80, "\tcolorBufferBegin1:   %08lx\n",
          (cfgAALfbCtrl & SST_SECONDARY_BUFFER_BASE));
      GDBG_INFO(80, "\tdepthBufferBegin:    %08lx\n",
          ((cfgDepthBufferAperture & SST_AA_DEPTH_BUFFER_APERTURE_BEGIN) >>
           SST_AA_DEPTH_BUFFER_APERTURE_BEGIN_SHIFT) * 4096);
      GDBG_INFO(80, "\tdepthBufferEnd:      %08lx\n",
          ((cfgDepthBufferAperture & SST_AA_DEPTH_BUFFER_APERTURE_END) >>
           SST_AA_DEPTH_BUFFER_APERTURE_END_SHIFT) * 4096);

    }
  }           
#endif /* HWC_EXT_INIT */

#if HWC_GDX_INIT
  if (((IS_NAPALM(bInfo->pciInfo.deviceID)) &&
       (bInfo->pciInfo.numChips > 1)) &&
      ((bInfo->h3nwaySli > 1) ||
       (bInfo->h3pixelSample > 2) ||
       (bInfo->h3pixelSample == 2 && !bInfo->buffInfo.enable2ndbuffer)))
  {
    hrmSLIAAChipInfo_t chipInfo;
    hrmSLIAAMemInfo_t  memInfo;
    
    chipInfo.size = sizeof(chipInfo); 
    chipInfo.aaEnable = (bInfo->h3pixelSample > 1);
    chipInfo.sliEnable = (bInfo->h3nwaySli > 1);
    
    chipInfo.sliAaAnalog = (GETENV("FX_GLIDE_ANALOG_SLI") ?
                            atol(GETENV("FX_GLIDE_ANALOG_SLI")) : 0);
    chipInfo.sli_nlines  = bInfo->h3sliBandHeight;
    chipInfo.swapAlgorithm = 1;
    chipInfo.numChips = bInfo->pciInfo.numChips;
    chipInfo.aaSampleHigh = (bInfo->h3pixelSample == 4);
    
    memInfo.size = sizeof(memInfo);
    memInfo.totalMemory = bInfo->h3Mem * 1024 * 1024;
    memInfo.tileMark = bInfo->buffInfo.colBuffStart0[0];
    memInfo.tileCmpMark = bInfo->buffInfo.colBuffStart0[0];
    memInfo.aaSecondaryColorBufBegin = bInfo->buffInfo.colBuffStart1[0];
    memInfo.aaSecondaryDepthBufBegin = bInfo->buffInfo.lfbBuffAddr0[bInfo->buffInfo.nColBuffers];
    memInfo.aaSecondaryDepthBufEnd   = bInfo->buffInfo.lfbBuffAddr0End[bInfo->buffInfo.nColBuffers];
    memInfo.bpp = bpp;
    
    if(chipInfo.aaEnable || chipInfo.sliEnable) {
      _hrmSLIAA((hrmBoard_t *)bInfo->hMon,&chipInfo,&memInfo);
    }

    /* The minivdd screws with lfbMemoryConfig, so we have to fix it. */
    HWC_IO_STORE(bInfo->regInfo, lfbMemoryConfig, lfbMemoryConfig);

    /* This will automagically get broadcast to all chips. */
    HWC_IO_STORE(bInfo->regInfo, vidMaxRGBDelta, /*bpp == 15 ? 0x101010 :*/ 0x100810);

  /*
  **  Let's make sure we aren't a bunch of pigeffers.
  */
  if (bInfo->h3pixelSample > 1 || bInfo->h3nwaySli > 1) { /* and thus it must be Napalm */

    FxU32
      tileLinearMark,
      aaMark,
      cfgAALfbCtrl,
      cfgDepthBufferAperture,
      locLFBMemCfg,
      lfbTileCompare,
      strideInTiles,
      dramInit0,
      dramInit1,
      miscInit0,
      miscInit1,
      chipNum;

    for(chipNum = 0; chipNum < bInfo->pciInfo.numChips; chipNum++) {
      /* Load */
      if(chipNum == 0) {
        HWC_IO_STORE(bInfo->regInfo, lfbMemoryConfig, SST_RAW_LFB_UPDATE_CONTROL);
        HWC_IO_LOAD(bInfo->regInfo, lfbMemoryConfig, locLFBMemCfg);
        HWC_IO_STORE(bInfo->regInfo, lfbMemoryConfig, SST_RAW_LFB_UPDATE_CONTROL|SST_RAW_LFB_READ_CONTROL);
        HWC_IO_LOAD(bInfo->regInfo, lfbMemoryConfig, lfbTileCompare);
        HWC_IO_STORE(bInfo->regInfo, lfbMemoryConfig, SST_RAW_LFB_UPDATE_CONTROL);
        HWC_IO_LOAD(bInfo->regInfo, dramInit0, dramInit0);
        HWC_IO_LOAD(bInfo->regInfo, dramInit1, dramInit1);
        HWC_IO_LOAD(bInfo->regInfo, miscInit0, miscInit0);
        HWC_IO_LOAD(bInfo->regInfo, miscInit1, miscInit1);
      } else {
        HWC_IO_STORE_SLAVE(chipNum, bInfo->regInfo, lfbMemoryConfig, SST_RAW_LFB_UPDATE_CONTROL);
        HWC_IO_LOAD_SLAVE(chipNum, bInfo->regInfo, lfbMemoryConfig, locLFBMemCfg);
        HWC_IO_STORE_SLAVE(chipNum, bInfo->regInfo, lfbMemoryConfig, SST_RAW_LFB_UPDATE_CONTROL|SST_RAW_LFB_READ_CONTROL);
        HWC_IO_LOAD_SLAVE(chipNum, bInfo->regInfo, lfbMemoryConfig, lfbTileCompare);
        HWC_IO_STORE_SLAVE(chipNum, bInfo->regInfo, lfbMemoryConfig, SST_RAW_LFB_UPDATE_CONTROL);        
        HWC_IO_LOAD_SLAVE(chipNum, bInfo->regInfo, dramInit0, dramInit0);
        HWC_IO_LOAD_SLAVE(chipNum, bInfo->regInfo, dramInit1, dramInit1);
        HWC_IO_LOAD_SLAVE(chipNum, bInfo->regInfo, miscInit0, miscInit0);
        HWC_IO_LOAD_SLAVE(chipNum, bInfo->regInfo, miscInit1, miscInit1);
      }

      /* pull the tile aperture begin page bits out and shift them up by
        12 since they represent the 4K-aligned page */
      tileLinearMark = (SST_RAW_LFB_TILE_BEGIN_PAGE_UNMUNGE(locLFBMemCfg)) << 12;
      strideInTiles  = (locLFBMemCfg & SST_RAW_LFB_TILE_STRIDE) >> SST_RAW_LFB_TILE_STRIDE_SHIFT;

    _hrmReadConfigRegister((hrmBoard_t *)bInfo->hMon,
                            0,
                            offsetof(SstPCIConfigRegs, cfgAALfbCtrl),
                            &cfgAALfbCtrl);

    _hrmReadConfigRegister((hrmBoard_t *)bInfo->hMon,
                            0,
                            offsetof(SstPCIConfigRegs, cfgAADepthBufferAperture),
                            &cfgDepthBufferAperture);

      /* Clear bits [31:26] and bits [3:0] */
      aaMark = cfgAALfbCtrl & ~(0xfc00000f);

      GDBG_INFO(80, FN_NAME ":  Offsets of buffers from respective bases %d:\n",chipNum);
      GDBG_INFO(80, "\tcfgAALfbCtrol:       %08lx %08lx\n",cfgAALfbCtrl,(cfgAALfbCtrl & SST_AA_LFB_READ_FORMAT) >> SST_AA_LFB_READ_FORMAT_SHIFT);
      GDBG_INFO(80, "\tlocLFBMemCfg:        %08lx\n",locLFBMemCfg);
      GDBG_INFO(80, "\tlfbTileCompare:      %08lx\n",lfbTileCompare);
      GDBG_INFO(80, "\tstrideInTiles:       %08lx\n",strideInTiles);
      GDBG_INFO(80, "\ttileMark:            %08lx\n",tileLinearMark);
      GDBG_INFO(80, "\taaMark:              %08lx\n",aaMark);
      GDBG_INFO(80, "\tcolBufferStart0[0]:  %08lx\n",
                bInfo->buffInfo.colBuffStart0[0] - tileLinearMark);
      GDBG_INFO(80, "\tcolBufferStart0[1]:  %08lx\n",  
                bInfo->buffInfo.colBuffStart0[1] - tileLinearMark);
      GDBG_INFO(80, "\tauxBufferStart0:  %08lx\n",
                bInfo->buffInfo.auxBuffStart0 - tileLinearMark);

      GDBG_INFO(80, "\tcolBufferStart1[0]:  %08lx\n",
                bInfo->buffInfo.colBuffStart1[0] - aaMark);
      GDBG_INFO(80, "\tcolBufferStart1[1]:  %08lx\n",
                bInfo->buffInfo.colBuffStart1[1] - aaMark);
      GDBG_INFO(80, "\tauxBufferStart1:  %08lx\n",
                bInfo->buffInfo.auxBuffStart1 - aaMark);

      GDBG_INFO(80, "\tcolorBufferBegin1:   %08lx\n",
          (cfgAALfbCtrl & SST_SECONDARY_BUFFER_BASE));
      GDBG_INFO(80, "\tdepthBufferBegin:    %08lx\n",
          ((cfgDepthBufferAperture & SST_AA_DEPTH_BUFFER_APERTURE_BEGIN) >>
           SST_AA_DEPTH_BUFFER_APERTURE_BEGIN_SHIFT) * 4096);
      GDBG_INFO(80, "\tdepthBufferEnd:      %08lx\n",
          ((cfgDepthBufferAperture & SST_AA_DEPTH_BUFFER_APERTURE_END) >>
           SST_AA_DEPTH_BUFFER_APERTURE_END_SHIFT) * 4096);

      GDBG_INFO(80, "\tbpp:                 %08lx\n",bpp);
      GDBG_INFO(80, "\tdramInit0:           %08lx\n",dramInit0);
      GDBG_INFO(80, "\tdramInit1:           %08lx\n",dramInit1);
      GDBG_INFO(80, "\tmiscInit0:           %08lx\n",miscInit0);
      GDBG_INFO(80, "\tmiscInit1:           %08lx\n",miscInit1);
    }
    }
  }
  else if(IS_NAPALM(bInfo->pciInfo.deviceID) && bInfo->h3pixelSample == 2) {
    
    FxU32 value, pixFmt;
    /* Single board two sample AA setup */
    
    /* cfgSliLfbCtrl */
    _hrmWriteConfigRegister((hrmBoard_t *)bInfo->hMon,
                            0,
                            offsetof(SstPCIConfigRegs, cfgSliLfbCtrl),
                            0);
    /* cfgAALfbCtrl */                            
    value = SST_AA_LFB_CPU_WRITE_ENABLE |
            SST_AA_LFB_DISPATCH_WRITE_ENABLE |
            SST_AA_LFB_READ_ENABLE |
            bInfo->buffInfo.colBuffStart1[0];

    pixFmt = (vidProcCfg & SST_OVERLAY_PIXEL_FORMAT);
    
    switch(pixFmt) {
    case SST_OVERLAY_PIXEL_RGB32U:
      value |= SST_AA_LFB_READ_FORMAT_32BPP;
      break;
    case SST_OVERLAY_PIXEL_RGB565D:
    case SST_OVERLAY_PIXEL_RGB565U:
      value |= SST_AA_LFB_READ_FORMAT_16BPP;
      break;
    case SST_OVERLAY_PIXEL_RGB1555D:
    case SST_OVERLAY_PIXEL_RGB1555U:
      value |= SST_AA_LFB_READ_FORMAT_15BPP;
      break;
    }                            
    _hrmWriteConfigRegister((hrmBoard_t *)bInfo->hMon,
                            0,
                            offsetof(SstPCIConfigRegs, cfgAALfbCtrl),
                            value);
    /* cfgAADepthBufferAperture */
    _hrmWriteConfigRegister((hrmBoard_t *)bInfo->hMon,
                            0,
                            offsetof(SstPCIConfigRegs, cfgAADepthBufferAperture),
                            ((bInfo->buffInfo.auxBuffStart0 >> 12) << SST_AA_DEPTH_BUFFER_APERTURE_BEGIN_SHIFT) |
                            ((bInfo->buffInfo.auxBuffEnd0 >> 12)   << SST_AA_DEPTH_BUFFER_APERTURE_END_SHIFT));
    /* cfgVideoCtrl0 */
    _hrmWriteConfigRegister((hrmBoard_t *)bInfo->hMon,
                            0,
                            offsetof(SstPCIConfigRegs, cfgVideoCtrl0),
                            SST_CFG_ENHANCED_VIDEO_EN | SST_CFG_VIDEO_LOCALMUX_SEL |
                            SST_CFG_DIVIDE_VIDEO_BY_2);
    /* cfgVideoCtrl1 */
    _hrmWriteConfigRegister((hrmBoard_t *)bInfo->hMon,
                            0,
                            offsetof(SstPCIConfigRegs, cfgVideoCtrl1),
                            0);
    /* cfgVideoCtrl2 */
    _hrmWriteConfigRegister((hrmBoard_t *)bInfo->hMon,
                            0,
                            offsetof(SstPCIConfigRegs, cfgVideoCtrl2),
                            0);
                            
    
  }
#endif /* HWC_INIT_GDX */

#if !HWC_EXT_INIT && !HWC_GDX_INIT
  if((IS_NAPALM(bInfo->pciInfo.deviceID)) && (bInfo->pciInfo.numChips > 1))
  {
    hwcSetSLIAAMode(bInfo,
                 (bInfo->h3nwaySli > 1),     /* sliEnable */
                 (bInfo->h3pixelSample > 1), /* aaEnable */
                 bInfo->h3analogSli,         /* analogSLI */
                 bInfo->h3sliBandHeight,     /* sliBandHeight */
                 bInfo->h3Mem * 1024 * 1024, /* totalMem */
                 bInfo->pciInfo.numChips,    /* numChips */
                 (bInfo->h3pixelSample == 4),/* aaSampleHigh */
                 bInfo->buffInfo.colBuffStart1[0],       /* aaColorBuffStart */
                 bInfo->buffInfo.lfbBuffAddr0[bInfo->buffInfo.nColBuffers],     /* aaDepthBuffStart */
                 bInfo->buffInfo.lfbBuffAddr0End[bInfo->buffInfo.nColBuffers],  /* aaDepthBuffEnd */
                 bpp);

    /* The minivdd screws with lfbMemoryConfig, so we have to fix it. */
    HWC_IO_STORE(bInfo->regInfo, lfbMemoryConfig, lfbMemoryConfig);
    HWC_IO_STORE(bInfo->regInfo, vidMaxRGBDelta, bpp == 15 ? 0x101010 : 0x100810);
  }
  /* Single chip AA config... probably not needed as a seperate chunk of code. */
  else if(bInfo->pciInfo.numChips == 1 && bInfo->h3pixelSample == 2) {
  
    FxU32 value, pixFmt;
    /* Single board two sample AA setup */
    
    /* cfgSliLfbCtrl */
    hwcWriteConfigRegister(bInfo, 0, offsetof(SstPCIConfigRegs, cfgSliLfbCtrl), 0);
    
    /* cfgAALfbCtrl */                            
    value = SST_AA_LFB_CPU_WRITE_ENABLE |
            SST_AA_LFB_DISPATCH_WRITE_ENABLE |
            SST_AA_LFB_READ_ENABLE |
            bInfo->buffInfo.colBuffStart1[0];

    pixFmt = (vidProcCfg & SST_OVERLAY_PIXEL_FORMAT);
    
    switch(pixFmt) {
    case SST_OVERLAY_PIXEL_RGB32U:
      value |= SST_AA_LFB_READ_FORMAT_32BPP;
      break;
    case SST_OVERLAY_PIXEL_RGB565D:
    case SST_OVERLAY_PIXEL_RGB565U:
      value |= SST_AA_LFB_READ_FORMAT_16BPP;
      break;
    case SST_OVERLAY_PIXEL_RGB1555D:
    case SST_OVERLAY_PIXEL_RGB1555U:
      value |= SST_AA_LFB_READ_FORMAT_15BPP;
      break;
    }                            
    hwcWriteConfigRegister(bInfo,
                            0,
                            offsetof(SstPCIConfigRegs, cfgAALfbCtrl),
                            value);
    /* cfgAADepthBufferAperture */
    hwcWriteConfigRegister(bInfo,
                            0,
                            offsetof(SstPCIConfigRegs, cfgAADepthBufferAperture),
                            ((bInfo->buffInfo.auxBuffStart0 >> 12) << SST_AA_DEPTH_BUFFER_APERTURE_BEGIN_SHIFT) |
                            ((bInfo->buffInfo.auxBuffEnd0 >> 12)   << SST_AA_DEPTH_BUFFER_APERTURE_END_SHIFT));
    /* cfgVideoCtrl0 */
    hwcWriteConfigRegister(bInfo,
                            0,
                            offsetof(SstPCIConfigRegs, cfgVideoCtrl0),
                            SST_CFG_ENHANCED_VIDEO_EN | SST_CFG_VIDEO_LOCALMUX_SEL |
                            SST_CFG_DIVIDE_VIDEO_BY_2);
    /* cfgVideoCtrl1 */
    hwcWriteConfigRegister(bInfo,
                            0,
                            offsetof(SstPCIConfigRegs, cfgVideoCtrl1),
                            0);
    /* cfgVideoCtrl2 */
    hwcWriteConfigRegister(bInfo,
                            0,
                            offsetof(SstPCIConfigRegs, cfgVideoCtrl2),
                            0);
  }      

#endif /* !HWC_EXT_INIT && !HWC_INIT_GDX */
#endif /* FX_GLIDE_NAPALM */

  /* Temp hack */
  if(GETENV("SST_PCI_LOWTHRESH")) {
  FxU32 pciInit0, thresh;
    thresh = atoi(GETENV("SST_PCI_LOWTHRESH"));
    if(thresh > 15) thresh = 15;
    HWC_IO_LOAD(bInfo->regInfo, pciInit0, pciInit0);
    pciInit0 &= ~SST_PCI_LOWTHRESH;        
    pciInit0 |= thresh << SST_PCI_LOWTHRESH_SHIFT;
    HWC_IO_STORE(bInfo->regInfo, pciInit0, pciInit0);
  }

  return FXTRUE;

#undef FN_NAME
} /* hwcInitVideo */

FxBool
hwcRestoreVideo(hwcBoardInfo *bInfo)
{
#define FN_NAME "hwcRestoreVideo"
  #if 1
  hwcIdleHardwareWithTimeout(bInfo);

  /* disable the CMD fifo */
  HWC_CAGP_STORE(bInfo->regInfo, cmdFifo0.baseSize, 0);
  #endif

  /* reset pci registers */
#ifdef FX_GLIDE_NAPALM
#ifdef HWC_EXT_INIT


#ifdef HWC_MINIVDD_HACK
  /*
   * Since I am a lazy bastard, try to use the minivdd to setup SLI/AA mode
   */
  if (((IS_NAPALM(bInfo->pciInfo.deviceID)) &&
       (bInfo->pciInfo.numChips > 1)) &&
      ((bInfo->h3nwaySli > 1) ||
       (bInfo->h3pixelSample > 2) ||
       (bInfo->h3pixelSample == 2 && !bInfo->buffInfo.enable2ndbuffer)))
  {
    if (bInfo->osNT)
    {
      hwcExtRequest_t ctxReq ;
      hwcExtResult_t  ctxRes ;
 
      ctxReq.which = HWCEXT_SLI_AA_REQUEST ;

      ctxReq.optData.sliAAReq.ChipInfo.dwaaEn             = (bInfo->h3pixelSample > 1) ;
      /* Request SLI or AA disable */
      ctxReq.optData.sliAAReq.ChipInfo.dwaaEn             = 0 ;
      ctxReq.optData.sliAAReq.ChipInfo.dwsliEn            = 0 ;

      ctxReq.optData.sliAAReq.ChipInfo.dwsli_nlines       = bInfo->h3sliBandHeight ;
      
      /* Fill out SLI mode information. */
      ctxReq.optData.sliAAReq.ChipInfo.dwChips            = bInfo->pciInfo.numChips ;
      ctxReq.optData.sliAAReq.ChipInfo.dwaaSampleHigh     = 0 ;

      ExtEscape((HDC)bInfo->hdc, HWCEXT_ESCAPE(bInfo->boardNum), 
                sizeof(ctxReq), (LPSTR) &ctxReq,
                sizeof(ctxRes), (LPSTR) &ctxRes);
    }
     else
    {
    DIOC_DATA DIOC_Data;
    SLI_AA_REQUEST Sli_AA_Request;
    HANDLE hDevice;

    /* Request SLI or AA enable */
    Sli_AA_Request.ChipInfo.dwaaEn             = 0 ;
    Sli_AA_Request.ChipInfo.dwsliEn            = 0 ;

    Sli_AA_Request.ChipInfo.dwsli_nlines       = bInfo->h3sliBandHeight;
    
    /* Fill out SLI mode information. */
    Sli_AA_Request.ChipInfo.dwChips            = bInfo->pciInfo.numChips ;
    Sli_AA_Request.ChipInfo.dwaaSampleHigh     = 0;
 
    /*
     * Call the MiniVDD
     */
    hDevice = CreateFile(MINIVDDNAME, 0, 0, NULL, 0, 0, NULL);
    if (INVALID_HANDLE_VALUE != hDevice)
    {
      DIOC_Data.dwDevNode = bInfo->devNode ;
      DIOC_Data.dwSpare = (DWORD)&Sli_AA_Request;
      DeviceIoControl(hDevice, SLI_AA_DISABLE, &DIOC_Data, sizeof(DIOC_Data), NULL, 0x0, NULL, NULL);
    }
    CloseHandle(hDevice);
    }
  }
   else
#endif /* HWC_MINIVDD_HACK */

  if (IS_NAPALM(bInfo->pciInfo.deviceID))
  {
    hwcExtRequest_t
      ctxReq;
    hwcExtResult_t
      ctxRes;
    FxU32 
      function_number;
    FxBool
      retVal = FXFALSE;
                          
    ctxReq.which = HWCEXT_PCI_OP;
                              
    for (function_number = 0; function_number < bInfo->pciInfo.numChips; function_number++) {

      ctxReq.optData.pciOpReq.DeviceId 
        = function_number & 0x3;
      ctxReq.optData.pciOpReq.Operation
        = HWCEXT_PCI_WRITE;
      ctxReq.optData.pciOpReq.Offset
        = offsetof(SstPCIConfigRegs, cfgSliLfbCtrl);
      ctxReq.optData.pciOpReq.Value
        = 0;
      retVal = ExtEscape((HDC)bInfo->hdc, HWCEXT_ESCAPE(bInfo->boardNum), 
                         sizeof(ctxReq), (LPSTR) &ctxReq,
                         sizeof(ctxRes), (LPSTR) &ctxRes);
                                       
      ctxReq.optData.pciOpReq.Offset
        = offsetof(SstPCIConfigRegs, cfgAADepthBufferAperture);
      ctxReq.optData.pciOpReq.Value
        = 0;
      retVal = ExtEscape((HDC)bInfo->hdc, HWCEXT_ESCAPE(bInfo->boardNum), 
                         sizeof(ctxReq), (LPSTR) &ctxReq,
                         sizeof(ctxRes), (LPSTR) &ctxRes);

      ctxReq.optData.pciOpReq.Offset
        = offsetof(SstPCIConfigRegs, cfgAALfbCtrl);
      ctxReq.optData.pciOpReq.Value
        = 0;

      retVal = ExtEscape((HDC)bInfo->hdc, HWCEXT_ESCAPE(bInfo->boardNum), 
                         sizeof(ctxReq), (LPSTR) &ctxReq,
                         sizeof(ctxRes), (LPSTR) &ctxRes);
                                                                                        
      ctxReq.optData.pciOpReq.Offset
        = offsetof(SstPCIConfigRegs, cfgVideoCtrl0);
      ctxReq.optData.pciOpReq.Value
        = 0;

      retVal = ExtEscape((HDC)bInfo->hdc, HWCEXT_ESCAPE(bInfo->boardNum), 
                         sizeof(ctxReq), (LPSTR) &ctxReq,
                         sizeof(ctxRes), (LPSTR) &ctxRes);

      ctxReq.optData.pciOpReq.Offset
        = offsetof(SstPCIConfigRegs, cfgVideoCtrl2);
      ctxReq.optData.pciOpReq.Value
        = 0;

      retVal = ExtEscape((HDC)bInfo->hdc, HWCEXT_ESCAPE(bInfo->boardNum), 
                         sizeof(ctxReq), (LPSTR) &ctxReq,
                         sizeof(ctxRes), (LPSTR) &ctxRes);
      ctxReq.optData.pciOpReq.Offset
        = offsetof(SstPCIConfigRegs, cfgVideoCtrl2);
      ctxReq.optData.pciOpReq.Value
        = 0;

      retVal = ExtEscape((HDC)bInfo->hdc, HWCEXT_ESCAPE(bInfo->boardNum), 
                         sizeof(ctxReq), (LPSTR) &ctxReq,
                         sizeof(ctxRes), (LPSTR) &ctxRes);
    }
  }
#endif

#if HWC_GDX_INIT
  if (((IS_NAPALM(bInfo->pciInfo.deviceID)) &&
       (bInfo->pciInfo.numChips > 1)) &&
      ((bInfo->h3nwaySli > 1) ||
       (bInfo->h3pixelSample > 2) ||
       (bInfo->h3pixelSample == 2 && !bInfo->buffInfo.enable2ndbuffer)))
  {
    hrmSLIAAChipInfo_t chipInfo;
    hrmSLIAAMemInfo_t  memInfo;
   
    chipInfo.size = sizeof(chipInfo); 
    chipInfo.aaEnable = 0;
    chipInfo.sliEnable = 0;
    chipInfo.numChips = bInfo->pciInfo.numChips;
    
    chipInfo.sliAaAnalog = 0;
    chipInfo.sli_nlines  = bInfo->h3sliBandHeight;
    chipInfo.swapAlgorithm = 0;
    chipInfo.aaSampleHigh = 0;
    
    memInfo.size = sizeof(memInfo);
    memInfo.totalMemory = bInfo->h3Mem;
    memInfo.tileMark = bInfo->buffInfo.colBuffStart0[0];
    memInfo.tileCmpMark = bInfo->buffInfo.colBuffStart0[0];
    memInfo.aaSecondaryColorBufBegin = bInfo->buffInfo.colBuffStart1[0];
    memInfo.aaSecondaryDepthBufBegin = bInfo->buffInfo.auxBuffStart1;
    memInfo.aaSecondaryDepthBufEnd = bInfo->buffInfo.auxBuffEnd1;
    memInfo.bpp = 0;
    
    _hrmSLIAA((hrmBoard_t *)bInfo->hMon,&chipInfo,&memInfo);
  }
  else if(IS_NAPALM(bInfo->pciInfo.deviceID)) {
     GDBG_INFO(80, "Cleaning up AA/SLI config registers\n");
   /* NOTE: Move this code to the ROM, so it can always
      clear out the AA/SLI config stuff after any mode change
      or whenever exclusive mode is released.  Doing it here
      will not always work. */
   /* cfgSliLfbCtrl */
    _hrmWriteConfigRegister((hrmBoard_t *)bInfo->hMon,
                            0,
                            offsetof(SstPCIConfigRegs, cfgSliLfbCtrl),
                            0);
    /* cfgAALfbCtrl */                            
    _hrmWriteConfigRegister((hrmBoard_t *)bInfo->hMon,
                            0,
                            offsetof(SstPCIConfigRegs, cfgAALfbCtrl),
                            0);
    /* cfgAADepthBufferAperture */
    _hrmWriteConfigRegister((hrmBoard_t *)bInfo->hMon,
                            0,
                            offsetof(SstPCIConfigRegs, cfgAADepthBufferAperture),
                            0);
    /* cfgVideoCtrl0 */
    _hrmWriteConfigRegister((hrmBoard_t *)bInfo->hMon,
                            0,
                            offsetof(SstPCIConfigRegs, cfgVideoCtrl0),
                            0);
    /* cfgVideoCtrl1 */
    _hrmWriteConfigRegister((hrmBoard_t *)bInfo->hMon,
                            0,
                            offsetof(SstPCIConfigRegs, cfgVideoCtrl1),
                            0);
    /* cfgVideoCtrl2 */
    _hrmWriteConfigRegister((hrmBoard_t *)bInfo->hMon,
                            0,
                            offsetof(SstPCIConfigRegs, cfgVideoCtrl2),
                            0);
  }
#endif /* HWC_INIT_GDX */

#if !HWC_EXT_INIT && !HWC_GDX_INIT
  if(IS_NAPALM(bInfo->pciInfo.deviceID)) {
    if(bInfo->pciInfo.numChips > 1) {
      hwcSetSLIAAMode(bInfo,
                      0,     /* sliEnable */
                      0,     /* aaEnable */
                      bInfo->h3analogSli,         /* analogSLI */
                      bInfo->h3sliBandHeight,     /* sliBandHeight */
                      bInfo->h3Mem * 1024 * 1024, /* totalMem */
                      bInfo->pciInfo.numChips,    /* numChips */
                      (bInfo->h3pixelSample == 4),/* aaSampleHigh */
                      bInfo->buffInfo.colBuffStart1[0],       /* aaColorBuffStart */
                      bInfo->buffInfo.lfbBuffAddr0[bInfo->buffInfo.nColBuffers],     /* aaDepthBuffStart */
                      bInfo->buffInfo.lfbBuffAddr0End[bInfo->buffInfo.nColBuffers],  /* aaDepthBuffEnd */
                      0);
    } else {  
      /* NOTE: Move this code to the ROM, so it can always
          clear out the AA/SLI config stuff after any mode change
          or whenever exclusive mode is released.  Doing it here
          will not always work. */
      /* cfgSliLfbCtrl */
        hwcWriteConfigRegister(bInfo,
                                0,
                                offsetof(SstPCIConfigRegs, cfgSliLfbCtrl),
                                0);
        /* cfgAALfbCtrl */                            
        hwcWriteConfigRegister(bInfo,
                                0,
                                offsetof(SstPCIConfigRegs, cfgAALfbCtrl),
                                0);
        /* cfgAADepthBufferAperture */
        hwcWriteConfigRegister(bInfo,
                                0,
                                offsetof(SstPCIConfigRegs, cfgAADepthBufferAperture),
                                0);
        /* cfgVideoCtrl0 */
        hwcWriteConfigRegister(bInfo,
                                0,
                                offsetof(SstPCIConfigRegs, cfgVideoCtrl0),
                                0);
        /* cfgVideoCtrl1 */
        hwcWriteConfigRegister(bInfo,
                                0,
                                offsetof(SstPCIConfigRegs, cfgVideoCtrl1),
                                0);
        /* cfgVideoCtrl2 */
        hwcWriteConfigRegister(bInfo,
                                0,
                                offsetof(SstPCIConfigRegs, cfgVideoCtrl2),
                                0);
    }
  }
#endif

#endif /* FX_GLIDE_NAPALM */

#ifdef HWC_EXT_INIT
  {
  FxI32 status;

  hwcExtRequest_t ctxReq;
  hwcExtResult_t  ctxRes;

  ctxReq.which = HWCEXT_HWCRLSEXCLUSIVE;
  ctxReq.optData.linearAddrReq.devNum = 0;
  GDBG_INFO(90, FN_NAME ":  ExtEscape:HWCEXT_HWCRLSEXCLUSIVE\n");

    ExtEscape((HDC) bInfo->hdc, HWCEXT_ESCAPE(bInfo->boardNum), sizeof(ctxReq), (void *) &ctxReq, /**/
      sizeof(ctxRes), (void *) &ctxRes);

   GDBG_INFO(80, "%s:  sizeof(ctxRes) = %d\n", FN_NAME, sizeof(ctxRes));
   GDBG_INFO(80, "%s:  &ctxRes = 0x%x\n", FN_NAME, &ctxRes);

   status = ctxRes.resStatus;

   GDBG_INFO(80, "%s:  ctxRes.resStatus = %d\n", FN_NAME, status);

  if (ctxRes.resStatus != 1) {
      hwc_errncpy(errorString, "HWCEXT_HWCRLSEXCLUSIVE Failed");
      return FXFALSE;
    }
    
  }
#endif /* HWC_EXT_INIT */

  /* Restore display */
  
  resetVideo();

  return FXTRUE;
#undef FN_NAME
} /* hwcRestoreVideo */

#ifdef FX_GLIDE_NAPALM
/* These are platform dependant */
FxU32 hwcReadConfigRegister(hwcBoardInfo *bInfo, FxU32 chipNumber, FxU32 offset)
{
#if HWC_EXT_INIT    
  hwcExtRequest_t ctxReq;
  hwcExtResult_t ctxRes;
  
  ctxReq.which = HWCEXT_PCI_OP;
    
  ctxReq.optData.pciOpReq.DeviceId  = chipNumber;    
  ctxReq.optData.pciOpReq.Operation = HWCEXT_PCI_READ;
  ctxReq.optData.pciOpReq.Offset    = offset;

  /*
  NB:  Some lazy bugger didn't check the return value!
  */
  ExtEscape((HDC)bInfo->hdc, HWCEXT_ESCAPE(bInfo->boardNum), 
            sizeof(ctxReq), (LPSTR) &ctxReq,
            sizeof(ctxRes), (LPSTR) &ctxRes);

  return ctxRes.optData.pciOpRes.Value;
#elif HWC_GDX_INIT
  FxU32 value;

  _hrmReadConfigRegister( (hrmBoard_t *)bInfo->hMon, chipNumber, offset, &value );
  
  return value; 
#else 
  /* DOS */
  FxU32 data, result;
  PciRegister reg;
  reg.regAddress = offset;
  reg.sizeInBytes = 4;
  
  result = pciGetConfigDataRaw(reg, bInfo->deviceNum | (chipNumber << 13), &data);
  return data;
#endif
}

void hwcWriteConfigRegister(hwcBoardInfo *bInfo, FxU32 chipNumber, FxU32 offset, FxU32 value)
{
#if HWC_EXT_INIT    
  hwcExtRequest_t ctxReq;
  hwcExtResult_t ctxRes;
  
  ctxReq.which = HWCEXT_PCI_OP;
  
  ctxReq.optData.pciOpReq.DeviceId  = chipNumber;
  ctxReq.optData.pciOpReq.Operation = HWCEXT_PCI_WRITE;
  ctxReq.optData.pciOpReq.Offset    = offset;
  ctxReq.optData.pciOpReq.Value     = value;
  
  ExtEscape((HDC)bInfo->hdc, HWCEXT_ESCAPE(bInfo->boardNum), 
            sizeof(ctxReq), (LPSTR) &ctxReq,
            sizeof(ctxRes), (LPSTR) &ctxRes);
#elif HWC_GDX_INIT
  _hrmWriteConfigRegister( (hrmBoard_t *)bInfo->hMon, chipNumber, offset, value );
#else
  /* DOS */
  PciRegister reg;
  reg.regAddress = offset;
  reg.sizeInBytes = 4;

  pciSetConfigDataRaw(reg, bInfo->deviceNum | (chipNumber << 13), &value);
#endif
}

/* These are not */                        
void hwcSLIReadEnable(hwcBoardInfo *bInfo)
{
  FxU32 cfgSliLfbCtrl;
  FxU32 cfgAALfbCtrl;
  FxU32 chipNumber;

  if(GETENV("FX_GLIDE_A0_READ_ABORT")) {
    if(bInfo->h3nwaySli > 1) {
      for(chipNumber = 0; chipNumber < bInfo->pciInfo.numChips; chipNumber++) {
        /* Turn on SLI Read */
        cfgSliLfbCtrl = hwcReadConfigRegister(bInfo, chipNumber, offsetof(SstPCIConfigRegs, cfgSliLfbCtrl));
        cfgSliLfbCtrl |= (SST_SLI_LFB_READ_ENABLE);
        hwcWriteConfigRegister(bInfo, chipNumber, offsetof(SstPCIConfigRegs, cfgSliLfbCtrl), cfgSliLfbCtrl);
        
        /* Turn off AA read if it is not supposed to be enabled */
        if(bInfo->h3pixelSample < 2) {
            cfgAALfbCtrl = hwcReadConfigRegister(bInfo, chipNumber, offsetof(SstPCIConfigRegs, cfgAALfbCtrl));
            cfgAALfbCtrl &= ~(SST_AA_LFB_READ_ENABLE);
            hwcWriteConfigRegister(bInfo, chipNumber, offsetof(SstPCIConfigRegs, cfgAALfbCtrl), cfgAALfbCtrl);
        } 
      }
    }           
  }
}

void hwcSLIReadDisable(hwcBoardInfo *bInfo)
{
  FxU32 cfgSliLfbCtrl;
  FxU32 cfgAALfbCtrl;
  FxU32 chipNumber;
  
  if(GETENV("FX_GLIDE_A0_READ_ABORT")) {
    if(bInfo->h3nwaySli > 1) {
        for(chipNumber = 0; chipNumber < bInfo->pciInfo.numChips; chipNumber++) {
        /* Turn off SLI Read */
        cfgSliLfbCtrl = hwcReadConfigRegister(bInfo, chipNumber, offsetof(SstPCIConfigRegs, cfgSliLfbCtrl));
        cfgSliLfbCtrl &= ~(SST_SLI_LFB_READ_ENABLE);
        hwcWriteConfigRegister(bInfo, chipNumber, offsetof(SstPCIConfigRegs, cfgSliLfbCtrl), cfgSliLfbCtrl);
        
        /* Turn on AA Read */
        cfgAALfbCtrl = hwcReadConfigRegister(bInfo, chipNumber, offsetof(SstPCIConfigRegs, cfgAALfbCtrl));
        cfgAALfbCtrl |= (SST_AA_LFB_READ_ENABLE);
        hwcWriteConfigRegister(bInfo, chipNumber, offsetof(SstPCIConfigRegs, cfgAALfbCtrl), cfgAALfbCtrl);
      }
    }           
  }
}
#endif

char *
hwcGetErrorString()
{
#define FN_NAME "hwcGetErrorString"
  return errorString;
#undef FN_NAME
} /* hwcGetErrorString */

FxBool
hwcCheckMemSize(hwcBoardInfo *bInfo, FxU32 xres, FxU32 yres, FxU32 nColBuffers,
                FxU32 nAuxBuffers, FxBool tiled)
{
#define FN_NAME "hwcCheckMemSize"
  FxU32
    bufSize, totSize;

  bufSize = calcBufferSize(bInfo, xres, yres, tiled);

  totSize = (nColBuffers + nAuxBuffers) * bufSize;

  if (totSize < ((bInfo->h3Mem << 20) - bInfo->min_tramSize)) /* Need 2M for texture */
    return FXTRUE;
  else
    return FXFALSE;    
#undef FN_NAME
} /* hwcCheckMemSize */

static FxU32
calcBufferStride(hwcBoardInfo *bInfo, FxU32 xres, FxBool tiled)
{
  FxU32
    strideInTiles;
  FxU32 shift = (bInfo->h3pixelSize >> 1);

  if (tiled == FXTRUE) {
    /* Calculate tile width stuff */
    strideInTiles = (xres << shift) >> 7;
    if ((xres << shift) & (HWC_TILE_WIDTH - 1))
      strideInTiles++;
    
    return (strideInTiles * HWC_TILE_WIDTH);

  } else {
    return (xres << shift);
  }
} /* calcBufferStride */

static FxU32
calcBufferHeightInTiles(hwcBoardInfo *bInfo, FxU32 yres)
{
  FxU32
    heightInTiles,            /* Height of buffer in tiles */
    numSLIBands;              /* Number of SLI bands needed */


  yres = yres >> (bInfo->h3nwaySli >> 1);

  /* yres is per-chip, which must be a multiple of the
   * SLI band height */
  if(bInfo->h3nwaySli > 1) {
    /* Round up to the number of bands we need */
    numSLIBands = (yres + (bInfo->h3sliBandHeight - 1)) / bInfo->h3sliBandHeight;
    /* Recalc new height and fall through */
    yres = numSLIBands * bInfo->h3sliBandHeight;
  }
  
  /* Calculate tile height stuff */
  heightInTiles = yres >> 5;
  
  /* This makes sure the number of tiles is 
   * enough to cover the resolution we want. */
  if (yres & (HWC_TILE_HEIGHT - 1))
    heightInTiles++;

  return heightInTiles;

} /* calcBufferHeightInTiles */

static FxU32
calcBufferSizeInTiles(hwcBoardInfo *bInfo, FxU32 xres, FxU32 yres) {
  FxU32
    bufSizeInTiles;           /* Size of buffer in tiles */

  bufSizeInTiles =
    calcBufferHeightInTiles(bInfo, yres) * (calcBufferStride(bInfo, xres, FXTRUE) >> 7);

  return bufSizeInTiles;

} /* calcBufferSizeInTiles */

static FxU32
calcBufferSize(hwcBoardInfo *bInfo, FxU32 xres, FxU32 yres, FxBool tiled)
{
  FxU32
    stride,
    height,
    bufSize;                  /* Size of buffer in bytes */
  FxU32 shift = (bInfo->h3pixelSize >> 1);

  if (tiled) {
    stride = calcBufferStride(bInfo, xres, tiled);
    height = HWC_TILE_HEIGHT * calcBufferHeightInTiles(bInfo, yres);
  } else {
    stride = xres << shift;
    height = yres >> (bInfo->h3nwaySli >> 1);
  }

  bufSize = stride * height;
  
  return bufSize;

} /* calcBufferSize */

/* How the hw treats lfb accesses are dependent on the 'type' of
 * memory (tiled/linear) that the color/aux buffers are in. We
 * pre-compute the actual lfb address here while we know about the
 * memory space and if we adjusted the page alignment above.
 *
 * NB: If we are in tiled mode then the fact that we align the color
 * buffers on page boundaries means that the y offset of the buffers
 * may not actually be on a boundary for the tile addressing scheme.
 * The 'rounding' done to HWC_TILED_BUFFER_Y_ALIGN adjust for this.
 *
 * NB: The memory optimization of aligning color buffers on even page
 * boundaries will cause the tiled lfb access to be off by a page so
 * we add in the width of a page (HWC_TILED_BUFFER_X_ADJUST) here.
 */
#define HWC_TILED_BUFFER_BYTES    HWC_LFB_STRIDE  /* 128 Bytes x 32 lines */
#define HWC_TILED_BUFFER_Y_ALIGN  (HWC_LFB_STRIDE * 32)
#define HWC_TILED_BUFFER_X_ADJUST 0x80UL

static FxU32
hwcBufferLfbAddr(const hwcBoardInfo *bInfo, FxU32 physAddress)
{
  FxU32 retVal = 0x00UL;

  FxU32 tileAddress;
  FxU32 tileNumber;
  FxU32 tileOffset;
  FxU32 tileXOffset;
  FxU32 tileScanline;
  FxU32 tileRow;
  FxU32 lfbAddress;
  FxU32 lfbYOffset;

  if (bInfo->vidInfo.tiled) {    
    GDBG_INFO(80, "\tphysAddress: 0x%08lx\n",physAddress);

    /* Compute address in tile space */
    tileAddress = physAddress - bInfo->primaryOffset;
    GDBG_INFO(80, "\ttileAddress: 0x%08lx\n",tileAddress);

    /* Compute tile number we're in (each tile is 4K bytes) */
    tileNumber = tileAddress >> 12;
    GDBG_INFO(80, "\ttileNumber: 0x%08lx (%d)\n",tileNumber,tileNumber);

    /* Compute base tile row we're in */
    tileRow = tileNumber / bInfo->buffInfo.bufStrideInTiles;
    GDBG_INFO(80, "\ttileRow: %d  (stride = %d)\n",tileNumber,bInfo->buffInfo.bufStrideInTiles);

    /* Compute offset within the tile */
    tileOffset = tileAddress - (tileNumber << 12);
    GDBG_INFO(80, "\ttileOffset: 0x%08lx\n",tileOffset);

    /* Compute scanline within the tile */
    tileScanline = tileOffset >> 7;
    GDBG_INFO(80, "\ttileScanline: 0x%08lx\n",tileScanline);

    /* Compute tile X offset within the row */
    tileXOffset = tileNumber - (tileRow * bInfo->buffInfo.bufStrideInTiles);
    GDBG_INFO(80, "\ttileXOffset: %d\n",tileXOffset);

    /* Compute Y offset in LFB space */
    lfbYOffset = ((tileRow * 32 + tileScanline) << (bInfo->h3nwaySli >> 1));

    /* Compute LFB address of tile start */
    lfbAddress =  bInfo->primaryOffset + lfbYOffset * HWC_LFB_STRIDE + tileXOffset * 128;

    GDBG_INFO(80, "\tlfbAddress: %08lx\n", lfbAddress);
    retVal = lfbAddress;
  } else {
    retVal = physAddress;
  }
  return retVal;
}

static FxU32
pow2Round(FxU32 val, FxU32 pow2Const)
{
  const FxU32 pow2Mask = (pow2Const - 1UL);

  return ((val + pow2Mask) & ~pow2Mask);
}

FxU32 
hwcInitAGPFifo(hwcBoardInfo *bInfo, FxBool enableHoleCounting) 
{
#define FN_NAME "hwcInitAGPFifo"
#if HWC_EXT_INIT || HWC_GDX_INIT
  FxU32
    agpSize, agpLAddr, agpPAddr;
#if HWC_EXT_INIT
  FxU32
    cagpRegs;                   /* pointer to Cmd/AGP regs */
  FxI32 status;

  hwcExtRequest_t ctxReq;
  hwcExtResult_t  ctxRes;

  if (bInfo->regInfo.initialized == FXFALSE) {
    sprintf(errorString, "%s:  Called before hwcMapBoard\n", FN_NAME);
    return FXFALSE;
  }
  cagpRegs = bInfo->regInfo.cmdAGPBase;

  if (bInfo->buffInfo.initialized == FXFALSE) {
    sprintf(errorString, "%s:  Called before hwcInitBuffers\n", FN_NAME);
    return FXFALSE;
  }

  ctxReq.which = HWCEXT_GETAGPINFO;
  GDBG_INFO(80, FN_NAME ":  ExtEscape:HWCEXT_GETAGPINFO\n");

  ExtEscape((HDC) bInfo->hdc, HWCEXT_ESCAPE(bInfo->boardNum), sizeof(ctxReq), (void *) &ctxReq, /**/
    sizeof(ctxRes), (void *) &ctxRes);

  status = ctxRes.resStatus;
  agpLAddr = ctxRes.optData.agpInfoRes.lAddr;
  agpPAddr = ctxRes.optData.agpInfoRes.pAddr;
  agpSize = ctxRes.optData.agpInfoRes.size;

  /* If we fail, bail and go to memory fifo */
  if ((status != 1) ||
     (agpSize == 0))
  {
    return hwcInitFifo(bInfo, enableHoleCounting); 
  }

#elif defined(HWC_GDX_INIT)
  if(!_hrmGetAGPInfo) {
    return hwcInitFifo(bInfo, enableHoleCounting);
  }
  
  if(0 != _hrmGetAGPInfo((hrmBoard_t *)bInfo->hMon,&agpLAddr,&agpPAddr,&agpSize)) {
      return hwcInitFifo(bInfo, enableHoleCounting);
  }  
#endif

  bInfo->fifoInfo.agpFifo = 1;
  bInfo->fifoInfo.agpVirtAddr = agpLAddr;
  bInfo->fifoInfo.agpPhysAddr = agpPAddr;
  bInfo->fifoInfo.fifoStart = agpPAddr;
  bInfo->fifoInfo.agpSize = agpSize;

  GDBG_INFO(80, "%s AGP linear address = 0x%x\n", FN_NAME, agpLAddr);
  GDBG_INFO(80, "%s AGP physical address = 0x%x\n", FN_NAME, agpPAddr);
  GDBG_INFO(80, "%s AGP Size = 0x%x\n", FN_NAME, agpSize);

#if 0
  From Windows code:

  SETDW(_FF(lpCRegs)->cmdFifo0.baseSize, 0);
  SETDW(_FF(lpCRegs)->cmdFifo0.baseAddrL,
    (_FF(agpPhysAddr) >> 12) );
  SETDW(_FF(lpCRegs)->cmdFifo0.readPtrL, _FF(agpPhysAddr) );
  SETDW(_FF(lpCRegs)->cmdFifo0.readPtrH,  0);
  SETDW(_FF(lpCRegs)->cmdFifo0.aMin,  _FF(agpPhysAddr) - 4);
  SETDW(_FF(lpCRegs)->cmdFifo0.aMax,  _FF(agpPhysAddr) - 4);
  SETDW(_FF(lpCRegs)->cmdFifo0.depth, 0);
  SETDW(_FF(lpCRegs)->cmdFifo0.holeCount, 0);
  SETDW(_FF(lpCRegs)->cmdFifoThresh, 0x122);
  SETDW(_FF(lpCRegs)->cmdFifo0.baseSize, 0x700);
#endif

  HWC_CAGP_STORE(bInfo->regInfo, cmdFifo0.baseAddrL,
    bInfo->fifoInfo.fifoStart>>12);
  HWC_CAGP_STORE(bInfo->regInfo, cmdFifo0.readPtrL, bInfo->fifoInfo.fifoStart);
  HWC_CAGP_STORE(bInfo->regInfo, cmdFifo0.readPtrH, 0);
  HWC_CAGP_STORE(bInfo->regInfo, cmdFifo0.aMin, bInfo->fifoInfo.fifoStart-4);
  HWC_CAGP_STORE(bInfo->regInfo, cmdFifo0.aMax, bInfo->fifoInfo.fifoStart-4);
  
  HWC_CAGP_STORE(bInfo->regInfo, cmdFifo0.depth, 0);
  HWC_CAGP_STORE(bInfo->regInfo, cmdFifo0.holeCount, 0);
  /* Fifo LWM /HWM/ THRESHOLD */
  HWC_CAGP_STORE(bInfo->regInfo, cmdFifoThresh, (0x09 << SST_HIGHWATER_SHIFT) | 0x2); 
  HWC_CAGP_STORE(bInfo->regInfo, cmdFifo0.baseSize,
    ((bInfo->fifoInfo.fifoLength >> 12) - 1) | SST_EN_CMDFIFO |
    SST_CMDFIFO_DISABLE_HOLES | SST_CMDFIFO_AGP);
  
  GDBG_INFO(2,"%s:  CMD FIFO placed at physical addr 0x%x\n", FN_NAME,
    bInfo->fifoInfo.fifoStart);

  return FXTRUE;
#else /* !HWC_EXT_INIT */
  return hwcInitFifo(bInfo, enableHoleCounting);
#endif /* !HWC_EXT_INIT */
#undef FN_NAME
} /* hwcInitAGPFifo */ 


FxBool
hwcAllocAuxRenderingBuffer(hwcBoardInfo *bInfo, hwcBufferDesc *bp, int width,
                           int height)  
{
#define FN_NAME "hwcAllocAuxRenderingBuffer"
  /* For now, these buffers  */
  FxBool
    rVal = FXFALSE;
  
  FxU32
    bufSize,
    offset;

  bufSize = (width * height) << 2;

  offset = bInfo->fbOffset - bufSize;

  if ((offset - bInfo->tramSize) < bInfo->min_tramSize) {
    sprintf(errorString, "%s:  Insufficient memory", FN_NAME);
  } else {
    bp->bufOffset = offset;
    bp->bufStride = width << 2; /* Below tiled memory for now */
    bp->bufBPP = 16;
    bp->tiled = 0;
    bp->bufType = HWC_BUFFER_AUXRENDER;

    bInfo->fbOffset -= bufSize;

    rVal = FXTRUE;
  }

  return rVal;

#undef FN_NAME
} /* hwcAllocAuxRenderingBuffer */

static void hwcReadBuffer565(hwcBoardInfo *bInfo, FxU32 src, FxU32 strideInBytes, FxU8 *dst, FxU32 renderMask, FxU32 compareMask, FxU32 aaShift)
{
  FxU32 width, height;
  FxU32 x, y, srcY;
  FxU16 *s;
  FxU8  *d;
  FxU16 pix16;
  FxU8  r, g, b;

#if __POWERPC__
  src += bInfo->pciInfo.swizzleOffset[3];
#endif

  width = bInfo->vidInfo.xRes;
  height = bInfo->vidInfo.yRes;

  srcY = 0;

  for(y = 0; y < height; y++) {    
    /* Dst always walks down entire framebuffer (or up, since this is Targa) */
    d = dst + width*3*(height-y-1);

    if((y & renderMask) == compareMask) {
      /* This chip owns this scanline. */
      s = (FxU16 *)(src + srcY*strideInBytes);
      for(x = 0; x < width; x++) {
        pix16 = *s++;
        r = (pix16 >> 11) & 0x1f;
        g = (pix16 >> 5) & 0x3f;
        b = pix16 & 0x1f;
        /* Targa is bgr. */
        *d++ += (b << (1 + aaShift));
        *d++ += (g << aaShift);
        *d++ += (r << (1 + aaShift));
      }  
      srcY++;
    }
  }  
}

static void hwcReadBuffer1555(hwcBoardInfo *bInfo, FxU32 src, FxU32 strideInBytes, FxU8 *dst, FxU32 renderMask, FxU32 compareMask, FxU32 aaShift)
{
  FxU32 width, height;
  FxU32 x, y, srcY;
  FxU16 *s;
  FxU8  *d;
  FxU16 pix16;
  FxU8  r, g, b;

#if __POWERPC__
  src += bInfo->pciInfo.swizzleOffset[3];
#endif

  width = bInfo->vidInfo.xRes;
  height = bInfo->vidInfo.yRes;
  
  srcY = 0;

  for(y = 0; y < height; y++) {    
    /* Dst always walks down entire framebuffer (or up, since this is Targa) */
    d = dst + width*3*(height-y-1);

    if((y & renderMask) == compareMask) {
      /* This chip owns this scanline. */
      s = (FxU16 *)(src + srcY*strideInBytes);
      for(x = 0; x < width; x++) {
        pix16 = *s++;
        r = (pix16 >> 10) & 0x1f;
        g = (pix16 >> 5) & 0x1f;
        b = pix16 & 0x1f;
        /* Targa is bgr. */
        *d++ += (b << (1 + aaShift));
        *d++ += (g << (1 + aaShift));
        *d++ += (r << (1 + aaShift));
      }  
      srcY++;
    }
  }  
}

static void hwcReadBuffer8888(hwcBoardInfo *bInfo, FxU32 src, FxU32 strideInBytes, FxU8 *dst, FxU32 renderMask, FxU32 compareMask, FxU32 aaShift)
{
  FxU32 width, height;
  FxU32 x, y, srcY;
  FxU32 *s;
  FxU8  *d;
  FxU32 pix32;
  FxU8  r, g, b;

  width = bInfo->vidInfo.xRes;
  height = bInfo->vidInfo.yRes;

#if __POWERPC__
  src += bInfo->pciInfo.swizzleOffset[1];
#endif

  srcY = 0;

  for(y = 0; y < height; y++) {    
    /* Dst always walks down entire framebuffer (or up, since this is Targa) */
    d = dst + width*3*(height-y-1);

    if((y & renderMask) == compareMask) {
      /* This chip owns this scanline. */
      s = (FxU32 *)(src + srcY*strideInBytes);
      for(x = 0; x < width; x++) {
        pix32 = *s++;
        r = (FxU8)((pix32 >> 16) & 0xff);
        g = (FxU8)((pix32 >> 8) & 0xff);
        b = (FxU8)(pix32 & 0xff);

        /* Targa is bgr. */
        *d++ += b >> (aaShift) ;
        *d++ += g >> (aaShift) ;
        *d++ += r >> (aaShift) ;
      }  
      srcY++;
    }
  }  
}
  
static void hwcGammaCorrect(hwcBoardInfo *bInfo, FxU8 *buffer, FxU32 width, FxU32 height)
{
  FxU32 red[256], green[256], blue[256];
  FxU32 i;

  /* Read current hardware gamma table. */
  if(hwcGetGammaTable(bInfo, 256, red, green, blue)) {
    for(i = 0; i < width*height; i++) {
      *buffer = (FxU8)blue[*buffer]; buffer++;
      *buffer = (FxU8)green[*buffer]; buffer++;
      *buffer = (FxU8)red[*buffer]; buffer++;
    }  
  }
}

/* Amazingly nasty code follows. */
void hwcAAScreenShot(hwcBoardInfo *bInfo, FxU32 colBufNum)
{
  /* We want to save off a 32-bit .TGA file (or whatever), even though
   * we only have 16-bit buffers.  In order to do this we have to individually
   * read from each AA sample buffer and merge the results by hand.   The merging
   * is the easy part.  Reading from each buffer individually is the really hard
   * part.  It would have ruled to have the read hardware have some way to "select"
   * which sample we want to read from, rather than always read from all of them.
   * 
   * So, the strategy is this.  First, figure out where the master and slave chips
   * are mapped and save off their config info.  Then, map everything to where the
   * slaves live and deconfigure the magic AA read stuff.  Then, for each chip we'll
   * map it to where the master was supposed to be.  Then we move the tileMark to the
   * base of the primary AA buffer and snarf the data.  Then we do the same for the
   * secondary AA buffer.  We then put the lfb config back where we're supposed to and
   * then map the chip back to the slave location.
   * 
   * After we've done all that we map everything back the way it was originally and then
   * (finally) save off the image file to disk.  */
  
  /* Note: This routine currently doesn't grok anything more than four chip configs. */
  FxU32 memBase1[4];
  FxU32 cfgInitEnable[4];
  FxU32 cfgPciDecode[4];
  FxU32 cfgAALfbCtrl[4];
  FxU32 cfgSliLfbCtrl[4];
  FxU32 cfgAADepthBufferAperture[4];
  FxU32 chip;
  FxU32 temp, vidProcCfg;
  FxU32 compareMask, renderMask, aaShift;
  FxU32 lfbMemoryConfig, lfbMemoryConfigTemp;
  void (*hwcReadBufferFunc)(hwcBoardInfo *bInfo, FxU32 src, FxU32 strideInBytes, FxU8 *dst, FxU32 renderMask, FxU32 compareMask, FxU32 aaShift);
  FxU8  header[18];
  FILE  *file;

  static FxU32 fileNameNum;
  char fileName[256];

  FxU8 *buffer;

  /* Allocate buffer to store frame into... */
  buffer = calloc(bInfo->vidInfo.xRes * bInfo->vidInfo.yRes, 3);

  if(!buffer)
    return;
  
  /* Have to do it the hard way for 16-bit 
   * or for the new way of doing 2-sample */
  if ((bInfo->h3pixelSize == 2) ||
     (bInfo->h3pixelSample == 2)) {
    
    /* Figure out framebuffer format (1555 or 565) */
    HWC_IO_LOAD(bInfo->regInfo, vidProcCfg, vidProcCfg);
    switch(vidProcCfg & SST_OVERLAY_PIXEL_FORMAT) {
      case SST_OVERLAY_PIXEL_RGB1555D:
      case SST_OVERLAY_PIXEL_RGB1555U:
        hwcReadBufferFunc = hwcReadBuffer1555;
        break;

      case SST_OVERLAY_PIXEL_RGB565D:
      case SST_OVERLAY_PIXEL_RGB565U:
        hwcReadBufferFunc = hwcReadBuffer565;
        break;

      case SST_OVERLAY_PIXEL_RGB32U:
        hwcReadBufferFunc = hwcReadBuffer8888;
        break ;
    }  
    
    /* First, figure out where everything is. */
    for(chip = 0; chip < bInfo->pciInfo.numChips; chip++) {
      memBase1[chip] = hwcReadConfigRegister(bInfo, chip, offsetof(SstPCIConfigRegs, memBaseAddr1));
      cfgInitEnable[chip] = hwcReadConfigRegister(bInfo, chip, offsetof(SstPCIConfigRegs, cfgInitEnable_FabID));
      cfgPciDecode[chip] = hwcReadConfigRegister(bInfo, chip, offsetof(SstPCIConfigRegs, cfgPciDecode));
      cfgSliLfbCtrl[chip] = hwcReadConfigRegister(bInfo, chip, offsetof(SstPCIConfigRegs, cfgSliLfbCtrl));
      cfgAALfbCtrl[chip] = hwcReadConfigRegister(bInfo, chip, offsetof(SstPCIConfigRegs, cfgAALfbCtrl));
      cfgAADepthBufferAperture[chip] = hwcReadConfigRegister(bInfo, chip, offsetof(SstPCIConfigRegs, cfgAADepthBufferAperture));
    }
  
    /* Map everyone to where the slave lives and disable snooping, SLI && AA reads */
    for(chip = 0; chip < bInfo->pciInfo.numChips; chip++) {
      temp = cfgInitEnable[chip] >> 8;
      temp &= ~(SST_ADDRESS_SNOOP_ENABLE|
                SST_MEMBASE0_SNOOP_ENABLE|
                SST_MEMBASE1_SNOOP_ENABLE|
                SST_ADDRESS_SNOOP_SLAVE);
      temp |= SST_ENABLE_BASE_ADDR_WRITES;
      hwcWriteConfigRegister(bInfo, chip, offsetof(SstPCIConfigRegs, cfgInitEnable_FabID), temp << 8);
      hwcWriteConfigRegister(bInfo, chip, offsetof(SstPCIConfigRegs, cfgSliLfbCtrl),0);
      hwcWriteConfigRegister(bInfo, chip, offsetof(SstPCIConfigRegs, cfgAALfbCtrl),0);
      hwcWriteConfigRegister(bInfo, chip, offsetof(SstPCIConfigRegs, cfgAADepthBufferAperture),0);
      /* For PowerPC systems we have to futz around with cfgPciDecode a bit more since the master would normally try to decode
       * 256MB of address space, which will screw up when we map it to where the slaves live. */
#if __POWERPC__      
      hwcWriteConfigRegister(bInfo, chip, offsetof(SstPCIConfigRegs, cfgPciDecode),
        SST_PCI_IOBASE0_DECODE_256 | SST_PCI_MEMBASE0_DECODE_32MB | SST_PCI_MEMBASE1_DECODE_64MB);
#else
      hwcWriteConfigRegister(bInfo, chip, offsetof(SstPCIConfigRegs, cfgPciDecode),cfgPciDecode[chip] & ~SST_MEMBASE1_SNOOP);
#endif      
      hwcWriteConfigRegister(bInfo, chip, offsetof(SstPCIConfigRegs, memBaseAddr1),memBase1[1]);
    }  

    /* Map chips and read buffers */
    for(chip = 0; chip < bInfo->pciInfo.numChips; chip++) {

      /* Grab SLI config stuff */
      if(cfgSliLfbCtrl[chip] & SST_SLI_LFB_READ_ENABLE) {
        renderMask = (cfgSliLfbCtrl[chip] & SST_SLI_LFB_RENDERMASK) >> SST_SLI_LFB_RENDERMASK_SHIFT;
        compareMask = (cfgSliLfbCtrl[chip] & SST_SLI_LFB_COMPAREMASK) >> SST_SLI_LFB_COMPAREMASK_SHIFT;
      } else {
        /* Non-SLI, use all scanlines */
        compareMask = renderMask = 0x00;
      }   

      /* Grab AA config stuff */
      if(cfgAALfbCtrl[chip] & SST_AA_LFB_READ_ENABLE) {
        /* Grab the number of samples from bInfo rather than the hardware.  This
         * makes it easier to deal with the new style 2-sample AA mode that uses
         * one buffer per chip, even though the backend LFB stuff is still configured
         * for two (that point to the same place). */
        if(bInfo->h3pixelSample == 4) {
          aaShift = 0;
        } else {
          aaShift = 1;
        }  
      } else {
        aaShift = 2;
      }
       
      /* Map chip to master address space. */
      hwcWriteConfigRegister(bInfo, chip, offsetof(SstPCIConfigRegs, memBaseAddr1),memBase1[0]);    
      /* Again, on PowerPC we have to reprogram the chip we're looking at to decode the proper amount of memory. (256MB) */
#if __POWERPC__
      hwcWriteConfigRegister(bInfo, chip, offsetof(SstPCIConfigRegs, cfgPciDecode),
              SST_PCI_IOBASE0_DECODE_256 | SST_PCI_MEMBASE0_DECODE_32MB | SST_PCI_MEMBASE1_DECODE_256MB);
#endif      

      /* This will always read from the master, but all chips share the same values. */
      if(chip == 0) {
        HWC_IO_LOAD(bInfo->regInfo, lfbMemoryConfig, lfbMemoryConfig);
      } else {
        HWC_IO_LOAD_SLAVE(chip, bInfo->regInfo, lfbMemoryConfig, lfbMemoryConfig);
      }  

      /* Just bang on lfbMemConfig to point to the base of the color buffer we want. */
      lfbMemoryConfigTemp =
        SST_RAW_LFB_TILE_BEGIN_PAGE_MUNGE((bInfo->buffInfo.colBuffStart0[colBufNum] >> 12))
          | HWC_RAW_LFB_STRIDE
          | (bInfo->buffInfo.bufStrideInTiles << SST_RAW_LFB_TILE_STRIDE_SHIFT);        

      if(chip == 0) {
        HWC_IO_STORE(bInfo->regInfo, lfbMemoryConfig, lfbMemoryConfigTemp);
      } else {
        HWC_IO_STORE_SLAVE(chip,bInfo->regInfo, lfbMemoryConfig, lfbMemoryConfigTemp);
      }  

      /* Read primary AA buffer */
      hwcReadBufferFunc(bInfo, bInfo->regInfo.rawLfbBase + bInfo->buffInfo.colBuffStart0[colBufNum], bInfo->buffInfo.bufLfbStride, buffer,
          renderMask, compareMask, aaShift);
        
      /* Now do secondary AA buffer, if enabled. */
      if(bInfo->buffInfo.enable2ndbuffer) {
        lfbMemoryConfigTemp =
          SST_RAW_LFB_TILE_BEGIN_PAGE_MUNGE((bInfo->buffInfo.colBuffStart1[colBufNum] >> 12))
            | HWC_RAW_LFB_STRIDE
            | (bInfo->buffInfo.bufStrideInTiles << SST_RAW_LFB_TILE_STRIDE_SHIFT);        
    
        if(chip == 0) {
          HWC_IO_STORE(bInfo->regInfo, lfbMemoryConfig, lfbMemoryConfigTemp);
        } else {
          HWC_IO_STORE_SLAVE(chip,bInfo->regInfo, lfbMemoryConfig, lfbMemoryConfigTemp);
        }  
                
        /* Read seconday AA buffer */
        hwcReadBufferFunc(bInfo, bInfo->regInfo.rawLfbBase + bInfo->buffInfo.colBuffStart1[colBufNum], bInfo->buffInfo.bufLfbStride, buffer,
            renderMask, compareMask, aaShift);
      }
        
      /* Restore lfbMemoryConfig */
      if(chip == 0) {
        HWC_IO_STORE(bInfo->regInfo, lfbMemoryConfig, lfbMemoryConfig);
      } else {
        HWC_IO_STORE_SLAVE(chip,bInfo->regInfo, lfbMemoryConfig, lfbMemoryConfig);
      }  
    
      /* Put chip back in temp location with the rest of the slaves. */
#if __POWERPC__
      hwcWriteConfigRegister(bInfo, chip, offsetof(SstPCIConfigRegs, cfgPciDecode),
              SST_PCI_IOBASE0_DECODE_256 | SST_PCI_MEMBASE0_DECODE_32MB | SST_PCI_MEMBASE1_DECODE_64MB);
#endif      
      hwcWriteConfigRegister(bInfo, chip, offsetof(SstPCIConfigRegs, memBaseAddr1),memBase1[1]);    

    } 
   
    /* Map everyone back */
    for(chip = 0; chip < bInfo->pciInfo.numChips; chip++) {
      hwcWriteConfigRegister(bInfo, chip, offsetof(SstPCIConfigRegs, memBaseAddr1),  memBase1[chip]);  
    }

    /* Re-enable stuff */
    for(chip = 0; chip < bInfo->pciInfo.numChips; chip++) {
      hwcWriteConfigRegister(bInfo, chip, offsetof(SstPCIConfigRegs, cfgInitEnable_FabID), cfgInitEnable[chip]);
      hwcWriteConfigRegister(bInfo, chip, offsetof(SstPCIConfigRegs, cfgSliLfbCtrl), cfgSliLfbCtrl[chip]);
      hwcWriteConfigRegister(bInfo, chip, offsetof(SstPCIConfigRegs, cfgAALfbCtrl),  cfgAALfbCtrl[chip]);
      hwcWriteConfigRegister(bInfo, chip, offsetof(SstPCIConfigRegs, cfgAADepthBufferAperture), cfgAADepthBufferAperture[chip]);
      hwcWriteConfigRegister(bInfo, chip, offsetof(SstPCIConfigRegs, cfgPciDecode),cfgPciDecode[chip]);
    }  
  } else {
    /* 32-bit case is easy.  We only have to read from the primary buffer on the master and let
     * the hardware do the rest */
    hwcReadBuffer8888(bInfo, bInfo->regInfo.rawLfbBase + bInfo->buffInfo.lfbBuffAddr0[colBufNum], bInfo->buffInfo.bufLfbStride, buffer,
        0x00, 0x00, 0);    
  }  

  /* Gamma correct image based on DAC contents. */
  hwcGammaCorrect(bInfo,buffer,bInfo->vidInfo.xRes,bInfo->vidInfo.yRes);

  /* Write buffer to disk */
  sprintf(fileName,"glide%04ld.tga",fileNameNum++);
  memset (header, 0, 18);
  header[2] = 2;    /* Uncompressed targa */
  header[12] = (FxU8)(bInfo->vidInfo.xRes & 255);
  header[13] = (FxU8)(bInfo->vidInfo.xRes >> 8);
  header[14] = (FxU8)(bInfo->vidInfo.yRes & 255);
  header[15] = (FxU8)(bInfo->vidInfo.yRes >> 8);
  header[16] = 24;  /* bytes per pixel */

  if(file = fopen(fileName,"wb")) {
    fwrite(header,18,1,file);
    fwrite(buffer,bInfo->vidInfo.xRes * bInfo->vidInfo.yRes * 3, 1, file);
    fclose(file);
  }

  /* Free memory */
  free(buffer);
}      

#define RED_SHIFT       16
#define GREEN_SHIFT     8
#define BLUE_SHIFT      0


#define CLAMP(val, min, max) if (val > max) val = max; else if (val < min) val = min;
#define ADJUST(val, lowest, low, high, typ) if (high < lowest) val=(typ)(low); else val = (typ)(high)
#define GETFLOATENV(s, v) if (GETENV(s)) v = (FxFloat)(atof(GETENV(s)))

/*---------------------------------------------------------------------------
 * Function    : adjustBrightnessAndContrast_m    
 *
 * Description :
 *               Routine to generate and apply a new gamma table based on 
 *               passed in Brightness and Contrast values.
 *               contrast is >=0.0
 *               Brightness may be negative.
 *---------------------------------------------------------------------------*/

static FxBool adjustBrightnessAndContrast_m(FxFloat contrast,
					    FxFloat brightness,
					    FxU32 nEntries,
					    FxU32 *pR, FxU32 *pG, FxU32 *pB)
{
  FxU16 i;
  FxFloat r,g,b;
  
  if (pR == NULL || pG == NULL || pG == NULL)
      return FXFALSE;
  
  GDBG_INFO(69, ":\tSlot\t\tRed\t\tGreen\t\tBlue\n");

  /* If the 0th row of the table contains non zero values then we get strange banding effects (Napalm) on
   * returning to the desktop to ensure this does not happen these values are intialised to zero.
   * Note this will not happen unless a brightness modifier is supplied, which highlighted the issue. */
   GDBG_INFO(69, "Note r[0]=g[0]=b[0]=special default \n");
   pB[0] = pG[0] = pR[0] = 0;

  for (i=1; i<nEntries; i++) 
  {
      /* Note to resolve rouding/sign errors, keep everything in the Fp domain until the last minute */

      /* R */
      r = (pR[i] * contrast) + brightness;
      ADJUST(pR[i], 0.0f, 0, r, FxU32);	
      CLAMP(pR[i], 0, 255);
      
      /* G */
      g = (pG[i] * contrast) + brightness;
      ADJUST(pG[i], 0.0f, 0, g, FxU32);	
      CLAMP(pG[i], 0, 255);
      
      /* B */
      b = (pB[i] * contrast) + brightness;
      ADJUST(pB[i], 0.0f, 0, b, FxU32);
      CLAMP(pB[i], 0, 255);

      GDBG_INFO(69, "\t%d\t\t%d\t\t%d\t\t%d\n", i, pR[i], pG[i], pB[i]);
  }
  
  return FXTRUE;
}
/* Gamma */


FxBool
hwcGammaTable(hwcBoardInfo *bInfo, FxU32 nEntries, FxU32 *r, FxU32 *g, FxU32 *b)
{
#define FN_NAME "hwcGammaTable"
  FxU32 gRamp[256];
  FxU32 i;
  FxU32 vidProcCfg;
  FxU32 dacBase;
  FxU32 rDacBase;
  FxU32 rDacData;
  char *psBrightness = "FX_GLIDE_BRIGHTNESS";
  char *psContrast = "FX_GLIDE_CONTRAST";
  
  /* Adjust Gamma as user selected */
  if (GETENV(psBrightness) || GETENV(psContrast))
  {
  	FxFloat brightness = 0.0f;
    	FxFloat contrast = 1.0f;
    	
    	/* override */
    	GETFLOATENV(psBrightness, brightness);
    	GETFLOATENV(psContrast, contrast);

	/* clamp contrast to > 0.0 */
	if (contrast <= 0.0f)
	{
		contrast = 1.0f;
		GDBG_INFO(69,": minihwc Readjusting contrast to %3.3f as <=0.0 \n", contrast);
	}

	GDBG_INFO(69,": minihwc Overriding Brightness with %3.3f and Contrast with %3.3f\n", brightness, contrast);

    	adjustBrightnessAndContrast_m(contrast, brightness, nEntries, r,g,b);
    }


  /* Load the table into the Display driver as above */
  for (i = 0; i < nEntries; i++) {
    gRamp[i] =
      ((r[i] & 0xff) << RED_SHIFT) |
        ((g[i] & 0xff) << GREEN_SHIFT) |  
          ((b[i] & 0xff) << BLUE_SHIFT);
		GDBG_INFO(69,": gRamp[%d] = %d\n", i, gRamp[i]);
  }
  
  /*
   **  On W9X/DOS, we can do this ourselves--which is much easier than
   **  mucking about with a bunch of 32-bit data in 16-bit driver
   **  code.
   */
  HWC_IO_LOAD( bInfo->regInfo, vidProcCfg, vidProcCfg);
  
  /* Determin which set of CLUT entries are selected */
  if (vidProcCfg & SST_OVERLAY_CLUT_SELECT)
    dacBase = 256;
  else
    dacBase = 0;
 
  /* Print out some useful info RE the vidProcCfg register */
  GDBG_INFO(80, "%s:  vidProcCFG(SST_OVERLAY_CLUT_SELECT) = %d\n",
            FN_NAME, (vidProcCfg & SST_OVERLAY_CLUT_SELECT) ? 1 : 0);
  GDBG_INFO(80, "%s:  vidProcCFG(SST_OVERLAY_EN) = %d\n",
            FN_NAME, (vidProcCfg & SST_OVERLAY_EN) ? 1 : 0);
  GDBG_INFO(80, "%s:  vidProcCFG(SST_OVERLAY_CLUT_BYPASS) = %d\n",
            FN_NAME, (vidProcCfg & SST_OVERLAY_CLUT_BYPASS) ? 1 : 0);

  for (i = 0; i < nEntries; i++) {
    int repeat = 100;
    while (repeat) {
      HWC_IO_STORE( bInfo->regInfo, dacAddr, dacBase + i);
      P6FENCE;
      HWC_IO_STORE( bInfo->regInfo, dacData, gRamp[i]);
      P6FENCE;
      HWC_IO_LOAD( bInfo->regInfo, dacAddr, rDacBase);
      P6FENCE;
      HWC_IO_LOAD( bInfo->regInfo, dacData, rDacData);
      P6FENCE;
      if ((rDacBase == (dacBase + i)) && (rDacData == gRamp[i]))
        break;
      repeat --;
    }
    if (!repeat) {
      GDBG_INFO(0, "%s: Error Writing DacData [%d, %x]. DacBase = %d\n",
                FN_NAME, i, gRamp[i], dacBase);
    }
  }

  return FXTRUE;
  
#if 0
  /*
   * Here lies the GDIish implementation of hwcGammaTable.
   * Although slower than just banging on the hardware, this
   * version is WinNT-friendly.
   */
  DDGAMMARAMP theRamp ;
  FxU32       index ;

  /*
   * Since the GDI SetDeviceGammaRamp has no nEntries argument
   * we may have to call GetDeviceGammaRamp first.
   */
  if (nEntries < 256)
    GetDeviceGammaRamp((HDC)bInfo->hdc, &theRamp) ; 

  for (index = 0 ;
       index < nEntries ;
       index++)
  {
    theRamp.red[index] = r[index] ;
    theRamp.green[index] = g[index] ;
    theRamp.blue[index] = b[index] ;
  }

  SetDeviceGammaRamp((HDC)bInfo->hdc, &theRamp) ;

  return FXTRUE ;
#endif

#undef FN_NAME
} /* hwcGammaTable */

FxBool
hwcGetGammaTable(hwcBoardInfo *bInfo, FxU32 nEntries, FxU32 *r, FxU32 *g, FxU32 *b)
{
#define FN_NAME "hwcGetGammaTable"
  FxU32 i;
  FxU32 vidProcCfg;
  FxU32 dacBase;
  FxU32 dacAddr ;
  FxU32 dacData ;
 
  /*
   * AJB- Don't believe the hype.  Although we can do this
   * ourselves on Win9x/DOS, it's actually a piece of cake
   * to call the GDI Gamma ramp interface. This non-GDIish
   * implementation is here because it is faster than 
   * calling the GDI function (which thunks to the display
   * driver).
   */
  HWC_IO_LOAD( bInfo->regInfo, vidProcCfg, vidProcCfg);
  
  /* Determine which set of CLUT entries are selected */
  if (vidProcCfg & SST_OVERLAY_CLUT_SELECT)
    dacBase = 256;
  else
    dacBase = 0;
 
  /* Print out some useful info RE the vidProcCfg register */
  GDBG_INFO(80, "%s:  vidProcCFG(SST_OVERLAY_CLUT_SELECT) = %d\n",
            FN_NAME, (vidProcCfg & SST_OVERLAY_CLUT_SELECT) ? 1 : 0);
  GDBG_INFO(80, "%s:  vidProcCFG(SST_OVERLAY_EN) = %d\n",
            FN_NAME, (vidProcCfg & SST_OVERLAY_EN) ? 1 : 0);
  GDBG_INFO(80, "%s:  vidProcCFG(SST_OVERLAY_CLUT_BYPASS) = %d\n",
            FN_NAME, (vidProcCfg & SST_OVERLAY_CLUT_BYPASS) ? 1 : 0);
  
  for (i = 0; i < nEntries; i++) 
  {
    int repeat = 100 ;

    do
    {
      HWC_IO_STORE(bInfo->regInfo, dacAddr, dacBase + i);
      P6FENCE;
      HWC_IO_LOAD(bInfo->regInfo, dacAddr, dacAddr);
      P6FENCE;
      HWC_IO_LOAD(bInfo->regInfo, dacData, dacData);
      P6FENCE;
    } while (--repeat && (dacAddr != dacBase + i)) ;

    if (!repeat) 
    {
      GDBG_INFO(0, "%s: Error Reading DacData [%d, %x]. DacBase = %d\n",
                FN_NAME, i, dacData, dacBase);
    }

    r[i] = (dacData >> RED_SHIFT) & 0xFF ;
    g[i] = (dacData >> GREEN_SHIFT) & 0xFF ;
    b[i] = (dacData >> BLUE_SHIFT) & 0xFF ;
  }

  return FXTRUE;
  
#if 0
  /*
   * Here lies the GDIish implementation of hwcGetGammaTable.
   * Although slower than just banging on the hardware, this
   * version is WinNT-friendly.
   */
  DDGAMMARAMP theRamp ;
  FxU32       index ;

  GetDeviceGammaRamp((HDC)bInfo->hdc, &theRamp) ; 

  for (index = 0 ;
       index < nEntries ;
       index++)
  {
    r[index] = theRamp.red[index] ;
    g[index] = theRamp.green[index] ;
    b[index] = theRamp.blue[index] ;
  }

  return FXTRUE ;
#endif
  
#undef FN_NAME
} /* hwcGetGammaTable */


FxBool
hwcGammaRGB(hwcBoardInfo *bInfo, float gammaR, float gammaG, float gammaB)
{
#define FN_NAME "hwcGammaRGB"
  FxU32
    grRamp[256], ggRamp[256], gbRamp[256];
  int
    i;

  GDBG_INFO(69, FN_NAME "(0x%x, %1.2f, %1.2f, %1.2f)\n",
            bInfo, gammaR, gammaG, gammaB);

  /*
  ** NB:  The system eventually devised by Bob and Ken *may* require
  ** separate R, G, and B vectors.
  */

  for (i = 0; i < 256; i++) {
    grRamp[i] = (FxU32)((pow(i/255.0F, 1.0F/gammaR)) * 255.0F + 0.5F);
    ggRamp[i] = (FxU32)((pow(i/255.0F, 1.0F/gammaG)) * 255.0F + 0.5F);
    gbRamp[i] = (FxU32)((pow(i/255.0F, 1.0F/gammaB)) * 255.0F + 0.5F);
  }

  hwcGammaTable(bInfo, 256, grRamp, ggRamp, gbRamp); 

  /*
  **  Now that we have a gamma table, we can give it to the driver via
  **  a call to ExtEscape() when that is defined.....
  */
  return FXFALSE;

#undef FN_NAME
} /* hwcGammaRGB */


#define M 1
#define K 1

FxBool
hwcSetGrxClock(hwcBoardInfo *bInfo, FxU32 speedInMHz)
{
#define FN_NAME "hwcSetGrxClock"
  FxU32
    pllCtrl1,
    dramInit0 = 0xc17ae29, 
    dramInit1 = 0x26c031,
    n,
    m = 1;

  n = (FxU32) ((speedInMHz - 4.76f)/2.38f);

  pllCtrl1 =
    (K << SST_PLL_K_SHIFT) | (m << SST_PLL_M_SHIFT) | (n << SST_PLL_N_SHIFT);

  GDBG_INFO(80, "%s:  Setting Graphics Clock to %d\n", FN_NAME, speedInMHz);

  HWC_IO_STORE( bInfo->regInfo, dramInit0, dramInit0);
  HWC_IO_STORE( bInfo->regInfo, dramInit1, dramInit1);
  HWC_IO_STORE( bInfo->regInfo, pllCtrl1, pllCtrl1);
  
  return FXTRUE;

#undef FN_NAME  
} /* hwcSetGrxClock */

FxBool
hwcSetMemClock(hwcBoardInfo *bInfo, FxU32 speedInMHz)
{
#define FN_NAME "hwcSetMemClock"

  return FXFALSE;
#undef FN_NAME  
} /* hwcSetMemClock */


FxBool
hwcResolutionSupported(hwcBoardInfo *bInfo, GrScreenResolution_t res, GrScreenRefresh_t ref)
{
#define FN_NAME "hwcResolutionSupported"
  static char *resNames[] = {
    "GR_RESOLUTION_320x200",
    "GR_RESOLUTION_320x240",
    "GR_RESOLUTION_400x256",
    "GR_RESOLUTION_512x384",
    "GR_RESOLUTION_640x200",
    "GR_RESOLUTION_640x350",
    "GR_RESOLUTION_640x400",
    "GR_RESOLUTION_640x480",
    "GR_RESOLUTION_800x600",
    "GR_RESOLUTION_960x720",
    "GR_RESOLUTION_856x480",
    "GR_RESOLUTION_512x256",
    "GR_RESOLUTION_1024x768",
    "GR_RESOLUTION_1280x1024",
    "GR_RESOLUTION_1600x1200",
    "GR_RESOLUTION_400x300",
    "GR_RESOLUTION_1152x864",
    "GR_RESOLUTION_1280x960",
    "GR_RESOLUTION_1600x1024",
    "GR_RESOLUTION_1792x1344",
    "GR_RESOLUTION_1856x1392",
    "GR_RESOLUTION_1920x1440",
    "GR_RESOLUTION_2048x1536",
    "GR_RESOLUTION_2048x2048"
  };

#if 0
  struct WidthHeight_s {
    FxU32 width; 
    FxU32 height;
  } whByRes[] = {
    {320, 200},                 /* GR_RESOLUTION_320x200 */
    {320, 240},                 /* GR_RESOLUTION_320x240 */
    {400, 256},                 /* GR_RESOLUTION_400x256 */
    {512, 384},                 /* GR_RESOLUTION_512x384 */
    {640, 200},                 /* GR_RESOLUTION_640x200 */
    {640, 350},                 /* GR_RESOLUTION_640x350 */
    {640, 400},                 /* GR_RESOLUTION_640x400 */
    {640, 480},                 /* GR_RESOLUTION_640x480 */
    {800, 600},                 /* GR_RESOLUTION_800x600 */
    {960, 720},                 /* GR_RESOLUTION_960x720 */
    {856, 480},                 /* GR_RESOLUTION_856x480 */
    {512, 256},                 /* GR_RESOLUTION_512x256 */
    {1024, 768},                /* GR_RESOLUTION_1024x768 */
    {1280, 1024},               /* GR_RESOLUTION_1280x1024 */
    {1600, 1200},               /* GR_RESOLUTION_1600x1200 */
    {400, 300},                 /* GR_RESOLUTION_400x300 */
    {1152, 864},                /* GR_RESOLUTION_1152x864 */
    {1280, 960},                /* GR_RESOLUTION_1280x960 */
    {1600, 1024},               /* GR_RESOLUTION_1600x1024 */
    {1792, 1344},               /* GR_RESOLUTION_1792x1344 */
    {1856, 1392},               /* GR_RESOLUTION_1856x1392 */
    {1920, 1440},               /* GR_RESOLUTION_1920x1440 */
    {2048, 1536},               /* GR_RESOLUTION_2048x1536 */
    {2048, 2048}                /* GR_RESOLUTION_2048x2048 */
  };
#endif  

  static char *refresh[] = {
    "GR_REFRESH_60Hz",
    "GR_REFRESH_70Hz",
    "GR_REFRESH_72Hz",
    "GR_REFRESH_75Hz",
    "GR_REFRESH_80Hz",
    "GR_REFRESH_90Hz",
    "GR_REFRESH_100Hz",
    "GR_REFRESH_85Hz",
    "GR_REFRESH_120Hz"    
  };


  GDBG_INFO(80, FN_NAME ":  res == %s (0x%x) ref == %s, supported == %s\n",
            resNames[res], resolutionSupported[bInfo->boardNum][res][ref], refresh[ref],
            resolutionSupported[bInfo->boardNum][res][ref] ? "FXTRUE" : "FXFALSE");
  

  /* Glide has very good checking to see if the memory required is
  available, so we'll just return whether the driver can do it. */
  return resolutionSupported[bInfo->boardNum][res][ref];

#undef FN_NAME
} /* hwcResolutionSupported */

#ifdef __WIN32__
static char *
getRegPath() 
{
  char *retVal = NULL;
  OSVERSIONINFO ovi;
  
  ovi.dwOSVersionInfoSize = sizeof ( ovi );
  GetVersionEx ( &ovi );
  if (ovi.dwPlatformId == VER_PLATFORM_WIN32_NT) {
    HKEY hKey;
    DWORD type ;
    static char strval[255];
    DWORD szData = sizeof(strval) ;

    GDBG_INFO(80, "OS == WNT\n");

    /* Go fishing for the registry path on Win2K */
    if (RegOpenKey(HKEY_LOCAL_MACHINE, "HARDWARE\\DEVICEMAP\\VIDEO", &hKey) == ERROR_SUCCESS)
    {
      if (RegQueryValueEx(hKey, "\\Device\\Video0", NULL, &type, strval, &szData) ==
          ERROR_SUCCESS)
      {
        if (type != REG_SZ)
        {
          /* It is hardcoded on NT via Display Control code. see:
           * $/devel/swtools/bansheecp2 */
          retVal = "SYSTEM\\CurrentControlSet\\Services\\3Dfx\\Device0\\glide";
        }
         else
         {
          strcat(strval, "\\glide") ;
          retVal = (char*)((int)strval + strlen("\\REGISTRY\\Machine\\")) ;
         }
      }
       else
         retVal = "SYSTEM\\CurrentControlSet\\Services\\3Dfx\\Device0\\glide";

      RegCloseKey(hKey);
    }
  } else {
    QDEVNODE QDevNode;
    QIN Qin;
    int status;

    GDBG_INFO(80, "OS == W9X\n");

    Qin.dwSubFunc = QUERYDEVNODE;
    {
      HDC curDC = GetDC(NULL);

      status = ExtEscape ( curDC, QUERYESCMODE, 
                           sizeof(Qin), (LPCSTR)&Qin, 
                           sizeof(QDevNode), (LPSTR)&QDevNode );
      ReleaseDC(NULL, curDC);
    }

    if ( status > 0 ) {
      static char regPath[255];

      CM_Get_DevNode_Key( QDevNode.dwDevNode, NULL, 
                          &regPath, sizeof(regPath), 
                          CM_REGISTRY_SOFTWARE );
      strcat(regPath, "\\glide");

      retVal = regPath;
    }
  }

  return retVal;
} /* getRegPath */
#endif

char *
hwcGetenv(char *a) 
{
#if __WIN32__
  char *retVal = NULL;
  static char *regPath;
  HKEY hKey;
  DWORD type ;
  DWORD szData = 255 ;
  static char strval[255];

  /* This should work for both NT and Win95/98 (getRegPath works) */
  if (retVal = getenv(a))
    return retVal;
  
  szData = sizeof(strval);

  if (regPath == NULL) {
    regPath = getRegPath();
    
    GDBG_INFO(80, "_grGetEnv:  regPath = %s\n", regPath);

    if (regPath == NULL)
      return NULL;
  } 
  
  if (RegOpenKey(HKEY_CURRENT_USER, regPath, &hKey) == ERROR_SUCCESS) {
    if (RegQueryValueEx(hKey, a, NULL, &type, strval, &szData) ==
        ERROR_SUCCESS) {
      if (type != REG_SZ) {
        retVal = NULL;
      } else {
        retVal = strval;
      }
    }
    RegCloseKey(hKey);
  }
  
  if ((retVal == NULL) &&
     RegOpenKey(HKEY_LOCAL_MACHINE, regPath, &hKey) == ERROR_SUCCESS)
  {
    if (RegQueryValueEx(hKey, a, NULL, &type, strval, &szData) ==
        ERROR_SUCCESS) {
      if (type != REG_SZ) {
        retVal = NULL;
      } else {
        retVal = strval;
      }
    }
    RegCloseKey(hKey);
  }
  return (char*)retVal;
#else
  return getenv(a);
#endif
} /* _grGetenv */

FxU32
hwcQueryContext(hwcBoardInfo *bInfo)
{
#define FN_NAME "hwcQueryContext"
  FxU32
    retVal = FXTRUE;

#if HWC_EXT_INIT
  {
    if( HWCEXT_PROTOCOL( bInfo->boardNum ) )
    {
      hwcExtRequest_t ctxReq;
      hwcExtResult_t ctxRes;
      GDBG_INFO(80, FN_NAME ":  ExtEscape:HWCEXT_QUERYCONTEXT\n");
      ctxReq.which = HWCEXT_QUERYCONTEXT;
      ExtEscape((HDC)bInfo->hdc, HWCEXT_ESCAPE(bInfo->boardNum), /**/
                        sizeof(ctxReq), (LPSTR) &ctxReq,
                        sizeof(ctxRes), (LPSTR) &ctxRes);
      retVal = (ctxRes.resStatus != HWC_CONTEXT_LOST);
    }
    else
    {
      retVal = *((FxU32*)bInfo->lostContextDWORD);
    }
  }
#endif /* HWC_EXT_INIT */

  return retVal;
#undef FN_NAME
} /* hwcQueryContext */

FxU32
hwcShareContextData(hwcBoardInfo *bInfo, FxU32 **data)
{
#define FN_NAME "hwcShareContextData"
  FxU32
    retVal = FXTRUE;
#if HWC_EXT_INIT
  hwcExtRequest_t ctxReq;
  hwcExtResult_t  ctxRes;

  GDBG_INFO(80, FN_NAME "\n");  

  if( HWCEXT_PROTOCOL( bInfo->boardNum ) )
  {
    if (bInfo->osNT) {
      hwcExtRequest_t
        ctxReq;
      hwcExtResult_t
        ctxRes;


      curBI = bInfo;
      ctxReq.optData.contextDwordNTReq.procId = GetCurrentProcessId();


      GDBG_INFO(80, FN_NAME ":  NT Branch\n");  
      {
        FxU32 ohWell;

        ctxReq.which = HWCEXT_CONTEXT_DWORD_NT;


        /* Now for the NASTY stuff: */
        __asm  mov eax, 0;
        __asm  mov ax, cs;
        __asm  mov ohWell, eax;

        ctxReq.optData.contextDwordNTReq.codeSegment = ohWell;

        __asm  mov eax, 0;
        __asm  mov ax, ds;
        __asm  mov ohWell, eax;
    
        ctxReq.optData.contextDwordNTReq.dataSegment = ohWell;

        /* oh, yeah */
      }
      GDBG_INFO(80, FN_NAME ":  Calling ExtEscape(HWCEXT_CONTEXT_DWORD_NT)\n");  
      ExtEscape((HDC) bInfo->hdc, HWCEXT_ESCAPE(bInfo->boardNum), sizeof(ctxReq), (void *) &ctxReq,
                sizeof(ctxRes), (void *) &ctxRes);
    
    
      *data = (FxU32 *) ctxRes.optData.contextDwordNTRes.dwordOffset;

    } else {
      /* context DWORD is rather poorly named now, but oh, well. */
      ctxReq.which = HWCEXT_SHARE_CONTEXT_DWORD;
          
      /*ctxReq.optData.contextDwordNTReq.procId = GetCurrentProcessId();*/

      bInfo->contextHandle = GetCurrentProcessId ();

      /* Piggy back the context handle on the unmapmemory structure for 
       * safety
           *
           * XXX:FIXME!! Add procId to 9x shareContext structure
       */
      ctxReq.optData.unmapMemoryReq.procHandle = bInfo->contextHandle;

      /* MDM-Richardson - Removed because it corrupts the req structure that
       * gets passed down through the ExtEscape.  Theory is that it messes 
       * with the LPSTR pointer due to a NULL 
       */
      /* ctxReq.Ext.optData.shareContextDWORDReq.contextDWORD =
        (FxU32) &bInfo->lostContextDWORD; */
    
      retVal = ExtEscape((HDC)bInfo->hdc, HWCEXT_ESCAPE(bInfo->boardNum), /**/
                         sizeof(ctxReq), (LPSTR) &ctxReq,
                       sizeof(ctxRes), (LPSTR) &ctxRes);
    
      if (retVal == 0xffffffff || ctxRes.resStatus == 0xffffffff )
        *data = &dummyContextDWORD;
      else
        *data = (FxU32 *) ctxRes.optData.shareContextDWORDRes.contextDWORD;
    }
    
    GDBG_INFO(80, FN_NAME ":  pointer to context = 0x%x\n",
              ctxRes.optData.shareContextDWORDRes.contextDWORD); 
  }
#endif
#if HWC_GDX_INIT
  *data = &dummyContextDWORD;
#endif
  return retVal;
#undef FN_NAME
} /* hwcShareContextData */

#ifdef HWC_EXT_INIT
void
hwcUnmapMemory() 
{
  FxU32 i;
  hwcExtRequest_t ctxReq;
  hwcExtResult_t  ctxRes;

  if ( curBI ) {
    if ( curBI->osNT ) {
      hwcExtRequest_t
        ctxReq;
      hwcExtResult_t
        ctxRes;
      ctxReq.which = HWCEXT_UNMAP_MEMORY;
      
      /* Assure that we free up the node by passing the known Process ID that
         was used to open the context
      */
      ctxReq.optData.unmapMemoryReq.procHandle = GetCurrentProcessId();
      
          ExtEscape((HDC)curBI->hdc, HWCEXT_ESCAPE(curBI->boardNum), 
                     sizeof(ctxReq), (LPSTR) &ctxReq,
                            sizeof(ctxRes), (LPSTR) &ctxRes);
      curBI->isMapped = FXFALSE;
    }
    curBI = NULL;
  }
  else {
    for(i=0;i<hInfo.nBoards;i++)
      {
        ctxReq.which = HWCEXT_UNMAP_MEMORY;
        ctxReq.optData.unmapMemoryReq.procHandle = (ULONG)GetCurrentProcessId();
        GDBG_INFO(80, "hwcUnmapMemory:  Calling ExtEscape(HWCEXT_UNMAP_MEMORY)\n");  
        ExtEscape((HDC)hInfo.boardInfo[i].hdc, HWCEXT_ESCAPE(i), /**/
                  sizeof(ctxReq), (LPSTR) &ctxReq,
                  sizeof(ctxRes), (LPSTR) &ctxRes);
        hInfo.boardInfo[i].isMapped = FXFALSE;
      }
  }
} /* hwcUnmapMemory */

void
hwcUnmapMemory9x(hwcBoardInfo *bInfo) 
{
#ifdef HWC_EXT_INIT
  hwcExtRequest_t ctxReq;
  hwcExtResult_t  ctxRes;

  ctxReq.which = HWCEXT_UNMAP_MEMORY;
  ctxReq.optData.unmapMemoryReq.procHandle = bInfo->contextHandle;

  /* Assure that we free up the node by passing the known Process ID that
     was used to open the context
  */
        
  ExtEscape((HDC)bInfo->hdc, HWCEXT_ESCAPE(bInfo->boardNum), 
            sizeof(ctxReq), (LPSTR) &ctxReq,
            sizeof(ctxRes), (LPSTR) &ctxRes);
  
  bInfo->isMapped = FXFALSE;
  /* Catch dumb bugs.  Nuke all linear register pointers. */

  
#endif // #ifdef HWC_EXT_INIT
} /* hwcUnmapMemory9x */

void
hwcClearContextData() 
{
#define FN_NAME "hwcClearContextData"
  return;
#undef FN_NAME
} /* hwcClearContextData */
#endif

void
hwcIdleWinFifo(hwcBoardInfo*     bInfo,
               const HwcWinFifo* fifo,
               const FxU32       serialNumber)
{
#if HWC_EXT_INIT || HWC_GDX_INIT
  while(hwcExecuteStatusWinFifo(bInfo, 
                                fifo,
                                serialNumber) != serialNumber) {
    /* Do Nothing? */;
  }
  if(fifo->fifoType == HWCEXT_FIFO_HOST) {
    FxU32 status;
    /* %%KCD - Hack.  In the host memory fifo case, we don't have a sentinal, so
       we just idle right here.  It's not a perfect soluction on a preemptive OS 
       since the hardware may take a long time to idle, but the host memory fifo
       case is going to suck for speed anyway.  Note that I don't look for all
       chips to idle since we never use windowed mode and SLI at the same time. */      
    do {
      HWC_SST_LOAD(bInfo->regInfo, status, status);        
    } while((status & SST_BUSY) != 0);      
  }
#endif
}
#if HWC_GDX_INIT
void
hwcCheckTarget(FxU32 sfcOffset, FxU32 sfcWidth, FxU32 sfcHeight,
               FxU32 sfcDepth, FxU32 auxFifoStart, FxU32 auxFifoSize)
{
}
#endif

#if HWC_EXT_INIT

void
hwcCheckTarget(FxU32 sfcOffset, FxU32 sfcWidth, FxU32 sfcHeight,
               FxU32 sfcDepth, FxU32 auxFifoStart, FxU32 auxFifoSize)
{
#define FN_NAME "hwcCheckTarget"
#ifdef GDBG_INFO_ON
  hwcBoardInfo *bI = &hInfo.boardInfo[0];
  FxU32
    winFifoBase, winFifoSize;
  FxU32
    vidProcCfg, vidScreenSize,
    vidDesktopStartAddr, vidDesktopOverlayStride,
    baseAddrL, baseSize,
    lfbMemoryConfig;
  FxU32
    shiftAdd,
    sfcEnd, winFifoEnd, auxFifoEnd,
    screenWidth, screenHeight,
    dtPixelFormat, 
    dtPixDepth, 
    dtStride,
    tileBase, tileStride,
    desktopBase, desktopEnd, desktopStride;


  /*
  ** Compute a bunch of stuff we'll need later...
  */

  /* Compute some convenient values */
  sfcEnd = sfcOffset + (sfcWidth * sfcHeight * sfcDepth / 8) - 1;
  auxFifoEnd = auxFifoSize + auxFifoSize;

  /* Compute base address and size of windows FIFO */
  HWC_CAGP_LOAD(bI->regInfo, cmdFifo0.baseAddrL, baseAddrL);
  HWC_CAGP_LOAD(bI->regInfo, cmdFifo0.baseSize, baseSize);
  winFifoBase = baseAddrL;
  winFifoSize = ((baseSize & SST_BASESIZE) >> SST_BASESIZE_SHIFT);
  winFifoEnd = winFifoBase + winFifoSize;


  /* Compute global tile stride */
  HWC_IO_LOAD(bI->regInfo, lfbMemoryConfig, lfbMemoryConfig);
  tileBase =
    (
     (lfbMemoryConfig & SST_RAW_LFB_TILE_BEGIN_PAGE) >>
     SST_RAW_LFB_TILE_BEGIN_PAGE_SHIFT
     );
  
  shiftAdd =
    ((lfbMemoryConfig & SST_RAW_LFB_ADDR_STRIDE) >>
      SST_RAW_LFB_ADDR_STRIDE_SHIFT);

  tileStride = (1 << (10 + shiftAdd));

  /* Get relevant info from vidProcCfg */
  HWC_IO_LOAD(bI->regInfo, vidProcCfg, vidProcCfg);
  dtPixelFormat = vidProcCfg & SST_DESKTOP_PIXEL_FORMAT;
  switch (dtPixelFormat) {
  case SST_DESKTOP_PIXEL_PAL8:
    dtPixDepth = 1;
    break;
  case SST_DESKTOP_PIXEL_RGB565:
    dtPixDepth = 2;
    break;
  case SST_DESKTOP_PIXEL_RGB24:
    dtPixDepth = 3;
    break;
  case SST_DESKTOP_PIXEL_RGB32:
    dtPixDepth = 4;
    break;
  }
  
  /* Compute Screen Size */
  HWC_IO_LOAD(bI->regInfo, vidScreenSize, vidScreenSize);
  screenWidth =
    (
     (vidScreenSize & SST_VIDEO_SCREEN_WIDTH) >>
     SST_VIDEO_SCREEN_WIDTH_SHIFT
     );
  screenHeight =
    (
     (vidScreenSize & SST_VIDEO_SCREEN_HEIGHT) >>
     SST_VIDEO_SCREEN_HEIGHT_SHIFT
     );
  
  /* Compute the end of the surface */

  /* Compute the desktop start and size (possibly width, too) */
  HWC_IO_LOAD(bI->regInfo,  vidDesktopStartAddr, vidDesktopStartAddr);
  desktopBase = vidDesktopStartAddr;

  HWC_IO_LOAD(bI->regInfo,  vidDesktopOverlayStride, vidDesktopOverlayStride);
  dtStride = vidDesktopOverlayStride & 0x7fff;

  if (desktopBase > tileBase) {
    desktopStride = dtStride << 7;
  } else {
    desktopStride = dtStride;
  }
  
  desktopEnd = desktopBase + screenWidth * screenHeight * dtPixDepth / 8;

  /* ++++ the CONSTANT below needs to be a variable--CHD */
  if (sfcOffset > 0x2000000) {
    GDBG_INFO(80, FN_NAME ":  surface offset greater than memory range\n");
    goto __errSurfaceFifo;
  }


  /* 
  **  Check for the Very Bad Things...
  ** 
  ** XXdwm  Why not just more simply check for interval overlap?  
  **        E.g. "!(Abegin >= Bend || Bbegin >= Aend)"
  */
  if (sfcOffset > tileBase) {   /* Tiled  case */
    /* Does it start in the windows FIFO? No:FIFOs can't be in tiled memory */
    /* Does it run into the windows FIFO? No:FIFOs can't be in tiled memory */
    /* Does it start in the aux FIFO? No:FIFOs can't be in tiled memory */
    /* Does it run into the aux FIFO? No:FIFOs can't be in tiled memory */


    /* Does it start in the desktop? */    
    /* Tiled memory is linear, so we have to check for overlapping
       rectangles.   */
    if (sfcOffset >= desktopBase && sfcOffset < desktopEnd) {
      GDBG_INFO(80, FN_NAME ":  Surface starts in desktop\n");
      goto __errSurfaceFifo;
    }

    /* Does it run into the desktop? */    
    if (sfcEnd > desktopBase && sfcEnd <= desktopEnd) {
      GDBG_INFO(80, FN_NAME ":  Surface ends in desktop\n");
      goto __errSurfaceFifo;
    }

  } else {                      /* Linear case */
    GDBG_INFO(80, FN_NAME ":  Linear Surface\n");

    /* Does it start in the windows FIFO? */    
    if (sfcOffset >= winFifoBase && sfcOffset < winFifoEnd) {
      GDBG_INFO(80, FN_NAME ":  Surface starts in Windows FIFO\n");
      goto __errSurfaceFifo;
    }

    /* Does it run into the windows FIFO? */
    if (sfcEnd > winFifoBase && sfcEnd <= winFifoEnd) {
      GDBG_INFO(80, FN_NAME ":  Surface runs into Windows FIFO\n");
      goto __errSurfaceFifo;
    }

    /* Does it start in the desktop? */
    if (sfcOffset >= desktopBase && sfcOffset < desktopEnd) {
      GDBG_INFO(80, FN_NAME ":  Surface starts in desktop\n");
      goto __errSurfaceFifo;
    }

    /* Does it run into the desktop? */
    if (sfcEnd > desktopBase && sfcEnd <= desktopEnd) {
      GDBG_INFO(80, FN_NAME ":  Surface ends in desktop\n");
      goto __errSurfaceFifo;
    }

    /* Does it start in the aux FIFO? */
    if (sfcOffset >= auxFifoStart && sfcOffset < auxFifoEnd) {
      GDBG_INFO(80, FN_NAME ":  Surface starts in aux FIFO\n");
      goto __errSurfaceFifo;
    }

    /* Does it run into the aux FIFO? */
    if (sfcEnd > auxFifoStart && sfcEnd <= auxFifoEnd) {
      GDBG_INFO(80, FN_NAME ":  Surface starts in aux FIFO\n");
      goto __errSurfaceFifo;
    }
  }
  
  return;

 __errSurfaceFifo:
  GDBG_INFO(80, FN_NAME ":  sfcStart = 0x%x, sfcEnd = 0x%x\n",
            sfcOffset, sfcEnd);
  exit(-1);
#endif /* GDBG_INFO_ON */
  return;
#undef FN_NAME
} /* hwcCheckTarget */

#endif /* HWC_EXT_INIT */

/* This routine only really works on Napalm since someone decided to change the register
 * layout from Voodoo3.  Redefine them here. */
#undef SST_SIPROCESS_OSC_CNTR_RUN         
#undef SST_SIPROCESS_OSC_NOR_SEL          
#undef SST_SIPROCESS_OSC_FORCE_ENABLE     

#define SST_SIPROCESS_OSC_CNTR_RUN         BIT(29)
#define SST_SIPROCESS_OSC_NOR_SEL          BIT(30)
#define SST_SIPROCESS_OSC_FORCE_ENABLE     BIT(31)

void hwcCalcSipValue(hwcBoardInfo *bInfo, FxU32 chipNum, FxU32 *nandChain, FxU32 *norChain)
{
  FxU32 pllCtrl1, pllCtrl1_save;
  FxU32 sipMonitor, temp;

  int min, max, iters;     // some storage vars
  FxI32 count, val;
static  FxI32 valarray[SST_SIPROCESS_OSC_CNTR + 1];    // is this how you do an array? God, I suck...

  int i;                   // some misc vars

  double total, E, SD, VAR, N, avg;   // these might have to be floats instead of ints

  // Don't do anything stupid. 
  if(chipNum >= bInfo->pciInfo.numChips) {
    *nandChain = 0;
    *norChain = 0;
    return;
  }
  // Okay, this is ripped from our diag environment, so 
  // obviously isn't going to necessarily work in this case...
  // This is just to get the base addresses into a var.

  // Read out old PLL value so we can restore it later.
  pllCtrl1 = 0x3205; // 125Mhz
  if(chipNum > 0) {
    HWC_IO_LOAD_SLAVE(chipNum, bInfo->regInfo, pllCtrl1, pllCtrl1_save);
    HWC_IO_STORE_SLAVE(chipNum, bInfo->regInfo, pllCtrl1, pllCtrl1);
  } else {
    HWC_IO_LOAD(bInfo->regInfo, pllCtrl1, pllCtrl1_save);
    HWC_IO_STORE(bInfo->regInfo, pllCtrl1, pllCtrl1);
  }  

  // set number of iterations
  iters = 1000;

  // initialize the storage array
  for (i=0; i<(SST_SIPROCESS_OSC_CNTR + 1); i++) {
	 valarray[i] = 0;
  }

  // start nand chain test
  min = 0; max = 0;
  for (i=0; i<iters; i++) {
    // program to count for 256 grxclk cycles
    count = 0x0ff;

    // write reset and count to SIPMONITOR register
    sipMonitor = count << SST_SIPROCESS_PCI_CNTR_SHIFT;
    if(chipNum > 0) {
      HWC_IO_STORE_SLAVE(chipNum, bInfo->regInfo, sipMonitor, sipMonitor | SST_SIPROCESS_OSC_CNTR_RESET_N | SST_SIPROCESS_OSC_NAND_SEL);
      HWC_IO_STORE_SLAVE(chipNum, bInfo->regInfo, sipMonitor, sipMonitor | SST_SIPROCESS_OSC_CNTR_RESET_N | SST_SIPROCESS_OSC_NAND_SEL);
      HWC_IO_LOAD_SLAVE(chipNum, bInfo->regInfo, sipMonitor, temp);
      HWC_IO_STORE_SLAVE(chipNum, bInfo->regInfo, sipMonitor, sipMonitor | SST_SIPROCESS_OSC_CNTR_RUN | SST_SIPROCESS_OSC_NAND_SEL);
    } else {
      HWC_IO_STORE(bInfo->regInfo, sipMonitor, sipMonitor | SST_SIPROCESS_OSC_CNTR_RESET_N | SST_SIPROCESS_OSC_NAND_SEL);
      HWC_IO_STORE(bInfo->regInfo, sipMonitor, sipMonitor | SST_SIPROCESS_OSC_CNTR_RESET_N | SST_SIPROCESS_OSC_NAND_SEL);
      HWC_IO_LOAD(bInfo->regInfo, sipMonitor, temp);
      HWC_IO_STORE(bInfo->regInfo, sipMonitor, sipMonitor | SST_SIPROCESS_OSC_CNTR_RUN | SST_SIPROCESS_OSC_NAND_SEL);
    } 

    while (count != 0) {
      // read back countdown counter to see when countdown has ended
      if(chipNum > 0) {
        HWC_IO_LOAD_SLAVE(chipNum, bInfo->regInfo, sipMonitor, count);
      } else {
        HWC_IO_LOAD(bInfo->regInfo, sipMonitor, count);
      }   
      count = (count & SST_SIPROCESS_PCI_CNTR) >> SST_SIPROCESS_PCI_CNTR_SHIFT;
    }
	 
    // read back actual SIP nand count
    if(chipNum > 0) {
      HWC_IO_LOAD_SLAVE(chipNum, bInfo->regInfo, sipMonitor, val);
    } else {
      HWC_IO_LOAD(bInfo->regInfo, sipMonitor, val);
    } 

    val &= SST_SIPROCESS_OSC_CNTR;

    // some statistics here
    if (val < min) { min = val; }
    if (val > max) { max = val; }
	 
    valarray[val]++;   // Do you have to initialize the array first? I forget...
  }

  // Please change the formatting of any text to however you see fit
  //printf("\n\n--- Process Values (NAND chain) ---\n");
  //printf("\n sip value: occurences (probability)\n");
  total = 0.0f;
  for (i = 0; i <= max; i++) {
    if (valarray[i] != 0) {
      //printf("  %4d: %4d (%f)\n", i, valarray[i], ((float)valarray[i])/iters);
      total += i * valarray[i];
    }
  }
  
  // some statistical stuff
  E = total / iters;
  total = 0;
  for (i = 0; i <= max; i++) {
    if (valarray[i] != 0) {
      total += (i - E)*(i - E) * valarray[i];
    }
  }

  VAR = total / iters;
  SD  = sqrt(VAR);    // how do you do sqrt??

  total = 0; N = 0;
  for (i = 0; i <= max; i++) {
    if ((valarray[i] != 0) && (i >= (E - SD)) && (i <= (E + SD))) {
      total += i * valarray[i];
      N += valarray[i];
    }
  }
  avg = total / N;

  //printf("E   = %g\n", E);
  //printf("VAR = %g\n", VAR);
  //printf("SD  = %g\n", SD);
  //printf("NAND avg = %d (using %d values about E)\n", (FxU32)avg, N);
	 
  *nandChain = (FxU32)avg;

  // initialize the storage array
  for (i=0; i<(SST_SIPROCESS_OSC_CNTR + 1); i++) {
    valarray[i] = 0;
  }

  // start nor chain test
  min = 0; max = 0;
  for (i=0; i<iters; i++) {
    // program to count for 256 grxclk cycles
    count = 0x0ff;

    // write reset and count to SIPMONITOR register
    sipMonitor = count << SST_SIPROCESS_PCI_CNTR_SHIFT;
    if(chipNum > 0) {        
      HWC_IO_STORE_SLAVE(chipNum, bInfo->regInfo, sipMonitor, sipMonitor | SST_SIPROCESS_OSC_CNTR_RESET_N | SST_SIPROCESS_OSC_NOR_SEL);
      HWC_IO_STORE_SLAVE(chipNum, bInfo->regInfo, sipMonitor, sipMonitor | SST_SIPROCESS_OSC_CNTR_RESET_N | SST_SIPROCESS_OSC_NOR_SEL);
      HWC_IO_LOAD_SLAVE(chipNum, bInfo->regInfo, sipMonitor, temp);
      HWC_IO_STORE_SLAVE(chipNum, bInfo->regInfo, sipMonitor, sipMonitor | SST_SIPROCESS_OSC_CNTR_RUN | SST_SIPROCESS_OSC_NOR_SEL);
    } else {
      HWC_IO_STORE(bInfo->regInfo, sipMonitor, sipMonitor | SST_SIPROCESS_OSC_CNTR_RESET_N | SST_SIPROCESS_OSC_NOR_SEL);
      HWC_IO_STORE(bInfo->regInfo, sipMonitor, sipMonitor | SST_SIPROCESS_OSC_CNTR_RESET_N | SST_SIPROCESS_OSC_NOR_SEL);
      HWC_IO_LOAD(bInfo->regInfo, sipMonitor, temp);
      HWC_IO_STORE(bInfo->regInfo, sipMonitor, sipMonitor | SST_SIPROCESS_OSC_CNTR_RUN | SST_SIPROCESS_OSC_NOR_SEL);
    }    

    while (count != 0) {
      // read back countdown counter to see when countdown has ended
      if(chipNum > 0) {
        HWC_IO_LOAD_SLAVE(chipNum, bInfo->regInfo, sipMonitor, count);
      } else {
        HWC_IO_LOAD(bInfo->regInfo, sipMonitor, count);
      }  
      count = (count & SST_SIPROCESS_PCI_CNTR) >> SST_SIPROCESS_PCI_CNTR_SHIFT;
    }
	 
    // read back actual SIP nand count
    if(chipNum > 0) {
      HWC_IO_LOAD_SLAVE(chipNum, bInfo->regInfo, sipMonitor, val);
    } else {
      HWC_IO_LOAD(bInfo->regInfo, sipMonitor, val);
    }    
    val &= SST_SIPROCESS_OSC_CNTR;

    // some statistics here
    if (val < min) { min = val; }
    if (val > max) { max = val; }
	 
    valarray[val]++;   // Do you have to initialize the array first? I forget...
  }

  // Please change the formatting of any text to however you see fit
  //printf("\n\n--- Process Values (NOR chain) ---\n");
  //printf("\n sip value: occurences (probability)\n");
  total = 0;
  for (i = 0; i <= max; i++) {
    if (valarray[i] != 0) {
      //printf("  %4d: %4d (%f)\n", i, valarray[i], ((float)valarray[i])/iters);
      total += i * valarray[i];
    }
  }

  E = total / iters;
  total = 0;
  for (i = 0; i <= max; i++) {
    if (valarray[i] != 0) {
      total += (i - E)*(i - E) * valarray[i];
    }
  }

  VAR = total / iters;
  SD  = sqrt(VAR);    // how do you do sqrt??

  total = 0; N = 0;
  for (i = 0; i <= max; i++) {
    if ((valarray[i] != 0) && (i >= (E - SD)) && (i <= (E + SD))) {
      total += i * valarray[i];
      N += valarray[i];
    }
  }
  avg = total / N;

  //printf("E   = %g\n", E);
  //printf("VAR = %g\n", VAR);
  //printf("SD  = %g\n", SD);
  //printf("NOR avg = %d (using %d values about E)\n", (FxU32)avg, N);

  *norChain = (FxU32)avg;

  // Restore clock speed
  HWC_IO_STORE(bInfo->regInfo, pllCtrl1, pllCtrl1_save);

}