summaryrefslogtreecommitdiff
path: root/src/r128_accel.c
blob: ded73d5a22b3d63743f9b1d442d63bd02cef7036 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
/* $XFree86: xc/programs/Xserver/hw/xfree86/drivers/ati/r128_accel.c,v 1.17 2003/10/03 20:11:11 herrb Exp $ */
/*
 * Copyright 1999, 2000 ATI Technologies Inc., Markham, Ontario,
 *                      Precision Insight, Inc., Cedar Park, Texas, and
 *                      VA Linux Systems Inc., Fremont, California.
 *
 * All Rights Reserved.
 *
 * Permission is hereby granted, free of charge, to any person obtaining
 * a copy of this software and associated documentation files (the
 * "Software"), to deal in the Software without restriction, including
 * without limitation on the rights to use, copy, modify, merge,
 * publish, distribute, sublicense, and/or sell copies of the Software,
 * and to permit persons to whom the Software is furnished to do so,
 * subject to the following conditions:
 *
 * The above copyright notice and this permission notice (including the
 * next paragraph) shall be included in all copies or substantial
 * portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NON-INFRINGEMENT.  IN NO EVENT SHALL ATI, PRECISION INSIGHT, VA LINUX
 * SYSTEMS AND/OR THEIR SUPPLIERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
 * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
 * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 * OTHER DEALINGS IN THE SOFTWARE.
 */

/*
 * Authors:
 *   Rickard E. Faith <faith@valinux.com>
 *   Kevin E. Martin <martin@valinux.com>
 *   Alan Hourihane <alanh@fairlite.demon.co.uk>
 *
 * Credits:
 *
 *   Thanks to Alan Hourihane <alanh@fairlite.demon..co.uk> and SuSE for
 *   providing source code to their 3.3.x Rage 128 driver.  Portions of
 *   this file are based on the acceleration code for that driver.
 *
 * References:
 *
 *   RAGE 128 VR/ RAGE 128 GL Register Reference Manual (Technical
 *   Reference Manual P/N RRG-G04100-C Rev. 0.04), ATI Technologies: April
 *   1999.
 *
 *   RAGE 128 Software Development Manual (Technical Reference Manual P/N
 *   SDK-G04000 Rev. 0.01), ATI Technologies: June 1999.
 *
 * Notes on unimplemented XAA optimizations:
 *
 *   SetClipping:   The Rage128 doesn't support the full 16bit registers needed
 *                  for XAA clip rect support.
 *   SolidFillTrap: This will probably work if we can compute the correct
 *                  Bresenham error values.
 *   TwoPointLine:  The Rage 128 supports Bresenham lines instead.
 *   DashedLine with non-power-of-two pattern length: Apparently, there is
 *                  no way to set the length of the pattern -- it is always
 *                  assumed to be 8 or 32 (or 1024?).
 *   ScreenToScreenColorExpandFill: See p. 4-17 of the Technical Reference
 *                  Manual where it states that monochrome expansion of frame
 *                  buffer data is not supported.
 *   CPUToScreenColorExpandFill, direct: The implementation here uses a hybrid
 *                  direct/indirect method.  If we had more data registers,
 *                  then we could do better.  If XAA supported a trigger write
 *                  address, the code would be simpler.
 * (Alan Hourihane) Update. We now use purely indirect and clip the full
 *                  rectangle. Seems as the direct method has some problems
 *                  with this, although this indirect method is much faster
 *                  than the old method of setting up the engine per scanline.
 *                  This code was the basis of the Radeon work we did.
 *   Color8x8PatternFill: Apparently, an 8x8 color brush cannot take an 8x8
 *                  pattern from frame buffer memory.
 *   ImageWrites:   See CPUToScreenColorExpandFill.
 *
 */

#define R128_TRAPEZOIDS 0       /* Trapezoids don't work               */

				/* Driver data structures */
#include "r128.h"
#include "r128_reg.h"
#ifdef XF86DRI
#include "r128_sarea.h"
#define _XF86DRI_SERVER_
#include "r128_dri.h"
#include "r128_common.h"
#endif

				/* Line support */
#include "miline.h"

				/* X and server generic header files */
#include "xf86.h"

static struct {
    int rop;
    int pattern;
} R128_ROP[] = {
    { R128_ROP3_ZERO, R128_ROP3_ZERO }, /* GXclear        */
    { R128_ROP3_DSa,  R128_ROP3_DPa  }, /* Gxand          */
    { R128_ROP3_SDna, R128_ROP3_PDna }, /* GXandReverse   */
    { R128_ROP3_S,    R128_ROP3_P    }, /* GXcopy         */
    { R128_ROP3_DSna, R128_ROP3_DPna }, /* GXandInverted  */
    { R128_ROP3_D,    R128_ROP3_D    }, /* GXnoop         */
    { R128_ROP3_DSx,  R128_ROP3_DPx  }, /* GXxor          */
    { R128_ROP3_DSo,  R128_ROP3_DPo  }, /* GXor           */
    { R128_ROP3_DSon, R128_ROP3_DPon }, /* GXnor          */
    { R128_ROP3_DSxn, R128_ROP3_PDxn }, /* GXequiv        */
    { R128_ROP3_Dn,   R128_ROP3_Dn   }, /* GXinvert       */
    { R128_ROP3_SDno, R128_ROP3_PDno }, /* GXorReverse    */
    { R128_ROP3_Sn,   R128_ROP3_Pn   }, /* GXcopyInverted */
    { R128_ROP3_DSno, R128_ROP3_DPno }, /* GXorInverted   */
    { R128_ROP3_DSan, R128_ROP3_DPan }, /* GXnand         */
    { R128_ROP3_ONE,  R128_ROP3_ONE  }  /* GXset          */
};

/* Flush all dirty data in the Pixel Cache to memory. */
void R128EngineFlush(ScrnInfoPtr pScrn)
{
    R128InfoPtr   info      = R128PTR(pScrn);
    unsigned char *R128MMIO = info->MMIO;
    int           i;

    OUTREGP(R128_PC_NGUI_CTLSTAT, R128_PC_FLUSH_ALL, ~R128_PC_FLUSH_ALL);
    for (i = 0; i < R128_TIMEOUT; i++) {
	if (!(INREG(R128_PC_NGUI_CTLSTAT) & R128_PC_BUSY)) break;
    }
}

/* Reset graphics card to known state. */
void R128EngineReset(ScrnInfoPtr pScrn)
{
    R128InfoPtr   info      = R128PTR(pScrn);
    unsigned char *R128MMIO = info->MMIO;
    CARD32        clock_cntl_index;
    CARD32        mclk_cntl;
    CARD32        gen_reset_cntl;

    R128EngineFlush(pScrn);

    clock_cntl_index = INREG(R128_CLOCK_CNTL_INDEX);
    mclk_cntl        = INPLL(pScrn, R128_MCLK_CNTL);

    OUTPLL(R128_MCLK_CNTL, mclk_cntl | R128_FORCE_GCP | R128_FORCE_PIPE3D_CP);

    gen_reset_cntl   = INREG(R128_GEN_RESET_CNTL);

    OUTREG(R128_GEN_RESET_CNTL, gen_reset_cntl | R128_SOFT_RESET_GUI);
    INREG(R128_GEN_RESET_CNTL);
    OUTREG(R128_GEN_RESET_CNTL,
	gen_reset_cntl & (CARD32)(~R128_SOFT_RESET_GUI));
    INREG(R128_GEN_RESET_CNTL);

    OUTPLL(R128_MCLK_CNTL,        mclk_cntl);
    OUTREG(R128_CLOCK_CNTL_INDEX, clock_cntl_index);
    OUTREG(R128_GEN_RESET_CNTL,   gen_reset_cntl);
}

/* The FIFO has 64 slots.  This routines waits until at least `entries' of
   these slots are empty. */
void R128WaitForFifoFunction(ScrnInfoPtr pScrn, int entries)
{
    R128InfoPtr   info      = R128PTR(pScrn);
    unsigned char *R128MMIO = info->MMIO;
    int           i;

    for (;;) {
	for (i = 0; i < R128_TIMEOUT; i++) {
	    info->fifo_slots = INREG(R128_GUI_STAT) & R128_GUI_FIFOCNT_MASK;
	    if (info->fifo_slots >= entries) return;
	}
	R128TRACE(("FIFO timed out: %d entries, stat=0x%08x, probe=0x%08x\n",
		   INREG(R128_GUI_STAT) & R128_GUI_FIFOCNT_MASK,
		   INREG(R128_GUI_STAT),
		   INREG(R128_GUI_PROBE)));
	xf86DrvMsg(pScrn->scrnIndex, X_ERROR,
		   "FIFO timed out, resetting engine...\n");
	R128EngineReset(pScrn);
#ifdef XF86DRI
	R128CCE_RESET(pScrn, info);
	if (info->directRenderingEnabled) {
	    R128CCE_START(pScrn, info);
	}
#endif
    }
}

/* Wait for the graphics engine to be completely idle: the FIFO has
   drained, the Pixel Cache is flushed, and the engine is idle.  This is a
   standard "sync" function that will make the hardware "quiescent". */
void R128WaitForIdle(ScrnInfoPtr pScrn)
{
    R128InfoPtr   info      = R128PTR(pScrn);
    unsigned char *R128MMIO = info->MMIO;
    int           i;

    R128WaitForFifoFunction(pScrn, 64);

    for (;;) {
	for (i = 0; i < R128_TIMEOUT; i++) {
	    if (!(INREG(R128_GUI_STAT) & R128_GUI_ACTIVE)) {
		R128EngineFlush(pScrn);
		return;
	    }
	}
	R128TRACE(("Idle timed out: %d entries, stat=0x%08x, probe=0x%08x\n",
		   INREG(R128_GUI_STAT) & R128_GUI_FIFOCNT_MASK,
		   INREG(R128_GUI_STAT),
		   INREG(R128_GUI_PROBE)));
	xf86DrvMsg(pScrn->scrnIndex, X_ERROR,
		   "Idle timed out, resetting engine...\n");
	R128EngineReset(pScrn);
#ifdef XF86DRI
	R128CCE_RESET(pScrn, info);
	if (info->directRenderingEnabled) {
	    R128CCE_START(pScrn, info);
	}
#endif
    }
}

#ifdef XF86DRI
/* Wait until the CCE is completely idle: the FIFO has drained and the
 * CCE is idle.
 */
void R128CCEWaitForIdle(ScrnInfoPtr pScrn)
{
    R128InfoPtr info = R128PTR(pScrn);
    int         ret, i;

    FLUSH_RING();

    for (;;) {
        i = 0;
        do {
            ret = drmCommandNone(info->drmFD, DRM_R128_CCE_IDLE);
        } while ( ret && errno == EBUSY && i++ < (R128_IDLE_RETRY * R128_IDLE_RETRY) );

	if (ret && ret != -EBUSY) {
	    xf86DrvMsg(pScrn->scrnIndex, X_ERROR,
		       "%s: CCE idle %d\n", __FUNCTION__, ret);
	}

	if (i > R128_IDLE_RETRY) {
	    xf86DrvMsg(pScrn->scrnIndex, X_ERROR,
		       "%s: (DEBUG) CCE idle took i = %d\n", __FUNCTION__, i);
	}

	if (ret == 0) return;

	xf86DrvMsg(pScrn->scrnIndex, X_ERROR,
		   "Idle timed out, resetting engine...\n");
	R128CCE_STOP(pScrn, info);
	R128EngineReset(pScrn);

	/* Always restart the engine when doing CCE 2D acceleration */
	R128CCE_RESET(pScrn, info);
	R128CCE_START(pScrn, info);
    }
}

int R128CCEStop(ScrnInfoPtr pScrn)
{
    R128InfoPtr    info = R128PTR(pScrn);
    drmR128CCEStop stop;
    int            ret, i;

    stop.flush = 1;
    stop.idle  = 1;

    ret = drmCommandWrite( info->drmFD, DRM_R128_CCE_STOP,
                           &stop, sizeof(drmR128CCEStop) );

    if ( ret == 0 ) {
        return 0;
    } else if ( errno != EBUSY ) {
        return -errno;
    }

    stop.flush = 0;

    i = 0;
    do {
        ret = drmCommandWrite( info->drmFD, DRM_R128_CCE_STOP,
                               &stop, sizeof(drmR128CCEStop) );
    } while ( ret && errno == EBUSY && i++ < R128_IDLE_RETRY );

    if ( ret == 0 ) {
        return 0;
    } else if ( errno != EBUSY ) {
        return -errno;
    }

    stop.idle = 0;

    if ( drmCommandWrite( info->drmFD, DRM_R128_CCE_STOP,
                          &stop, sizeof(drmR128CCEStop) )) {
        return -errno;
    } else {
        return 0;
    }
}

#endif

/* Setup for XAA SolidFill. */
static void R128SetupForSolidFill(ScrnInfoPtr pScrn,
				  int color, int rop, unsigned int planemask)
{
    R128InfoPtr   info      = R128PTR(pScrn);
    unsigned char *R128MMIO = info->MMIO;

    R128WaitForFifo(pScrn, 4);
    OUTREG(R128_DP_GUI_MASTER_CNTL, (info->dp_gui_master_cntl
				     | R128_GMC_BRUSH_SOLID_COLOR
				     | R128_GMC_SRC_DATATYPE_COLOR
				     | R128_ROP[rop].pattern));
    OUTREG(R128_DP_BRUSH_FRGD_CLR,  color);
    OUTREG(R128_DP_WRITE_MASK,      planemask);
    OUTREG(R128_DP_CNTL,            (R128_DST_X_LEFT_TO_RIGHT
				     | R128_DST_Y_TOP_TO_BOTTOM));
}

/* Subsequent XAA SolidFillRect.

   Tests: xtest CH06/fllrctngl, xterm
*/
static void  R128SubsequentSolidFillRect(ScrnInfoPtr pScrn,
					 int x, int y, int w, int h)
{
    R128InfoPtr   info      = R128PTR(pScrn);
    unsigned char *R128MMIO = info->MMIO;

    R128WaitForFifo(pScrn, 2);
    OUTREG(R128_DST_Y_X,          (y << 16) | x);
    OUTREG(R128_DST_WIDTH_HEIGHT, (w << 16) | h);
}

/* Setup for XAA solid lines. */
static void R128SetupForSolidLine(ScrnInfoPtr pScrn,
				  int color, int rop, unsigned int planemask)
{
    R128InfoPtr   info      = R128PTR(pScrn);
    unsigned char *R128MMIO = info->MMIO;

    R128WaitForFifo(pScrn, 3);
    OUTREG(R128_DP_GUI_MASTER_CNTL, (info->dp_gui_master_cntl
				     | R128_GMC_BRUSH_SOLID_COLOR
				     | R128_GMC_SRC_DATATYPE_COLOR
				     | R128_ROP[rop].pattern));
    OUTREG(R128_DP_BRUSH_FRGD_CLR,  color);
    OUTREG(R128_DP_WRITE_MASK,      planemask);
}


/* Subsequent XAA solid Bresenham line.

   Tests: xtest CH06/drwln, ico, Mark Vojkovich's linetest program

   [See http://www.xfree86.org/devel/archives/devel/1999-Jun/0102.shtml for
   Mark Vojkovich's linetest program, posted 2Jun99 to devel@xfree86.org.]

   x11perf -line500
                               1024x768@76Hz   1024x768@76Hz
                                        8bpp           32bpp
   not used:                     39700.0/sec     34100.0/sec
   used:                         47600.0/sec     36800.0/sec
*/
static void R128SubsequentSolidBresenhamLine(ScrnInfoPtr pScrn,
					     int x, int y,
					     int major, int minor,
					     int err, int len, int octant)
{
    R128InfoPtr   info      = R128PTR(pScrn);
    unsigned char *R128MMIO = info->MMIO;
    int           flags     = 0;

    if (octant & YMAJOR)         flags |= R128_DST_Y_MAJOR;
    if (!(octant & XDECREASING)) flags |= R128_DST_X_DIR_LEFT_TO_RIGHT;
    if (!(octant & YDECREASING)) flags |= R128_DST_Y_DIR_TOP_TO_BOTTOM;

    R128WaitForFifo(pScrn, 6);
    OUTREG(R128_DP_CNTL_XDIR_YDIR_YMAJOR, flags);
    OUTREG(R128_DST_Y_X,                  (y << 16) | x);
    OUTREG(R128_DST_BRES_ERR,             err);
    OUTREG(R128_DST_BRES_INC,             minor);
    OUTREG(R128_DST_BRES_DEC,             -major);
    OUTREG(R128_DST_BRES_LNTH,            len);
}

/* Subsequent XAA solid horizontal and vertical lines

   1024x768@76Hz 8bpp
                             Without             With
   x11perf -hseg500      87600.0/sec     798000.0/sec
   x11perf -vseg500      38100.0/sec      38000.0/sec
*/
static void R128SubsequentSolidHorVertLine(ScrnInfoPtr pScrn,
					   int x, int y, int len, int dir )
{
    R128InfoPtr   info      = R128PTR(pScrn);
    unsigned char *R128MMIO = info->MMIO;

    R128WaitForFifo(pScrn, 1);
    OUTREG(R128_DP_CNTL, (R128_DST_X_LEFT_TO_RIGHT
			  | R128_DST_Y_TOP_TO_BOTTOM));

    if (dir == DEGREES_0) {
	R128SubsequentSolidFillRect(pScrn, x, y, len, 1);
    } else {
	R128SubsequentSolidFillRect(pScrn, x, y, 1, len);
    }
}

/* Setup for XAA dashed lines.

   Tests: xtest CH05/stdshs, XFree86/drwln

   NOTE: Since we can only accelerate lines with power-of-2 patterns of
   length <= 32, these x11perf numbers are not representative of the
   speed-up on appropriately-sized patterns.

   1024x768@76Hz 8bpp
                             Without             With
   x11perf -dseg100     218000.0/sec     222000.0/sec
   x11perf -dline100    215000.0/sec     221000.0/sec
   x11perf -ddline100   178000.0/sec     180000.0/sec
*/
static void R128SetupForDashedLine(ScrnInfoPtr pScrn,
				   int fg, int bg,
				   int rop, unsigned int planemask,
				   int length, unsigned char *pattern)
{
    R128InfoPtr   info      = R128PTR(pScrn);
    unsigned char *R128MMIO = info->MMIO;
    CARD32        pat       = *(CARD32 *)(pointer)pattern;

#if X_BYTE_ORDER == X_LITTLE_ENDIAN
# define PAT_SHIFT(pat,n) pat << n
#else
# define PAT_SHIFT(pat,n) pat >> n
#endif

    switch (length) {
    case  2: pat |= PAT_SHIFT(pat,2); /* fall through */
    case  4: pat |= PAT_SHIFT(pat,4); /* fall through */
    case  8: pat |= PAT_SHIFT(pat,8); /* fall through */
    case 16: pat |= PAT_SHIFT(pat,16);
    }

    R128WaitForFifo(pScrn, 5);
    OUTREG(R128_DP_GUI_MASTER_CNTL, (info->dp_gui_master_cntl
				     | (bg == -1
					? R128_GMC_BRUSH_32x1_MONO_FG_LA
					: R128_GMC_BRUSH_32x1_MONO_FG_BG)
				     | R128_ROP[rop].pattern
				     | R128_GMC_BYTE_LSB_TO_MSB));
    OUTREG(R128_DP_WRITE_MASK,      planemask);
    OUTREG(R128_DP_BRUSH_FRGD_CLR,  fg);
    OUTREG(R128_DP_BRUSH_BKGD_CLR,  bg);
    OUTREG(R128_BRUSH_DATA0,        pat);
}

/* Subsequent XAA dashed line. */
static void R128SubsequentDashedBresenhamLine(ScrnInfoPtr pScrn,
					      int x, int y,
					      int major, int minor,
					      int err, int len, int octant,
					      int phase)
{
    R128InfoPtr   info      = R128PTR(pScrn);
    unsigned char *R128MMIO = info->MMIO;
    int           flags     = 0;

    if (octant & YMAJOR)         flags |= R128_DST_Y_MAJOR;
    if (!(octant & XDECREASING)) flags |= R128_DST_X_DIR_LEFT_TO_RIGHT;
    if (!(octant & YDECREASING)) flags |= R128_DST_Y_DIR_TOP_TO_BOTTOM;

    R128WaitForFifo(pScrn, 7);
    OUTREG(R128_DP_CNTL_XDIR_YDIR_YMAJOR, flags);
    OUTREG(R128_DST_Y_X,                  (y << 16) | x);
    OUTREG(R128_BRUSH_Y_X,                (phase << 16) | phase);
    OUTREG(R128_DST_BRES_ERR,             err);
    OUTREG(R128_DST_BRES_INC,             minor);
    OUTREG(R128_DST_BRES_DEC,             -major);
    OUTREG(R128_DST_BRES_LNTH,            len);
}

#if R128_TRAPEZOIDS
				/* This doesn't work.  Except in the
				   lower-left quadrant, all of the pixel
				   errors appear to be because eL and eR
				   are not correct.  Drawing from right to
				   left doesn't help.  Be aware that the
				   non-_SUB registers set the sub-pixel
				   values to 0.5 (0x08), which isn't what
				   XAA wants. */
/* Subsequent XAA SolidFillTrap.  XAA always passes data that assumes we
   fill from top to bottom, so dyL and dyR are always non-negative. */
static void R128SubsequentSolidFillTrap(ScrnInfoPtr pScrn, int y, int h,
					int left, int dxL, int dyL, int eL,
					int right, int dxR, int dyR, int eR)
{
    R128InfoPtr   info      = R128PTR(pScrn);
    unsigned char *R128MMIO = info->MMIO;
    int           flags     = 0;
    int           Lymajor   = 0;
    int           Rymajor   = 0;
    int           origdxL   = dxL;
    int           origdxR   = dxR;

    R128TRACE(("Trap %d %d; L %d %d %d %d; R %d %d %d %d\n",
	       y, h,
	       left, dxL, dyL, eL,
	       right, dxR, dyR, eR));

    if (dxL < 0)    dxL = -dxL; else flags |= (1 << 0) /* | (1 << 8) */;
    if (dxR < 0)    dxR = -dxR; else flags |= (1 << 6);

    R128WaitForFifo(pScrn, 11);

#if 1
    OUTREG(R128_DP_CNTL,            flags | (1 << 1) | (1 << 7));
    OUTREG(R128_DST_Y_SUB,          ((y) << 4) | 0x0 );
    OUTREG(R128_DST_X_SUB,          ((left) << 4)|0x0);
    OUTREG(R128_TRAIL_BRES_ERR,     eR-dxR);
    OUTREG(R128_TRAIL_BRES_INC,     dxR);
    OUTREG(R128_TRAIL_BRES_DEC,     -dyR);
    OUTREG(R128_TRAIL_X_SUB,        ((right) << 4) | 0x0);
    OUTREG(R128_LEAD_BRES_ERR,      eL-dxL);
    OUTREG(R128_LEAD_BRES_INC,      dxL);
    OUTREG(R128_LEAD_BRES_DEC,      -dyL);
    OUTREG(R128_LEAD_BRES_LNTH_SUB, ((h) << 4) | 0x00);
#else
    OUTREG(R128_DP_CNTL,            flags | (1 << 1) );
    OUTREG(R128_DST_Y_SUB,          (y << 4));
    OUTREG(R128_DST_X_SUB,          (right << 4));
    OUTREG(R128_TRAIL_BRES_ERR,     eL);
    OUTREG(R128_TRAIL_BRES_INC,     dxL);
    OUTREG(R128_TRAIL_BRES_DEC,     -dyL);
    OUTREG(R128_TRAIL_X_SUB,        (left << 4) | 0);
    OUTREG(R128_LEAD_BRES_ERR,      eR);
    OUTREG(R128_LEAD_BRES_INC,      dxR);
    OUTREG(R128_LEAD_BRES_DEC,      -dyR);
    OUTREG(R128_LEAD_BRES_LNTH_SUB, h << 4);
#endif
}
#endif

/* Setup for XAA screen-to-screen copy.

   Tests: xtest CH06/fllrctngl (also tests transparency).
*/
static void R128SetupForScreenToScreenCopy(ScrnInfoPtr pScrn,
					   int xdir, int ydir, int rop,
					   unsigned int planemask,
					   int trans_color)
{
    R128InfoPtr   info      = R128PTR(pScrn);
    unsigned char *R128MMIO = info->MMIO;

    info->xdir = xdir;
    info->ydir = ydir;
    R128WaitForFifo(pScrn, 3);
    OUTREG(R128_DP_GUI_MASTER_CNTL, (info->dp_gui_master_cntl
				     | R128_GMC_BRUSH_SOLID_COLOR
				     | R128_GMC_SRC_DATATYPE_COLOR
				     | R128_ROP[rop].rop
				     | R128_DP_SRC_SOURCE_MEMORY));
    OUTREG(R128_DP_WRITE_MASK,      planemask);
    OUTREG(R128_DP_CNTL,            ((xdir >= 0 ? R128_DST_X_LEFT_TO_RIGHT : 0)
				     | (ydir >= 0
					? R128_DST_Y_TOP_TO_BOTTOM
					: 0)));

    if ((trans_color != -1) || (info->XAAForceTransBlit == TRUE)) {
				/* Set up for transparency */
	R128WaitForFifo(pScrn, 3);
	OUTREG(R128_CLR_CMP_CLR_SRC, trans_color);
	OUTREG(R128_CLR_CMP_MASK,    R128_CLR_CMP_MSK);
	OUTREG(R128_CLR_CMP_CNTL,    (R128_SRC_CMP_NEQ_COLOR
				      | R128_CLR_CMP_SRC_SOURCE));
    }
}

/* Subsequent XAA screen-to-screen copy. */
static void R128SubsequentScreenToScreenCopy(ScrnInfoPtr pScrn,
					     int xa, int ya,
					     int xb, int yb,
					     int w, int h)
{
    R128InfoPtr   info      = R128PTR(pScrn);
    unsigned char *R128MMIO = info->MMIO;

    if (info->xdir < 0) xa += w - 1, xb += w - 1;
    if (info->ydir < 0) ya += h - 1, yb += h - 1;

    R128WaitForFifo(pScrn, 3);
    OUTREG(R128_SRC_Y_X,          (ya << 16) | xa);
    OUTREG(R128_DST_Y_X,          (yb << 16) | xb);
    OUTREG(R128_DST_HEIGHT_WIDTH, (h << 16) | w);
}

/* Setup for XAA mono 8x8 pattern color expansion.  Patterns with
   transparency use `bg == -1'.  This routine is only used if the XAA
   pixmap cache is turned on.

   Tests: xtest XFree86/fllrctngl (no other test will test this routine with
                                   both transparency and non-transparency)

   1024x768@76Hz 8bpp
                             Without             With
   x11perf -srect100     38600.0/sec      85700.0/sec
   x11perf -osrect100    38600.0/sec      85700.0/sec
*/
static void R128SetupForMono8x8PatternFill(ScrnInfoPtr pScrn,
					   int patternx, int patterny,
					   int fg, int bg, int rop,
					   unsigned int planemask)
{
    R128InfoPtr   info      = R128PTR(pScrn);
    unsigned char *R128MMIO = info->MMIO;

    R128WaitForFifo(pScrn, 6);
    OUTREG(R128_DP_GUI_MASTER_CNTL, (info->dp_gui_master_cntl
				     | (bg == -1
					? R128_GMC_BRUSH_8X8_MONO_FG_LA
					: R128_GMC_BRUSH_8X8_MONO_FG_BG)
				     | R128_ROP[rop].pattern
				     | R128_GMC_BYTE_LSB_TO_MSB));
    OUTREG(R128_DP_WRITE_MASK,      planemask);
    OUTREG(R128_DP_BRUSH_FRGD_CLR,  fg);
    OUTREG(R128_DP_BRUSH_BKGD_CLR,  bg);
    OUTREG(R128_BRUSH_DATA0,        patternx);
    OUTREG(R128_BRUSH_DATA1,        patterny);
}

/* Subsequent XAA 8x8 pattern color expansion.  Because they are used in
   the setup function, `patternx' and `patterny' are not used here. */
static void R128SubsequentMono8x8PatternFillRect(ScrnInfoPtr pScrn,
						 int patternx, int patterny,
						 int x, int y, int w, int h)
{
    R128InfoPtr   info      = R128PTR(pScrn);
    unsigned char *R128MMIO = info->MMIO;

    R128WaitForFifo(pScrn, 3);
    OUTREG(R128_BRUSH_Y_X,        (patterny << 8) | patternx);
    OUTREG(R128_DST_Y_X,          (y << 16) | x);
    OUTREG(R128_DST_HEIGHT_WIDTH, (h << 16) | w);
}

#if 0
/* Setup for XAA color 8x8 pattern fill.

   Tests: xtest XFree86/fllrctngl (with Mono8x8PatternFill off)
*/
static void R128SetupForColor8x8PatternFill(ScrnInfoPtr pScrn,
					    int patx, int paty,
					    int rop, unsigned int planemask,
					    int trans_color)
{
    R128InfoPtr   info      = R128PTR(pScrn);
    unsigned char *R128MMIO = info->MMIO;

    R128TRACE(("Color8x8 %d %d %d\n", trans_color, patx, paty));

    R128WaitForFifo(pScrn, 2);
    OUTREG(R128_DP_GUI_MASTER_CNTL, (info->dp_gui_master_cntl
				     | R128_GMC_BRUSH_8x8_COLOR
				     | R128_GMC_SRC_DATATYPE_COLOR
				     | R128_ROP[rop].rop
				     | R128_DP_SRC_SOURCE_MEMORY));
    OUTREG(R128_DP_WRITE_MASK,      planemask);

    if (trans_color != -1) {
				/* Set up for transparency */
	R128WaitForFifo(pScrn, 3);
	OUTREG(R128_CLR_CMP_CLR_SRC, trans_color);
	OUTREG(R128_CLR_CMP_MASK,    R128_CLR_CMP_MSK);
	OUTREG(R128_CLR_CMP_CNTL,    (R128_SRC_CMP_NEQ_COLOR
				      | R128_CLR_CMP_SRC_SOURCE));
    }
}

/* Subsequent XAA 8x8 pattern color expansion. */
static void R128SubsequentColor8x8PatternFillRect( ScrnInfoPtr pScrn,
						   int patx, int paty,
						   int x, int y, int w, int h)
{
    R128InfoPtr   info      = R128PTR(pScrn);
    unsigned char *R128MMIO = info->MMIO;

    R128TRACE(("Color8x8 %d,%d %d,%d %d %d\n", patx, paty, x, y, w, h));
    R128WaitForFifo(pScrn, 3);
    OUTREG(R128_SRC_Y_X, (paty << 16) | patx);
    OUTREG(R128_DST_Y_X, (y << 16) | x);
    OUTREG(R128_DST_HEIGHT_WIDTH, (h << 16) | w);
}
#endif

/* Setup for XAA indirect CPU-to-screen color expansion (indirect).
   Because of how the scratch buffer is initialized, this is really a
   mainstore-to-screen color expansion.  Transparency is supported when `bg
   == -1'.

   x11perf -ftext (pure indirect):
                               1024x768@76Hz   1024x768@76Hz
                                        8bpp           32bpp
   not used:                    685000.0/sec    794000.0/sec
   used:                       1070000.0/sec   1080000.0/sec

   We could improve this indirect routine by about 10% if the hardware
   could accept DWORD padded scanlines, or if XAA could provide bit-packed
   data.  We might also be able to move to a direct routine if there were
   more HOST_DATA registers.

   Implementing the hybrid indirect/direct scheme improved performance in a
   few areas:

   1024x768@76 8bpp
                                   Indirect          Hybrid
   x11perf -oddsrect10          50100.0/sec     71700.0/sec
   x11perf -oddsrect100          4240.0/sec      6660.0/sec
   x11perf -bigsrect10          50300.0/sec     71100.0/sec
   x11perf -bigsrect100          4190.0/sec      6800.0/sec
   x11perf -polytext           584000.0/sec    714000.0/sec
   x11perf -polytext16         154000.0/sec    172000.0/sec
   x11perf -seg1              1780000.0/sec   1880000.0/sec
   x11perf -copyplane10         42900.0/sec     58300.0/sec
   x11perf -copyplane100         4400.0/sec      6710.0/sec
   x11perf -putimagexy10         5090.0/sec      6670.0/sec
   x11perf -putimagexy100         424.0/sec       575.0/sec

   1024x768@76 -depth 24 -fbbpp 32
                                   Indirect          Hybrid
   x11perf -oddsrect100          4240.0/sec      6670.0/sec
   x11perf -bigsrect100          4190.0/sec      6800.0/sec
   x11perf -polytext           585000.0/sec    719000.0/sec
   x11perf -seg1              2960000.0/sec   2990000.0/sec
   x11perf -copyplane100         4400.0/sec      6700.0/sec
   x11perf -putimagexy100         138.0/sec       191.0/sec

*/
static void R128SetupForScanlineCPUToScreenColorExpandFill(ScrnInfoPtr pScrn,
							   int fg, int bg,
							   int rop,
							   unsigned int
							   planemask)
{
    R128InfoPtr   info      = R128PTR(pScrn);
    unsigned char *R128MMIO = info->MMIO;

    R128WaitForFifo(pScrn, 4);
#if X_BYTE_ORDER == X_LITTLE_ENDIAN
    OUTREG(R128_DP_GUI_MASTER_CNTL, (info->dp_gui_master_cntl
				     | R128_GMC_DST_CLIPPING
				     | R128_GMC_BRUSH_NONE
				     | (bg == -1
					? R128_GMC_SRC_DATATYPE_MONO_FG_LA
					: R128_GMC_SRC_DATATYPE_MONO_FG_BG)
				     | R128_ROP[rop].rop
				     | R128_GMC_BYTE_LSB_TO_MSB
				     | R128_DP_SRC_SOURCE_HOST_DATA));
#else	/* X_BYTE_ORDER == X_BIG_ENDIAN */
    OUTREG(R128_DP_GUI_MASTER_CNTL, (info->dp_gui_master_cntl
				     | R128_GMC_DST_CLIPPING
				     | R128_GMC_BRUSH_NONE
				     | (bg == -1
					? R128_GMC_SRC_DATATYPE_MONO_FG_LA
					: R128_GMC_SRC_DATATYPE_MONO_FG_BG)
				     | R128_ROP[rop].rop
				     | R128_DP_SRC_SOURCE_HOST_DATA));
#endif
    OUTREG(R128_DP_WRITE_MASK,      planemask);
    OUTREG(R128_DP_SRC_FRGD_CLR,    fg);
    OUTREG(R128_DP_SRC_BKGD_CLR,    bg);
}

/* Subsequent XAA indirect CPU-to-screen color expansion.  This is only
   called once for each rectangle. */
static void R128SubsequentScanlineCPUToScreenColorExpandFill(ScrnInfoPtr pScrn,
							     int x, int y,
							     int w, int h,
							     int skipleft)
{
    R128InfoPtr   info      = R128PTR(pScrn);
    unsigned char *R128MMIO = info->MMIO;
    int x1clip = x+skipleft;
    int x2clip = x+w;

    info->scanline_h      = h;
    info->scanline_words  = (w + 31) >> 5;

#if 0
    /* Seems as though the Rage128's doesn't like blitting directly
     * as we must be overwriting something too quickly, therefore we
     * render to the buffer first and then blit */
    if ((info->scanline_words * h) <= 9) {
	/* Turn on direct for less than 9 dword colour expansion */
	info->scratch_buffer[0]
	    = (unsigned char *)(ADDRREG(R128_HOST_DATA_LAST)
				- (info->scanline_words - 1));
	info->scanline_direct = 1;
    } else
#endif
    {
	/* Use indirect for anything else */
	info->scratch_buffer[0] = info->scratch_save;
	info->scanline_direct   = 0;
    }

    if (pScrn->bitsPerPixel == 24) {
	x1clip *= 3;
	x2clip *= 3;
    }

    R128WaitForFifo(pScrn, 4 + (info->scanline_direct ?
					(info->scanline_words * h) : 0) );
    OUTREG(R128_SC_TOP_LEFT,     (y << 16)       | (x1clip & 0xffff));
    OUTREG(R128_SC_BOTTOM_RIGHT, ((y+h-1) << 16) | ((x2clip-1) & 0xffff));
    OUTREG(R128_DST_Y_X,         (y << 16)       | (x & 0xffff));
    /* Have to pad the width here and use clipping engine */
    OUTREG(R128_DST_HEIGHT_WIDTH, (h << 16)      | ((w + 31) & ~31));
}

/* Subsequent XAA indirect CPU-to-screen color expansion.  This is called
   once for each scanline. */
static void R128SubsequentColorExpandScanline(ScrnInfoPtr pScrn, int bufno)
{
    R128InfoPtr     info      = R128PTR(pScrn);
    unsigned char   *R128MMIO = info->MMIO;
    CARD32          *p        = (pointer)info->scratch_buffer[bufno];
    int             i;
    int             left      = info->scanline_words;
    volatile CARD32 *d;

    if (info->scanline_direct) return;
    --info->scanline_h;
    while (left) {
        write_mem_barrier();
	if (left <= 8) {
	  /* Last scanline - finish write to DATA_LAST */
	  if (info->scanline_h == 0) {
	    R128WaitForFifo(pScrn, left);
				/* Unrolling doesn't improve performance */
	    for (d = ADDRREG(R128_HOST_DATA_LAST) - (left - 1); left; --left)
		*d++ = *p++;
	    return;
	  } else {
	    R128WaitForFifo(pScrn, left);
				/* Unrolling doesn't improve performance */
	    for (d = ADDRREG(R128_HOST_DATA7) - (left - 1); left; --left)
		*d++ = *p++;
	  }
	} else {
	    R128WaitForFifo(pScrn, 8);
				/* Unrolling doesn't improve performance */
	    for (d = ADDRREG(R128_HOST_DATA0), i = 0; i < 8; i++)
		*d++ = *p++;
	    left -= 8;
	}
    }
}

/* Setup for XAA indirect image write.

   1024x768@76Hz 8bpp
                             Without             With
   x11perf -putimage10   37500.0/sec      39300.0/sec
   x11perf -putimage100   2150.0/sec       1170.0/sec
   x11perf -putimage500    108.0/sec         49.8/sec
 */
static void R128SetupForScanlineImageWrite(ScrnInfoPtr pScrn,
					   int rop,
					   unsigned int planemask,
					   int trans_color,
					   int bpp,
					   int depth)
{
    R128InfoPtr   info      = R128PTR(pScrn);
    unsigned char *R128MMIO = info->MMIO;

    info->scanline_bpp = bpp;

    R128WaitForFifo(pScrn, 2);
    OUTREG(R128_DP_GUI_MASTER_CNTL, (info->dp_gui_master_cntl
				     | R128_GMC_DST_CLIPPING
				     | R128_GMC_BRUSH_1X8_COLOR
				     | R128_GMC_SRC_DATATYPE_COLOR
				     | R128_ROP[rop].rop
				     | R128_GMC_BYTE_LSB_TO_MSB
				     | R128_DP_SRC_SOURCE_HOST_DATA));
    OUTREG(R128_DP_WRITE_MASK,      planemask);

    if (trans_color != -1) {
				/* Set up for transparency */
	R128WaitForFifo(pScrn, 3);
	OUTREG(R128_CLR_CMP_CLR_SRC, trans_color);
	OUTREG(R128_CLR_CMP_MASK,    R128_CLR_CMP_MSK);
	OUTREG(R128_CLR_CMP_CNTL,    (R128_SRC_CMP_NEQ_COLOR
				      | R128_CLR_CMP_SRC_SOURCE));
    }
}

/* Subsequent XAA indirect image write. This is only called once for each
   rectangle. */
static void R128SubsequentScanlineImageWriteRect(ScrnInfoPtr pScrn,
						 int x, int y,
						 int w, int h,
						 int skipleft)
{
    R128InfoPtr   info      = R128PTR(pScrn);
    unsigned char *R128MMIO = info->MMIO;
    int x1clip = x+skipleft;
    int x2clip = x+w;

    int shift = 0; /* 32bpp */

    if (pScrn->bitsPerPixel == 8) shift = 3;
    else if (pScrn->bitsPerPixel == 16) shift = 1;

    info->scanline_h      = h;
    info->scanline_words  = (w * info->scanline_bpp + 31) >> 5;

#if 0
    /* Seeing as the CPUToScreen doesn't like this, I've done this
     * here too, as it uses pretty much the same path. */
    if ((info->scanline_words * h) <= 9) {
	/* Turn on direct for less than 9 dword colour expansion */
	info->scratch_buffer[0]
	    = (unsigned char *)(ADDRREG(R128_HOST_DATA_LAST)
				- (info->scanline_words - 1));
	info->scanline_direct = 1;
    } else
#endif
    {
	/* Use indirect for anything else */
	info->scratch_buffer[0] = info->scratch_save;
	info->scanline_direct   = 0;
    }

    if (pScrn->bitsPerPixel == 24) {
	x1clip *= 3;
	x2clip *= 3;
    }

    R128WaitForFifo(pScrn, 4 + (info->scanline_direct ?
					(info->scanline_words * h) : 0) );
    OUTREG(R128_SC_TOP_LEFT,      (y << 16)       | (x1clip & 0xffff));
    OUTREG(R128_SC_BOTTOM_RIGHT,  ((y+h-1) << 16) | ((x2clip-1) & 0xffff));
    OUTREG(R128_DST_Y_X,          (y << 16)       | (x & 0xffff));
    /* Have to pad the width here and use clipping engine */
    OUTREG(R128_DST_HEIGHT_WIDTH, (h << 16)       | ((w + shift) & ~shift));
}

/* Subsequent XAA indirect iamge write.  This is called once for each
   scanline. */
static void R128SubsequentImageWriteScanline(ScrnInfoPtr pScrn, int bufno)
{
    R128InfoPtr     info      = R128PTR(pScrn);
    unsigned char   *R128MMIO = info->MMIO;
    CARD32          *p        = (pointer)info->scratch_buffer[bufno];
    int             i;
    int             left      = info->scanline_words;
    volatile CARD32 *d;

    if (info->scanline_direct) return;
    --info->scanline_h;
    while (left) {
        write_mem_barrier();
	if (left <= 8) {
	  /* Last scanline - finish write to DATA_LAST */
	  if (info->scanline_h == 0) {
	    R128WaitForFifo(pScrn, left);
				/* Unrolling doesn't improve performance */
	    for (d = ADDRREG(R128_HOST_DATA_LAST) - (left - 1); left; --left)
		*d++ = *p++;
	    return;
	  } else {
	    R128WaitForFifo(pScrn, left);
				/* Unrolling doesn't improve performance */
	    for (d = ADDRREG(R128_HOST_DATA7) - (left - 1); left; --left)
		*d++ = *p++;
	  }
	} else {
	    R128WaitForFifo(pScrn, 8);
				/* Unrolling doesn't improve performance */
	    for (d = ADDRREG(R128_HOST_DATA0), i = 0; i < 8; i++)
		*d++ = *p++;
	    left -= 8;
	}
    }
}

/* Initialize the acceleration hardware. */
void R128EngineInit(ScrnInfoPtr pScrn)
{
    R128InfoPtr   info      = R128PTR(pScrn);
    unsigned char *R128MMIO = info->MMIO;

    R128TRACE(("EngineInit (%d/%d)\n", info->CurrentLayout.pixel_code, info->CurrentLayout.bitsPerPixel));

    OUTREG(R128_SCALE_3D_CNTL, 0);
    R128EngineReset(pScrn);

    switch (info->CurrentLayout.pixel_code) {
    case 8:  info->datatype = 2; break;
    case 15: info->datatype = 3; break;
    case 16: info->datatype = 4; break;
    case 24: info->datatype = 5; break;
    case 32: info->datatype = 6; break;
    default:
	R128TRACE(("Unknown depth/bpp = %d/%d (code = %d)\n",
		   info->CurrentLayout.depth, info->CurrentLayout.bitsPerPixel,
		   info->CurrentLayout.pixel_code));
    }
    info->pitch = (info->CurrentLayout.displayWidth / 8) * (info->CurrentLayout.pixel_bytes == 3 ? 3 : 1);

    R128TRACE(("Pitch for acceleration = %d\n", info->pitch));

    R128WaitForFifo(pScrn, 2);
    OUTREG(R128_DEFAULT_OFFSET, 0);
    OUTREG(R128_DEFAULT_PITCH,  info->pitch);

    R128WaitForFifo(pScrn, 4);
    OUTREG(R128_AUX_SC_CNTL,             0);
    OUTREG(R128_DEFAULT_SC_BOTTOM_RIGHT, (R128_DEFAULT_SC_RIGHT_MAX
					  | R128_DEFAULT_SC_BOTTOM_MAX));
    OUTREG(R128_SC_TOP_LEFT,             0);
    OUTREG(R128_SC_BOTTOM_RIGHT,         (R128_DEFAULT_SC_RIGHT_MAX
					  | R128_DEFAULT_SC_BOTTOM_MAX));

    info->dp_gui_master_cntl = ((info->datatype << R128_GMC_DST_DATATYPE_SHIFT)
				| R128_GMC_CLR_CMP_CNTL_DIS
				| R128_GMC_AUX_CLIP_DIS);
    R128WaitForFifo(pScrn, 1);
    OUTREG(R128_DP_GUI_MASTER_CNTL, (info->dp_gui_master_cntl
				     | R128_GMC_BRUSH_SOLID_COLOR
				     | R128_GMC_SRC_DATATYPE_COLOR));

    R128WaitForFifo(pScrn, 8);
    OUTREG(R128_DST_BRES_ERR,      0);
    OUTREG(R128_DST_BRES_INC,      0);
    OUTREG(R128_DST_BRES_DEC,      0);
    OUTREG(R128_DP_BRUSH_FRGD_CLR, 0xffffffff);
    OUTREG(R128_DP_BRUSH_BKGD_CLR, 0x00000000);
    OUTREG(R128_DP_SRC_FRGD_CLR,   0xffffffff);
    OUTREG(R128_DP_SRC_BKGD_CLR,   0x00000000);
    OUTREG(R128_DP_WRITE_MASK,     0xffffffff);

    R128WaitForFifo(pScrn, 1);

#if X_BYTE_ORDER == X_BIG_ENDIAN
    /* FIXME: this is a kludge for texture uploads in the 3D driver. Look at
     * how the radeon driver handles HOST_DATA_SWAP if you want to implement
     * CCE ImageWrite acceleration or anything needing this bit */
#ifdef XF86DRI
    if (info->directRenderingEnabled)
	OUTREGP(R128_DP_DATATYPE, 0, ~R128_HOST_BIG_ENDIAN_EN);
    else
#endif
	OUTREGP(R128_DP_DATATYPE,
		R128_HOST_BIG_ENDIAN_EN, ~R128_HOST_BIG_ENDIAN_EN);
#else /* X_LITTLE_ENDIAN */
    OUTREGP(R128_DP_DATATYPE, 0, ~R128_HOST_BIG_ENDIAN_EN);
#endif

#ifdef XF86DRI
    info->sc_left         = 0x00000000;
    info->sc_right        = R128_DEFAULT_SC_RIGHT_MAX;
    info->sc_top          = 0x00000000;
    info->sc_bottom       = R128_DEFAULT_SC_BOTTOM_MAX;

    info->re_top_left     = 0x00000000;
    info->re_width_height = ((0x7ff << R128_RE_WIDTH_SHIFT) |
			     (0x7ff << R128_RE_HEIGHT_SHIFT));

    info->aux_sc_cntl     = 0x00000000;
#endif

    R128WaitForIdle(pScrn);
}

#ifdef XF86DRI

/* Setup for XAA SolidFill. */
static void R128CCESetupForSolidFill(ScrnInfoPtr pScrn,
				     int color, int rop,
				     unsigned int planemask)
{
    R128InfoPtr   info = R128PTR(pScrn);
    RING_LOCALS;

    R128CCE_REFRESH( pScrn, info );

    BEGIN_RING( 8 );

    OUT_RING_REG( R128_DP_GUI_MASTER_CNTL,
		  (info->dp_gui_master_cntl
		   | R128_GMC_BRUSH_SOLID_COLOR
		   | R128_GMC_SRC_DATATYPE_COLOR
		   | R128_ROP[rop].pattern) );

    OUT_RING_REG( R128_DP_BRUSH_FRGD_CLR,  color );
    OUT_RING_REG( R128_DP_WRITE_MASK,	   planemask );
    OUT_RING_REG( R128_DP_CNTL,		   (R128_DST_X_LEFT_TO_RIGHT |
					    R128_DST_Y_TOP_TO_BOTTOM));
    ADVANCE_RING();
}

/* Subsequent XAA SolidFillRect.

   Tests: xtest CH06/fllrctngl, xterm
*/
static void R128CCESubsequentSolidFillRect(ScrnInfoPtr pScrn,
					   int x, int y, int w, int h)
{
    R128InfoPtr   info = R128PTR(pScrn);
    RING_LOCALS;

    R128CCE_REFRESH( pScrn, info );

    BEGIN_RING( 4 );

    OUT_RING_REG( R128_DST_Y_X,          (y << 16) | x );
    OUT_RING_REG( R128_DST_WIDTH_HEIGHT, (w << 16) | h );

    ADVANCE_RING();
}

/* Setup for XAA screen-to-screen copy.

   Tests: xtest CH06/fllrctngl (also tests transparency).
*/
static void R128CCESetupForScreenToScreenCopy(ScrnInfoPtr pScrn,
					       int xdir, int ydir, int rop,
					       unsigned int planemask,
					       int trans_color)
{
    R128InfoPtr   info = R128PTR(pScrn);
    RING_LOCALS;

    R128CCE_REFRESH( pScrn, info );

    info->xdir = xdir;
    info->ydir = ydir;

    BEGIN_RING( 6 );

    OUT_RING_REG( R128_DP_GUI_MASTER_CNTL,
		  (info->dp_gui_master_cntl
		   | R128_GMC_BRUSH_NONE
		   | R128_GMC_SRC_DATATYPE_COLOR
		   | R128_ROP[rop].rop
		   | R128_DP_SRC_SOURCE_MEMORY) );

    OUT_RING_REG( R128_DP_WRITE_MASK, planemask );
    OUT_RING_REG( R128_DP_CNTL,
		  ((xdir >= 0 ? R128_DST_X_LEFT_TO_RIGHT : 0) |
		   (ydir >= 0 ? R128_DST_Y_TOP_TO_BOTTOM : 0)) );

    ADVANCE_RING();

    if ((trans_color != -1) || (info->XAAForceTransBlit == TRUE)) {
	BEGIN_RING( 6 );

	OUT_RING_REG( R128_CLR_CMP_CLR_SRC, trans_color );
	OUT_RING_REG( R128_CLR_CMP_MASK,    R128_CLR_CMP_MSK );
	OUT_RING_REG( R128_CLR_CMP_CNTL,    (R128_SRC_CMP_NEQ_COLOR |
					     R128_CLR_CMP_SRC_SOURCE) );

	ADVANCE_RING();
    }
}

/* Subsequent XAA screen-to-screen copy. */
static void R128CCESubsequentScreenToScreenCopy(ScrnInfoPtr pScrn,
						 int xa, int ya,
						 int xb, int yb,
						 int w, int h)
{
    R128InfoPtr   info = R128PTR(pScrn);
    RING_LOCALS;

    R128CCE_REFRESH( pScrn, info );

    if (info->xdir < 0) xa += w - 1, xb += w - 1;
    if (info->ydir < 0) ya += h - 1, yb += h - 1;

    BEGIN_RING( 6 );

    OUT_RING_REG( R128_SRC_Y_X,          (ya << 16) | xa );
    OUT_RING_REG( R128_DST_Y_X,          (yb << 16) | xb );
    OUT_RING_REG( R128_DST_HEIGHT_WIDTH, (h << 16) | w );

    ADVANCE_RING();
}


/*
 * XAA scanline color expansion
 *
 * We use HOSTDATA_BLT CCE packets, dividing the image in chunks that fit into
 * the indirect buffer if necessary.
 */
static void R128CCESetupForScanlineCPUToScreenColorExpandFill(ScrnInfoPtr pScrn,
							      int fg, int bg,
							      int rop,
							      unsigned int
							      planemask)
{
    R128InfoPtr   info      = R128PTR(pScrn);
    RING_LOCALS;

    R128CCE_REFRESH( pScrn, info );

    BEGIN_RING( 2 );
    OUT_RING_REG(R128_DP_WRITE_MASK,      planemask);
    ADVANCE_RING();

    info->scanline_rop = rop;
    info->scanline_fg  = fg;
    info->scanline_bg  = bg;
}

/* Helper function to write out a HOSTDATA_BLT packet into the indirect buffer
   and set the XAA scratch buffer address appropriately */
static void R128CCEScanlineCPUToScreenColorExpandFillPacket(ScrnInfoPtr pScrn,
							    int bufno)
{
    R128InfoPtr	info = R128PTR(pScrn);
    int chunk_words = info->scanline_hpass * info->scanline_words;
    RING_LOCALS;

    R128CCE_REFRESH( pScrn, info );

    BEGIN_RING( chunk_words+9 );

    OUT_RING( CCE_PACKET3( R128_CCE_PACKET3_CNTL_HOSTDATA_BLT, chunk_words+9-2 ) );
#if X_BYTE_ORDER == X_LITTLE_ENDIAN
    OUT_RING( (info->dp_gui_master_cntl
	       | R128_GMC_DST_CLIPPING
	       | R128_GMC_BRUSH_NONE
	       | (info->scanline_bg == -1
		  ? R128_GMC_SRC_DATATYPE_MONO_FG_LA
		  : R128_GMC_SRC_DATATYPE_MONO_FG_BG)
	       | R128_ROP[info->scanline_rop].rop
	       | R128_GMC_BYTE_LSB_TO_MSB
	       | R128_DP_SRC_SOURCE_HOST_DATA));
#else	/* X_BYTE_ORDER == X_BIG_ENDIAN */
    OUT_RING( (info->dp_gui_master_cntl
	       | R128_GMC_DST_CLIPPING
	       | R128_GMC_BRUSH_NONE
	       | (info->scanline_bg == -1
		  ? R128_GMC_SRC_DATATYPE_MONO_FG_LA
		  : R128_GMC_SRC_DATATYPE_MONO_FG_BG)
	       | R128_ROP[info->scanline_rop].rop
	       | R128_DP_SRC_SOURCE_HOST_DATA));
#endif
    OUT_RING( (info->scanline_y << 16) | (info->scanline_x1clip & 0xffff) );
    OUT_RING( ((info->scanline_y+info->scanline_hpass-1) << 16) | ((info->scanline_x2clip-1) & 0xffff) );
    OUT_RING( info->scanline_fg );
    OUT_RING( info->scanline_bg );
    OUT_RING( (info->scanline_y << 16) | (info->scanline_x & 0xffff));

    /* Have to pad the width here and use clipping engine */
    OUT_RING( (info->scanline_hpass << 16)      | ((info->scanline_w + 31) & ~31));

    OUT_RING( chunk_words );

    info->scratch_buffer[bufno] = (unsigned char *) &__head[__count];
    __count += chunk_words;

    ADVANCE_RING();

    info->scanline_y += info->scanline_hpass;
    info->scanline_h -= info->scanline_hpass;

    if ( R128_VERBOSE )
          xf86DrvMsg( pScrn->scrnIndex, X_INFO,
		      "%s: hpass=%d, words=%d => chunk_words=%d, y=%d, h=%d\n",
		      __FUNCTION__, info->scanline_hpass, info->scanline_words,
		      chunk_words, info->scanline_y, info->scanline_h );
}

/* Subsequent XAA indirect CPU-to-screen color expansion.  This is only
   called once for each rectangle. */
static void R128CCESubsequentScanlineCPUToScreenColorExpandFill(ScrnInfoPtr pScrn,
								int x, int y,
								int w, int h,
								int skipleft)
{
    R128InfoPtr   info      = R128PTR(pScrn);

#define BUFSIZE ( R128_BUFFER_SIZE/4-9 )

    info->scanline_x      = x;
    info->scanline_y      = y;
    info->scanline_w      = w;
    info->scanline_h      = h;

    info->scanline_x1clip = x+skipleft;
    info->scanline_x2clip = x+w;

    info->scanline_words  = (w + 31) >> 5;
    info->scanline_hpass  = min(h,(BUFSIZE/info->scanline_words));

    if ( R128_VERBOSE )
        xf86DrvMsg( pScrn->scrnIndex, X_INFO,
		    "%s: x=%d, y=%d, w=%d, h=%d, skipleft=%d => x1clip=%d, x2clip=%d, hpass=%d, words=%d\n",
		    __FUNCTION__, x, y, w, h, skipleft, info->scanline_x1clip, info->scanline_x2clip,
		    info->scanline_hpass, info->scanline_words );

    R128CCEScanlineCPUToScreenColorExpandFillPacket(pScrn, 0);
}

/* Subsequent XAA indirect CPU-to-screen color expansion.  This is called
   once for each scanline. */
static void R128CCESubsequentColorExpandScanline(ScrnInfoPtr pScrn,
						 int bufno)
{
    R128InfoPtr     info      = R128PTR(pScrn);

    if ( R128_VERBOSE )
        xf86DrvMsg( pScrn->scrnIndex, X_INFO,
		    "%s enter: scanline_hpass=%d, scanline_h=%d\n",
		    __FUNCTION__, info->scanline_hpass, info->scanline_h );

    if (--info->scanline_hpass) {
        info->scratch_buffer[bufno] += 4 * info->scanline_words;
    }
    else if(info->scanline_h) {
        info->scanline_hpass = min(info->scanline_h,(BUFSIZE/info->scanline_words));
        R128CCEScanlineCPUToScreenColorExpandFillPacket(pScrn, bufno);
    }

    if ( R128_VERBOSE )
        xf86DrvMsg( pScrn->scrnIndex, X_INFO,
		    "%s exit: scanline_hpass=%d, scanline_h=%d\n",
		    __FUNCTION__, info->scanline_hpass, info->scanline_h );
}

/* Solid lines */
static void R128CCESetupForSolidLine(ScrnInfoPtr pScrn,
				  int color, int rop, unsigned int planemask)
{
    R128InfoPtr   info      = R128PTR(pScrn);
    RING_LOCALS;

    R128CCE_REFRESH( pScrn, info );

    BEGIN_RING( 6 );

    OUT_RING_REG(R128_DP_GUI_MASTER_CNTL, (info->dp_gui_master_cntl
				     | R128_GMC_BRUSH_SOLID_COLOR
				     | R128_GMC_SRC_DATATYPE_COLOR
				     | R128_ROP[rop].pattern));
    OUT_RING_REG(R128_DP_BRUSH_FRGD_CLR,  color);
    OUT_RING_REG(R128_DP_WRITE_MASK,      planemask);

    ADVANCE_RING();
}

static void R128CCESubsequentSolidBresenhamLine(ScrnInfoPtr pScrn,
					     int x, int y,
					     int major, int minor,
					     int err, int len, int octant)
{
    R128InfoPtr   info      = R128PTR(pScrn);
    int           flags     = 0;
    RING_LOCALS;

    R128CCE_REFRESH( pScrn, info );

    if (octant & YMAJOR)         flags |= R128_DST_Y_MAJOR;
    if (!(octant & XDECREASING)) flags |= R128_DST_X_DIR_LEFT_TO_RIGHT;
    if (!(octant & YDECREASING)) flags |= R128_DST_Y_DIR_TOP_TO_BOTTOM;

    BEGIN_RING( 12 );

    OUT_RING_REG(R128_DP_CNTL_XDIR_YDIR_YMAJOR, flags);
    OUT_RING_REG(R128_DST_Y_X,                  (y << 16) | x);
    OUT_RING_REG(R128_DST_BRES_ERR,             err);
    OUT_RING_REG(R128_DST_BRES_INC,             minor);
    OUT_RING_REG(R128_DST_BRES_DEC,             -major);
    OUT_RING_REG(R128_DST_BRES_LNTH,            len);

    ADVANCE_RING();
}

static void R128CCESubsequentSolidHorVertLine(ScrnInfoPtr pScrn,
					   int x, int y, int len, int dir )
{
    R128InfoPtr   info      = R128PTR(pScrn);
    RING_LOCALS;

    R128CCE_REFRESH( pScrn, info );

    BEGIN_RING( 2 );

    OUT_RING_REG(R128_DP_CNTL, (R128_DST_X_LEFT_TO_RIGHT
			  | R128_DST_Y_TOP_TO_BOTTOM));

    ADVANCE_RING();

    if (dir == DEGREES_0) {
	R128CCESubsequentSolidFillRect(pScrn, x, y, len, 1);
    } else {
	R128CCESubsequentSolidFillRect(pScrn, x, y, 1, len);
    }
}

/* Dashed lines */
static void R128CCESetupForDashedLine(ScrnInfoPtr pScrn,
				   int fg, int bg,
				   int rop, unsigned int planemask,
				   int length, unsigned char *pattern)
{
    R128InfoPtr   info      = R128PTR(pScrn);
    CARD32        pat       = *(CARD32 *)(pointer)pattern;
    RING_LOCALS;

    R128CCE_REFRESH( pScrn, info );

#if X_BYTE_ORDER == X_LITTLE_ENDIAN
# define PAT_SHIFT(pat,n) pat << n
#else
# define PAT_SHIFT(pat,n) pat >> n
#endif

    switch (length) {
    case  2: pat |= PAT_SHIFT(pat,2); /* fall through */
    case  4: pat |= PAT_SHIFT(pat,4); /* fall through */
    case  8: pat |= PAT_SHIFT(pat,8); /* fall through */
    case 16: pat |= PAT_SHIFT(pat,16);
    }

    BEGIN_RING( 10 );

    OUT_RING_REG(R128_DP_GUI_MASTER_CNTL, (info->dp_gui_master_cntl
				     | (bg == -1
					? R128_GMC_BRUSH_32x1_MONO_FG_LA
					: R128_GMC_BRUSH_32x1_MONO_FG_BG)
				     | R128_ROP[rop].pattern
				     | R128_GMC_BYTE_LSB_TO_MSB));
    OUT_RING_REG(R128_DP_WRITE_MASK,      planemask);
    OUT_RING_REG(R128_DP_BRUSH_FRGD_CLR,  fg);
    OUT_RING_REG(R128_DP_BRUSH_BKGD_CLR,  bg);
    OUT_RING_REG(R128_BRUSH_DATA0,        pat);

    ADVANCE_RING();
}

static void R128CCESubsequentDashedBresenhamLine(ScrnInfoPtr pScrn,
					      int x, int y,
					      int major, int minor,
					      int err, int len, int octant,
					      int phase)
{
    R128InfoPtr   info      = R128PTR(pScrn);
    int           flags     = 0;
    RING_LOCALS;

    R128CCE_REFRESH( pScrn, info );

    if (octant & YMAJOR)         flags |= R128_DST_Y_MAJOR;
    if (!(octant & XDECREASING)) flags |= R128_DST_X_DIR_LEFT_TO_RIGHT;
    if (!(octant & YDECREASING)) flags |= R128_DST_Y_DIR_TOP_TO_BOTTOM;

    BEGIN_RING( 14 );

    OUT_RING_REG(R128_DP_CNTL_XDIR_YDIR_YMAJOR, flags);
    OUT_RING_REG(R128_DST_Y_X,                  (y << 16) | x);
    OUT_RING_REG(R128_BRUSH_Y_X,                (phase << 16) | phase);
    OUT_RING_REG(R128_DST_BRES_ERR,             err);
    OUT_RING_REG(R128_DST_BRES_INC,             minor);
    OUT_RING_REG(R128_DST_BRES_DEC,             -major);
    OUT_RING_REG(R128_DST_BRES_LNTH,            len);

    ADVANCE_RING();
}

/* Mono 8x8 pattern color expansion */
static void R128CCESetupForMono8x8PatternFill(ScrnInfoPtr pScrn,
					   int patternx, int patterny,
					   int fg, int bg, int rop,
					   unsigned int planemask)
{
    R128InfoPtr   info      = R128PTR(pScrn);
    RING_LOCALS;

    R128CCE_REFRESH( pScrn, info );

    BEGIN_RING( 12 );

    OUT_RING_REG(R128_DP_GUI_MASTER_CNTL, (info->dp_gui_master_cntl
				     | (bg == -1
					? R128_GMC_BRUSH_8X8_MONO_FG_LA
					: R128_GMC_BRUSH_8X8_MONO_FG_BG)
				     | R128_ROP[rop].pattern
				     | R128_GMC_BYTE_LSB_TO_MSB));
    OUT_RING_REG(R128_DP_WRITE_MASK,      planemask);
    OUT_RING_REG(R128_DP_BRUSH_FRGD_CLR,  fg);
    OUT_RING_REG(R128_DP_BRUSH_BKGD_CLR,  bg);
    OUT_RING_REG(R128_BRUSH_DATA0,        patternx);
    OUT_RING_REG(R128_BRUSH_DATA1,        patterny);

    ADVANCE_RING();
}

static void R128CCESubsequentMono8x8PatternFillRect(ScrnInfoPtr pScrn,
						 int patternx, int patterny,
						 int x, int y, int w, int h)
{
    R128InfoPtr   info      = R128PTR(pScrn);
    RING_LOCALS;

    R128CCE_REFRESH( pScrn, info );

    BEGIN_RING( 6 );

    OUT_RING_REG(R128_BRUSH_Y_X,        (patterny << 8) | patternx);
    OUT_RING_REG(R128_DST_Y_X,          (y << 16) | x);
    OUT_RING_REG(R128_DST_HEIGHT_WIDTH, (h << 16) | w);

    ADVANCE_RING();
}

/* Get an indirect buffer for the CCE 2D acceleration commands.
 */
drmBufPtr R128CCEGetBuffer( ScrnInfoPtr pScrn )
{
    R128InfoPtr   info = R128PTR(pScrn);
    drmDMAReq dma;
    drmBufPtr buf = NULL;
    int indx = 0;
    int size = 0;
    int ret, i = 0;

#if 0
    /* FIXME: pScrn->pScreen has not been initialized when this is first
       called from RADEONSelectBuffer via RADEONDRICPInit.  We could use
       the screen index from pScrn, which is initialized, and then get
       the screen from screenInfo.screens[index], but that is a hack. */
    dma.context = DRIGetContext(pScrn->pScreen);
#else
    dma.context = 0x00000001; /* This is the X server's context */
#endif
    dma.send_count = 0;
    dma.send_list = NULL;
    dma.send_sizes = NULL;
    dma.flags = 0;
    dma.request_count = 1;
    dma.request_size = R128_BUFFER_SIZE;
    dma.request_list = &indx;
    dma.request_sizes = &size;
    dma.granted_count = 0;

    while ( 1 ) {
	do {
	    ret = drmDMA( info->drmFD, &dma );
	    if ( ret && ret != -EAGAIN ) {
		xf86DrvMsg( pScrn->scrnIndex, X_ERROR,
			    "%s: CCE GetBuffer %d\n", __FUNCTION__, ret );
	    }
	} while ( ( ret == -EAGAIN ) && ( i++ < R128_TIMEOUT ) );

	if ( ret == 0 ) {
	    buf = &info->buffers->list[indx];
	    buf->used = 0;
	    if ( R128_VERBOSE ) {
		xf86DrvMsg( pScrn->scrnIndex, X_INFO,
			    "   GetBuffer returning %d\n", buf->idx );
	    }
	    return buf;
	}

	xf86DrvMsg( pScrn->scrnIndex, X_ERROR,
		    "GetBuffer timed out, resetting engine...\n");
	R128EngineReset( pScrn );
	/* R128EngineRestore( pScrn ); FIXME ??? */

	/* Always restart the engine when doing CCE 2D acceleration */
	R128CCE_RESET( pScrn, info );
	R128CCE_START( pScrn, info );
    }
}

/* Flush the indirect buffer to the kernel for submission to the card.
 */
void R128CCEFlushIndirect( ScrnInfoPtr pScrn, int discard )
{
    R128InfoPtr   info = R128PTR(pScrn);
    drmBufPtr buffer = info->indirectBuffer;
    int start = info->indirectStart;
    drmR128Indirect indirect;

    if ( !buffer )
	return;

    if ( (start == buffer->used) && !discard )
        return;

    indirect.idx = buffer->idx;
    indirect.start = start;
    indirect.end = buffer->used;
    indirect.discard = discard;

    drmCommandWriteRead( info->drmFD, DRM_R128_INDIRECT,
                         &indirect, sizeof(drmR128Indirect));

    if ( discard )
        buffer = info->indirectBuffer = R128CCEGetBuffer( pScrn );

    /* pad to an even number of dwords */
    if (buffer->used & 7)
        buffer->used = ( buffer->used+7 ) & ~7;

    info->indirectStart = buffer->used;
}

/* Flush and release the indirect buffer.
 */
void R128CCEReleaseIndirect( ScrnInfoPtr pScrn )
{
    R128InfoPtr   info = R128PTR(pScrn);
    drmBufPtr buffer = info->indirectBuffer;
    int start = info->indirectStart;
    drmR128Indirect indirect;

    info->indirectBuffer = NULL;
    info->indirectStart = 0;

    if ( !buffer )
	return;

    indirect.idx = buffer->idx;
    indirect.start = start;
    indirect.end = buffer->used;
    indirect.discard = 1;

    drmCommandWriteRead( info->drmFD, DRM_R128_INDIRECT,
                         &indirect, sizeof(drmR128Indirect));
}

static void R128CCEAccelInit(ScrnInfoPtr pScrn, XAAInfoRecPtr a)
{
    R128InfoPtr info = R128PTR(pScrn);

    a->Flags                            = (PIXMAP_CACHE
					   | OFFSCREEN_PIXMAPS
					   | LINEAR_FRAMEBUFFER);

				/* Sync */
    a->Sync                             = R128CCEWaitForIdle;

    /* Solid Filled Rectangle */
    a->PolyFillRectSolidFlags           = 0;
    a->SetupForSolidFill                = R128CCESetupForSolidFill;
    a->SubsequentSolidFillRect          = R128CCESubsequentSolidFillRect;

				/* Screen-to-screen Copy */
				/* Transparency uses the wrong colors for
				   24 bpp mode -- the transparent part is
				   correct, but the opaque color is wrong.
				   This can be seen with netscape's I-bar
				   cursor when editing in the URL location
				   box. */
    a->ScreenToScreenCopyFlags          = ((pScrn->bitsPerPixel == 24)
					   ? NO_TRANSPARENCY
					   : 0);
    a->SetupForScreenToScreenCopy       = R128CCESetupForScreenToScreenCopy;
    a->SubsequentScreenToScreenCopy     = R128CCESubsequentScreenToScreenCopy;

				/* Indirect CPU-To-Screen Color Expand */
    a->ScanlineCPUToScreenColorExpandFillFlags = LEFT_EDGE_CLIPPING
					       | LEFT_EDGE_CLIPPING_NEGATIVE_X;
    a->NumScanlineColorExpandBuffers   = 1;
    a->ScanlineColorExpandBuffers      = info->scratch_buffer;
    info->scratch_buffer[0]            = NULL;
    a->SetupForScanlineCPUToScreenColorExpandFill
	= R128CCESetupForScanlineCPUToScreenColorExpandFill;
    a->SubsequentScanlineCPUToScreenColorExpandFill
	= R128CCESubsequentScanlineCPUToScreenColorExpandFill;
    a->SubsequentColorExpandScanline   = R128CCESubsequentColorExpandScanline;

				/* Bresenham Solid Lines */
    a->SetupForSolidLine               = R128CCESetupForSolidLine;
    a->SubsequentSolidBresenhamLine    = R128CCESubsequentSolidBresenhamLine;
    a->SubsequentSolidHorVertLine      = R128CCESubsequentSolidHorVertLine;

				/* Bresenham Dashed Lines*/
    a->SetupForDashedLine              = R128CCESetupForDashedLine;
    a->SubsequentDashedBresenhamLine   = R128CCESubsequentDashedBresenhamLine;
    a->DashPatternMaxLength            = 32;
    a->DashedLineFlags                 = (LINE_PATTERN_LSBFIRST_LSBJUSTIFIED
					  | LINE_PATTERN_POWER_OF_2_ONLY);

				/* Mono 8x8 Pattern Fill (Color Expand) */
    a->SetupForMono8x8PatternFill       = R128CCESetupForMono8x8PatternFill;
    a->SubsequentMono8x8PatternFillRect = R128CCESubsequentMono8x8PatternFillRect;
    a->Mono8x8PatternFillFlags          = (HARDWARE_PATTERN_PROGRAMMED_BITS
					   | HARDWARE_PATTERN_PROGRAMMED_ORIGIN
					   | HARDWARE_PATTERN_SCREEN_ORIGIN
					   | BIT_ORDER_IN_BYTE_LSBFIRST);
}
#endif

static void R128MMIOAccelInit(ScrnInfoPtr pScrn, XAAInfoRecPtr a)
{
    R128InfoPtr info = R128PTR(pScrn);

    a->Flags                            = (PIXMAP_CACHE
					   | OFFSCREEN_PIXMAPS
					   | LINEAR_FRAMEBUFFER);

				/* Sync */
    a->Sync                             = R128WaitForIdle;

				/* Solid Filled Rectangle */
    a->PolyFillRectSolidFlags           = 0;
    a->SetupForSolidFill                = R128SetupForSolidFill;
    a->SubsequentSolidFillRect          = R128SubsequentSolidFillRect;

				/* Screen-to-screen Copy */
				/* Transparency uses the wrong colors for
				   24 bpp mode -- the transparent part is
				   correct, but the opaque color is wrong.
				   This can be seen with netscape's I-bar
				   cursor when editing in the URL location
				   box. */
    a->ScreenToScreenCopyFlags          = ((pScrn->bitsPerPixel == 24)
					   ? NO_TRANSPARENCY
					   : 0);
    a->SetupForScreenToScreenCopy       = R128SetupForScreenToScreenCopy;
    a->SubsequentScreenToScreenCopy     = R128SubsequentScreenToScreenCopy;

				/* Mono 8x8 Pattern Fill (Color Expand) */
    a->SetupForMono8x8PatternFill       = R128SetupForMono8x8PatternFill;
    a->SubsequentMono8x8PatternFillRect = R128SubsequentMono8x8PatternFillRect;
    a->Mono8x8PatternFillFlags          = (HARDWARE_PATTERN_PROGRAMMED_BITS
					   | HARDWARE_PATTERN_PROGRAMMED_ORIGIN
					   | HARDWARE_PATTERN_SCREEN_ORIGIN
					   | BIT_ORDER_IN_BYTE_LSBFIRST);

				/* Indirect CPU-To-Screen Color Expand */
    a->ScanlineCPUToScreenColorExpandFillFlags = LEFT_EDGE_CLIPPING
					       | LEFT_EDGE_CLIPPING_NEGATIVE_X;
    a->NumScanlineColorExpandBuffers   = 1;
    a->ScanlineColorExpandBuffers      = info->scratch_buffer;
    info->scratch_save                 = xalloc(((pScrn->virtualX+31)/32*4)
					    + (pScrn->virtualX
					    * info->CurrentLayout.pixel_bytes));
    info->scratch_buffer[0]            = info->scratch_save;
    a->SetupForScanlineCPUToScreenColorExpandFill
	= R128SetupForScanlineCPUToScreenColorExpandFill;
    a->SubsequentScanlineCPUToScreenColorExpandFill
	= R128SubsequentScanlineCPUToScreenColorExpandFill;
    a->SubsequentColorExpandScanline   = R128SubsequentColorExpandScanline;

				/* Bresenham Solid Lines */
    a->SetupForSolidLine               = R128SetupForSolidLine;
    a->SubsequentSolidBresenhamLine    = R128SubsequentSolidBresenhamLine;
    a->SubsequentSolidHorVertLine      = R128SubsequentSolidHorVertLine;

				/* Bresenham Dashed Lines*/
    a->SetupForDashedLine              = R128SetupForDashedLine;
    a->SubsequentDashedBresenhamLine   = R128SubsequentDashedBresenhamLine;
    a->DashPatternMaxLength            = 32;
    a->DashedLineFlags                 = (LINE_PATTERN_LSBFIRST_LSBJUSTIFIED
					  | LINE_PATTERN_POWER_OF_2_ONLY);

				/* ImageWrite */
    a->NumScanlineImageWriteBuffers    = 1;
    a->ScanlineImageWriteBuffers       = info->scratch_buffer;
    info->scratch_buffer[0]            = info->scratch_save;
    a->SetupForScanlineImageWrite      = R128SetupForScanlineImageWrite;
    a->SubsequentScanlineImageWriteRect= R128SubsequentScanlineImageWriteRect;
    a->SubsequentImageWriteScanline    = R128SubsequentImageWriteScanline;
    a->ScanlineImageWriteFlags         = CPU_TRANSFER_PAD_DWORD
		/* Performance tests show that we shouldn't use GXcopy for
		 * uploads as a memcpy is faster */
					  | NO_GXCOPY
					  | LEFT_EDGE_CLIPPING
					  | LEFT_EDGE_CLIPPING_NEGATIVE_X
					  | SCANLINE_PAD_DWORD;
}

/* Initialize XAA for supported acceleration and also initialize the
   graphics hardware for acceleration. */
Bool R128AccelInit(ScreenPtr pScreen)
{
    ScrnInfoPtr   pScrn = xf86Screens[pScreen->myNum];
    R128InfoPtr   info  = R128PTR(pScrn);
    XAAInfoRecPtr a;

    if (!(a = info->accel = XAACreateInfoRec())) return FALSE;

#ifdef XF86DRI
    if (info->directRenderingEnabled)
	R128CCEAccelInit(pScrn, a);
    else
#endif
	R128MMIOAccelInit(pScrn, a);

    R128EngineInit(pScrn);
    return XAAInit(pScreen, a);
}