aboutsummaryrefslogtreecommitdiff
path: root/sim/mips/sky-pke.c
blob: 6e318750eaab4a3dd451b946204bef9178341142 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
/* Copyright (C) 1998, Cygnus Solutions */


#include "config.h"

#include <stdlib.h>
#include "sim-main.h"
#include "sim-bits.h"
#include "sim-assert.h"
#include "sky-pke.h"
#include "sky-dma.h"
#include "sky-vu.h"
#include "sky-gpuif.h"
#include "sky-device.h"


#ifdef HAVE_STRING_H
#include <string.h>
#else
#ifdef HAVE_STRINGS_H
#include <strings.h>
#endif
#endif


/* Internal function declarations */

static int pke_io_read_buffer(device*, void*, int, address_word,
			       unsigned, sim_cpu*, sim_cia);
static int pke_io_write_buffer(device*, const void*, int, address_word,
			       unsigned, sim_cpu*, sim_cia);
static void pke_reset(struct pke_device*);
static void pke_issue(SIM_DESC, struct pke_device*);
static void pke_pc_advance(struct pke_device*, int num_words);
static struct fifo_quadword* pke_pcrel_fifo(struct pke_device*, int operand_num, 
					    unsigned_4** operand);
static unsigned_4* pke_pcrel_operand(struct pke_device*, int operand_num);
static unsigned_4 pke_pcrel_operand_bits(struct pke_device*, int bit_offset,
					 int bit_width, unsigned_4* sourceaddr);
static void pke_attach(SIM_DESC sd, struct pke_device* me);
enum pke_check_target { chk_vu, chk_path1, chk_path2, chk_path3 };
static int pke_check_stall(struct pke_device* me, enum pke_check_target what);
static void pke_flip_dbf(struct pke_device* me);
static void pke_begin_interrupt_stall(struct pke_device* me);
/* PKEcode handlers */
static void pke_code_nop(struct pke_device* me, unsigned_4 pkecode);
static void pke_code_stcycl(struct pke_device* me, unsigned_4 pkecode);
static void pke_code_offset(struct pke_device* me, unsigned_4 pkecode);
static void pke_code_base(struct pke_device* me, unsigned_4 pkecode);
static void pke_code_itop(struct pke_device* me, unsigned_4 pkecode);
static void pke_code_stmod(struct pke_device* me, unsigned_4 pkecode);
static void pke_code_mskpath3(struct pke_device* me, unsigned_4 pkecode);
static void pke_code_pkemark(struct pke_device* me, unsigned_4 pkecode);
static void pke_code_flushe(struct pke_device* me, unsigned_4 pkecode);
static void pke_code_flush(struct pke_device* me, unsigned_4 pkecode);
static void pke_code_flusha(struct pke_device* me, unsigned_4 pkecode);
static void pke_code_pkemscal(struct pke_device* me, unsigned_4 pkecode);
static void pke_code_pkemscnt(struct pke_device* me, unsigned_4 pkecode);
static void pke_code_pkemscalf(struct pke_device* me, unsigned_4 pkecode);
static void pke_code_stmask(struct pke_device* me, unsigned_4 pkecode);
static void pke_code_strow(struct pke_device* me, unsigned_4 pkecode);
static void pke_code_stcol(struct pke_device* me, unsigned_4 pkecode);
static void pke_code_mpg(struct pke_device* me, unsigned_4 pkecode);
static void pke_code_direct(struct pke_device* me, unsigned_4 pkecode);
static void pke_code_directhl(struct pke_device* me, unsigned_4 pkecode);
static void pke_code_unpack(struct pke_device* me, unsigned_4 pkecode);
static void pke_code_error(struct pke_device* me, unsigned_4 pkecode);
unsigned_4 pke_fifo_flush(struct pke_fifo*);
void pke_fifo_reset(struct pke_fifo*);
struct fifo_quadword* pke_fifo_fit(struct pke_fifo*);
struct fifo_quadword* pke_fifo_access(struct pke_fifo*, unsigned_4 qwnum);
void pke_fifo_old(struct pke_fifo*, unsigned_4 qwnum);



/* Static data */

struct pke_device pke0_device = 
{ 
  { "pke0", &pke_io_read_buffer, &pke_io_write_buffer }, /* device */
  0, 0,        /* ID, flags */
  {},          /* regs */
  {}, 0,      /* FIFO write buffer */
  { NULL, 0, 0, 0 }, /* FIFO */
  NULL,           /* FIFO trace file */
  -1, -1, 0, 0, 0, /* invalid FIFO cache */
  0, 0            /* pc */
};


struct pke_device pke1_device = 
{ 
  { "pke1", &pke_io_read_buffer, &pke_io_write_buffer }, /* device */
  1, 0,        /* ID, flags */
  {},          /* regs */
  {}, 0,       /* FIFO write buffer */
  { NULL, 0, 0, 0 }, /* FIFO */
  NULL,           /* FIFO trace file */
  -1, -1, 0, 0, 0, /* invalid FIFO cache */
  0, 0         /* pc */
};



/* External functions */


/* Attach PKE addresses to main memory */

void
pke0_attach(SIM_DESC sd) 
{
  pke_attach(sd, & pke0_device);
  pke_reset(& pke0_device);
}

void
pke1_attach(SIM_DESC sd) 
{
  pke_attach(sd, & pke1_device);
  pke_reset(& pke1_device);
}



/* Issue a PKE instruction if possible */

void 
pke0_issue(SIM_DESC sd) 
{
  pke_issue(sd, & pke0_device);
}

void 
pke1_issue(SIM_DESC sd) 
{
  pke_issue(sd, & pke1_device);
}



/* Internal functions */


/* Attach PKE memory regions to simulator */

void 
pke_attach(SIM_DESC sd, struct pke_device* me) 
{
  /* register file */
  sim_core_attach (sd, NULL, 0, access_read_write, 0,
		   (me->pke_number == 0) ? PKE0_REGISTER_WINDOW_START : PKE1_REGISTER_WINDOW_START,
                   PKE_REGISTER_WINDOW_SIZE /*nr_bytes*/,
                   0 /*modulo*/,
                   (device*) me,
                   NULL /*buffer*/);

  /* FIFO port */
  sim_core_attach (sd, NULL, 0, access_read_write, 0,
		   (me->pke_number == 0) ? PKE0_FIFO_ADDR : PKE1_FIFO_ADDR,
                   sizeof(quadword) /*nr_bytes*/,
                   0 /*modulo*/,
                   (device*) me,
                   NULL /*buffer*/);

  /* VU MEM0 tracking table */
  sim_core_attach (sd, NULL, 0, access_read_write, 0,
		   ((me->pke_number == 0) ? VU0_MEM0_SRCADDR_START : VU1_MEM0_SRCADDR_START),
                   ((me->pke_number == 0) ? VU0_MEM0_SIZE : VU1_MEM0_SIZE) / 2,
                   0 /*modulo*/,
                   NULL,
                   NULL /*buffer*/);

  /* VU MEM1 tracking table */
  sim_core_attach (sd, NULL, 0, access_read_write, 0,
		   ((me->pke_number == 0) ? VU0_MEM1_SRCADDR_START : VU1_MEM1_SRCADDR_START),
                   ((me->pke_number == 0) ? VU0_MEM1_SIZE : VU1_MEM1_SIZE) / 4,
                   0 /*modulo*/,
                   NULL,
                   NULL /*buffer*/);


  /* attach to trace file if appropriate */
  {
    char trace_envvar[80];
    char* trace_filename = NULL;
    sprintf(trace_envvar, "VIF%d_TRACE_FILE", me->pke_number);
    trace_filename = getenv(trace_envvar);
    if(trace_filename != NULL)
      {
	me->fifo_trace_file = fopen(trace_filename, "w");
	if(me->fifo_trace_file == NULL)
	    perror("VIF FIFO trace error on fopen");
	else
	  setvbuf(me->fifo_trace_file, NULL, _IOLBF, 0);
      }
  }
}


/* Read PKE Pseudo-PC into buf in target order */
int
read_pke_pc (struct pke_device *me, void *buf)
{
  *((int *) buf) = H2T_4( (me->fifo_pc << 2) | me->qw_pc );
  return 4;
}


/* Read PKE reg into buf in target order */
int
read_pke_reg (struct pke_device *me, int reg_num, void *buf)
{
  /* handle reads to individual registers; clear `readable' on error */
  switch (reg_num)
    {
    /* handle common case of register reading, side-effect free */
    /* PKE1-only registers*/
    case PKE_REG_BASE:
    case PKE_REG_OFST:
    case PKE_REG_TOPS:
    case PKE_REG_TOP:
    case PKE_REG_DBF:
      if (me->pke_number == 0)
	{
	  *((int *) buf) = 0;
	  break;
	}
      /* fall through */

    /* PKE0 & PKE1 common registers*/
    case PKE_REG_STAT:
    case PKE_REG_ERR:
    case PKE_REG_MARK:
    case PKE_REG_CYCLE:
    case PKE_REG_MODE:
    case PKE_REG_NUM:
    case PKE_REG_MASK:
    case PKE_REG_CODE:
    case PKE_REG_ITOPS:
    case PKE_REG_ITOP:
    case PKE_REG_R0:
    case PKE_REG_R1:
    case PKE_REG_R2:
    case PKE_REG_R3:
    case PKE_REG_C0:
    case PKE_REG_C1:
    case PKE_REG_C2:
    case PKE_REG_C3:
      *((int *) buf) = H2T_4(me->regs[reg_num][0]);
      break;

    /* handle common case of write-only registers */
    case PKE_REG_FBRST:
      *((int *) buf) = 0;
      break;

    default:
      ASSERT(0); /* tests above should prevent this possibility */
    }

  return 4;
}


/* Handle a PKE read; return no. of bytes read */

int
pke_io_read_buffer(device *me_,
		   void *dest,
		   int space,
		   address_word addr,
		   unsigned nr_bytes,
		   sim_cpu *cpu,
		   sim_cia cia)
{
  /* downcast to gather embedding pke_device struct */
  struct pke_device* me = (struct pke_device*) me_;

  /* find my address ranges */
  address_word my_reg_start =
    (me->pke_number == 0) ? PKE0_REGISTER_WINDOW_START : PKE1_REGISTER_WINDOW_START;
  address_word my_fifo_addr =
    (me->pke_number == 0) ? PKE0_FIFO_ADDR : PKE1_FIFO_ADDR;

  /* enforce that an access does not span more than one quadword */
  address_word low = ADDR_TRUNC_QW(addr);
  address_word high = ADDR_TRUNC_QW(addr + nr_bytes - 1);
  if(low != high)
    return 0;

  /* classify address & handle */
  if((addr >= my_reg_start) && (addr < my_reg_start + PKE_REGISTER_WINDOW_SIZE))
    {
      /* register bank */
      int reg_num = ADDR_TRUNC_QW(addr - my_reg_start) >> 4;
      int reg_byte = ADDR_OFFSET_QW(addr);      /* find byte-offset inside register bank */
      quadword result;

      /* clear result */
      result[0] = result[1] = result[2] = result[3] = 0;

      read_pke_reg (me, reg_num, result);

      /* perform transfer & return */
      memcpy(dest, ((unsigned_1*) &result) + reg_byte, nr_bytes);

      return nr_bytes;
      /* NOTREACHED */
    }
  else if(addr >= my_fifo_addr &&
	  addr < my_fifo_addr + sizeof(quadword))
    {
      /* FIFO */

      /* FIFO is not readable: return a word of zeroes */
      memset(dest, 0, nr_bytes);
      return nr_bytes;
    }

  /* NOTREACHED */
  return 0;
}

/* Write PKE reg from buf, which is in target order */
int
write_pke_reg (struct pke_device *me, int reg_num, const void *buf)
{
  int writeable = 1;
  /* make words host-endian */
  unsigned_4 input = T2H_4( *((unsigned_4 *) buf) );

  /* handle writes to individual registers; clear `writeable' on error */
  switch (reg_num)
    {
    case PKE_REG_FBRST:
      /* Order these tests from least to most overriding, in case
	 multiple bits are set. */
      if(BIT_MASK_GET(input, PKE_REG_FBRST_STC_B, PKE_REG_FBRST_STC_E))
	{
	  /* clear a bunch of status bits */
	  PKE_REG_MASK_SET(me, STAT, PSS, 0);
	  PKE_REG_MASK_SET(me, STAT, PFS, 0);
	  PKE_REG_MASK_SET(me, STAT, PIS, 0);
	  PKE_REG_MASK_SET(me, STAT, INT, 0);
	  PKE_REG_MASK_SET(me, STAT, ER0, 0);
	  PKE_REG_MASK_SET(me, STAT, ER1, 0);
	  me->flags &= ~PKE_FLAG_PENDING_PSS;
	  /* will allow resumption of possible stalled instruction */
	}
      if(BIT_MASK_GET(input, PKE_REG_FBRST_STP_B, PKE_REG_FBRST_STP_E))
	{
	  me->flags |= PKE_FLAG_PENDING_PSS;
	}
      if(BIT_MASK_GET(input, PKE_REG_FBRST_FBK_B, PKE_REG_FBRST_FBK_E))
	{
	  PKE_REG_MASK_SET(me, STAT, PFS, 1);
	}
      if(BIT_MASK_GET(input, PKE_REG_FBRST_RST_B, PKE_REG_FBRST_RST_E))
	{
	  pke_reset(me);
	}
      break;
      
    case PKE_REG_ERR:
      /* copy bottom three bits */
      BIT_MASK_SET(me->regs[PKE_REG_ERR][0], 0, 2, BIT_MASK_GET(input, 0, 2));
      break;

    case PKE_REG_MARK:
      /* copy bottom sixteen bits */
      PKE_REG_MASK_SET(me, MARK, MARK, BIT_MASK_GET(input, 0, 15));
      /* reset MRK bit in STAT */
      PKE_REG_MASK_SET(me, STAT, MRK, 0);
      break;

      /* handle common case of read-only registers */
      /* PKE1-only registers - not really necessary to handle separately */
    case PKE_REG_BASE:
    case PKE_REG_OFST:
    case PKE_REG_TOPS:
    case PKE_REG_TOP:
    case PKE_REG_DBF:
      if(me->pke_number == 0)
	writeable = 0;
      /* fall through */
      /* PKE0 & PKE1 common registers*/
    case PKE_REG_STAT:
      /* ignore FDR bit for PKE1_STAT -- simulator does not implement PKE->RAM transfers */
    case PKE_REG_CYCLE:
    case PKE_REG_MODE:
    case PKE_REG_NUM:
    case PKE_REG_MASK:
    case PKE_REG_CODE:
    case PKE_REG_ITOPS:
    case PKE_REG_ITOP:
    case PKE_REG_R0:
    case PKE_REG_R1:
    case PKE_REG_R2:
    case PKE_REG_R3:
    case PKE_REG_C0:
    case PKE_REG_C1:
    case PKE_REG_C2:
    case PKE_REG_C3:
      writeable = 0;
      break;

    default:
      ASSERT(0); /* test above should prevent this possibility */
    }

  /* perform return */
  if(! writeable) 
    {
      return 0; /* error */
    } 

  return 4;
}


/* Handle a PKE write; return no. of bytes written */

int
pke_io_write_buffer(device *me_,
		    const void *src,
		    int space,
		    address_word addr,
		    unsigned nr_bytes,
		    sim_cpu *cpu,
		    sim_cia cia)
{ 
  /* downcast to gather embedding pke_device struct */
  struct pke_device* me = (struct pke_device*) me_;

  /* find my address ranges */
  address_word my_reg_start =
    (me->pke_number == 0) ? PKE0_REGISTER_WINDOW_START : PKE1_REGISTER_WINDOW_START;
  address_word my_fifo_addr =
    (me->pke_number == 0) ? PKE0_FIFO_ADDR : PKE1_FIFO_ADDR;

  /* enforce that an access does not span more than one quadword */
  address_word low = ADDR_TRUNC_QW(addr);
  address_word high = ADDR_TRUNC_QW(addr + nr_bytes - 1);
  if(low != high)
    return 0;

  /* classify address & handle */
  if((addr >= my_reg_start) && (addr < my_reg_start + PKE_REGISTER_WINDOW_SIZE))
    {
      /* register bank */
      int reg_num = ADDR_TRUNC_QW(addr - my_reg_start) >> 4;
      int reg_byte = ADDR_OFFSET_QW(addr);      /* find byte-offset inside register bank */
      quadword input;

      /* clear input */
      input[0] = input[1] = input[2] = input[3] = 0;

      /* write user-given bytes into input */
      memcpy(((unsigned_1*) &input) + reg_byte, src, nr_bytes);

      write_pke_reg (me, reg_num, input);
      return nr_bytes;

      /* NOTREACHED */
    }
  else if(addr >= my_fifo_addr &&
	  addr < my_fifo_addr + sizeof(quadword))
    {
      /* FIFO */
      struct fifo_quadword* fqw;
      int fifo_byte = ADDR_OFFSET_QW(addr);      /* find byte-offset inside fifo quadword */
      unsigned_4 dma_tag_present = 0;
      int i;

      /* collect potentially-partial quadword in write buffer; LE byte order */
      memcpy(((unsigned_1*)& me->fifo_qw_in_progress) + fifo_byte, src, nr_bytes);
      /* mark bytes written */
      for(i = fifo_byte; i < fifo_byte + nr_bytes; i++)
	BIT_MASK_SET(me->fifo_qw_done, i, i, 1);

      /* return if quadword not quite written yet */
      if(BIT_MASK_GET(me->fifo_qw_done, 0, sizeof(quadword)-1) !=
	 BIT_MASK_BTW(0, sizeof(quadword)-1))
	return nr_bytes;

      /* all done - process quadword after clearing flag */
      BIT_MASK_SET(me->fifo_qw_done, 0, sizeof(quadword)-1, 0);

      /* allocate required address in FIFO */
      fqw = pke_fifo_fit(& me->fifo);
      ASSERT(fqw != NULL);

      /* fill in unclassified FIFO quadword data in host byte order */
      fqw->word_class[0] = fqw->word_class[1] = 
	fqw->word_class[2] = fqw->word_class[3] = wc_unknown;
      fqw->data[0] = T2H_4(me->fifo_qw_in_progress[0]);
      fqw->data[1] = T2H_4(me->fifo_qw_in_progress[1]); 
      fqw->data[2] = T2H_4(me->fifo_qw_in_progress[2]); 
      fqw->data[3] = T2H_4(me->fifo_qw_in_progress[3]); 

      /* read DMAC-supplied indicators */
      ASSERT(sizeof(unsigned_4) == 4);
      PKE_MEM_READ(me, (me->pke_number == 0 ? DMA_D0_MADR : DMA_D1_MADR),
		   & fqw->source_address, /* converted to host-endian */
		   4);
      PKE_MEM_READ(me, (me->pke_number == 0 ? DMA_D0_PKTFLAG : DMA_D1_PKTFLAG),
		   & dma_tag_present,
		   4);

      if(dma_tag_present)
	{
	  /* lower two words are DMA tags */
	  fqw->word_class[0] = fqw->word_class[1] = wc_dma;
	}

      /* set FQC to "1" as FIFO is now not empty */ 
      PKE_REG_MASK_SET(me, STAT, FQC, 1);
      
      /* okay */
      return nr_bytes;
    }

  /* NOTREACHED */
  return 0;
}



/* Reset the PKE */
void
pke_reset(struct pke_device* me)
{
  /* advance PC over last quadword in FIFO; keep previous FIFO history  */
  me->fifo_pc = pke_fifo_flush(& me->fifo);
  me->qw_pc = 0;
  /* clear registers, flag, other state */
  memset(me->regs, 0, sizeof(me->regs));
  me->fifo_qw_done = 0;
  me->flags = 0;
}



/* Issue & swallow next PKE opcode if possible/available */

void
pke_issue(SIM_DESC sd, struct pke_device* me)
{
  struct fifo_quadword* fqw;
  unsigned_4 fw;
  unsigned_4 cmd, intr;

  /* 1 -- fetch PKE instruction */

  /* confirm availability of new quadword of PKE instructions */
  fqw = pke_fifo_access(& me->fifo, me->fifo_pc);
  if(fqw == NULL)
    return;

  /* skip over DMA tag, if present */
  pke_pc_advance(me, 0);
  /* note: this can only change qw_pc from 0 to 2 and will not
     invalidate fqw */

  /* "fetch" instruction quadword and word */ 
  fw = fqw->data[me->qw_pc];

  /* store word in PKECODE register */
  me->regs[PKE_REG_CODE][0] = fw;


  /* 2 -- test go / no-go for PKE execution */

  /* switch on STAT:PSS if PSS-pending and in idle state */
  if((PKE_REG_MASK_GET(me, STAT, PPS) == PKE_REG_STAT_PPS_IDLE) &&
     (me->flags & PKE_FLAG_PENDING_PSS) != 0)
    {
      me->flags &= ~PKE_FLAG_PENDING_PSS;
      PKE_REG_MASK_SET(me, STAT, PSS, 1);
    }

  /* check for stall/halt control bits */
  if(PKE_REG_MASK_GET(me, STAT, PFS) ||
     PKE_REG_MASK_GET(me, STAT, PSS) || /* note special treatment below */
     /* PEW bit not a reason to keep stalling - it's just an indication, re-computed below */
     /* PGW bit not a reason to keep stalling - it's just an indication, re-computed below */
     /* ER0/ER1 not a reason to keep stalling - it's just an indication */
     PKE_REG_MASK_GET(me, STAT, PIS))
    {
      /* (still) stalled */
      PKE_REG_MASK_SET(me, STAT, PPS, PKE_REG_STAT_PPS_STALL);
      /* try again next cycle */
      return;
    }


  /* 3 -- decode PKE instruction */

  /* decoding */
  if(PKE_REG_MASK_GET(me, STAT, PPS) == PKE_REG_STAT_PPS_IDLE)
    PKE_REG_MASK_SET(me, STAT, PPS, PKE_REG_STAT_PPS_DECODE);

  /* Extract relevant bits from PKEcode */
  intr = BIT_MASK_GET(fw, PKE_OPCODE_I_B,   PKE_OPCODE_I_E);
  cmd  = BIT_MASK_GET(fw, PKE_OPCODE_CMD_B, PKE_OPCODE_CMD_E);

  /* handle interrupts */
  if(intr)
    {
      /* are we resuming an interrupt-stalled instruction? */
      if(me->flags & PKE_FLAG_INT_NOLOOP)
	{
	  /* clear loop-prevention flag */
	  me->flags &= ~PKE_FLAG_INT_NOLOOP;

	  /* fall through to decode & execute */
	  /* The pke_code_* functions should not check the MSB in the
             pkecode. */
	}
      else /* new interrupt-flagged instruction */
	{
	  /* set INT flag in STAT register */
	  PKE_REG_MASK_SET(me, STAT, INT, 1);
	  /* set loop-prevention flag */
	  me->flags |= PKE_FLAG_INT_NOLOOP;

	  /* set PIS if stall not masked */
	  if(!PKE_REG_MASK_GET(me, ERR, MII))
	    pke_begin_interrupt_stall(me);

	  /* suspend this instruction unless it's PKEMARK */
	  if(!IS_PKE_CMD(cmd, PKEMARK))
	    {
	      PKE_REG_MASK_SET(me, STAT, PPS, PKE_REG_STAT_PPS_STALL);
	      return;
	    }
	  else
	    {
	      ; /* fall through to decode & execute */
	    }
	}
    }


  /* decode & execute */
  if(IS_PKE_CMD(cmd, PKENOP))
    pke_code_nop(me, fw);
  else if(IS_PKE_CMD(cmd, STCYCL))
    pke_code_stcycl(me, fw);
  else if(me->pke_number == 1 && IS_PKE_CMD(cmd, OFFSET))
    pke_code_offset(me, fw);
  else if(me->pke_number == 1 && IS_PKE_CMD(cmd, BASE))
    pke_code_base(me, fw);
  else if(IS_PKE_CMD(cmd, ITOP))
    pke_code_itop(me, fw);
  else if(IS_PKE_CMD(cmd, STMOD))
    pke_code_stmod(me, fw);
  else if(me->pke_number == 1 && IS_PKE_CMD(cmd, MSKPATH3))
    pke_code_mskpath3(me, fw);
  else if(IS_PKE_CMD(cmd, PKEMARK))
    pke_code_pkemark(me, fw);
  else if(IS_PKE_CMD(cmd, FLUSHE))
    pke_code_flushe(me, fw);
  else if(me->pke_number == 1 && IS_PKE_CMD(cmd, FLUSH))
    pke_code_flush(me, fw);
  else if(me->pke_number == 1 && IS_PKE_CMD(cmd, FLUSHA))
    pke_code_flusha(me, fw);
  else if(IS_PKE_CMD(cmd, PKEMSCAL))
    pke_code_pkemscal(me, fw);
  else if(IS_PKE_CMD(cmd, PKEMSCNT))
    pke_code_pkemscnt(me, fw);
  else if(me->pke_number == 1 && IS_PKE_CMD(cmd, PKEMSCALF))
    pke_code_pkemscalf(me, fw);
  else if(IS_PKE_CMD(cmd, STMASK))
    pke_code_stmask(me, fw);
  else if(IS_PKE_CMD(cmd, STROW))
    pke_code_strow(me, fw);
  else if(IS_PKE_CMD(cmd, STCOL))
    pke_code_stcol(me, fw);
  else if(IS_PKE_CMD(cmd, MPG))
    pke_code_mpg(me, fw);
  else if(IS_PKE_CMD(cmd, DIRECT))
    pke_code_direct(me, fw);
  else if(IS_PKE_CMD(cmd, DIRECTHL))
    pke_code_directhl(me, fw);
  else if(IS_PKE_CMD(cmd, UNPACK))
    pke_code_unpack(me, fw);
  /* ... no other commands ... */
  else
    pke_code_error(me, fw);
}



/* Clear out contents of FIFO; act as if it was empty.  Return PC
   pointing to one-past-last word. */

unsigned_4
pke_fifo_flush(struct pke_fifo* fifo)
{
  /* don't modify any state! */
  return fifo->origin + fifo->next;
}



/* Clear out contents of FIFO; make it really empty. */

void
pke_fifo_reset(struct pke_fifo* fifo)
{
  int i;

  /* clear fifo quadwords */
  for(i=0; i<fifo->next; i++)
    {
      zfree(fifo->quadwords[i]);
      fifo->quadwords[i] = NULL;
    }

  /* reset pointers */
  fifo->origin = 0;
  fifo->next = 0;
}



/* Make space for the next quadword in the FIFO.  Allocate/enlarge
   FIFO pointer block if necessary.  Return a pointer to it. */

struct fifo_quadword*
pke_fifo_fit(struct pke_fifo* fifo)
{
  struct fifo_quadword* fqw;

  /* out of space on quadword pointer array? */
  if(fifo->next == fifo->length) /* also triggered before fifo->quadwords allocated */
    {
      struct fifo_quadword** new_qw;
      unsigned_4 new_length = fifo->length + PKE_FIFO_GROW_SIZE;

      /* allocate new pointer block */
      new_qw = zalloc(new_length * sizeof(struct fifo_quadword*));
      ASSERT(new_qw != NULL);

      /* copy over old contents, if any */
      if(fifo->quadwords != NULL)
	{
	  /* copy over old pointers to beginning of new block */
	  memcpy(new_qw, fifo->quadwords,
		 fifo->length * sizeof(struct fifo_quadword*));
	  
	  /* free old block */
	  zfree(fifo->quadwords);
	}

      /* replace pointers & counts */
      fifo->quadwords = new_qw;
      fifo->length = new_length;
    }

  /* sanity check */
  ASSERT(fifo->quadwords != NULL);

  /* allocate new quadword from heap */
  fqw = zalloc(sizeof(struct fifo_quadword));
  ASSERT(fqw != NULL);

  /* push quadword onto fifo */
  fifo->quadwords[fifo->next] = fqw;
  fifo->next++;
  return fqw;
}



/* Return a pointer to the FIFO quadword with given absolute index, or
   NULL if it is out of range */

struct fifo_quadword*
pke_fifo_access(struct pke_fifo* fifo, unsigned_4 qwnum)
{
  struct fifo_quadword* fqw;

  if((qwnum < fifo->origin) ||  /* before history */
     (qwnum >= fifo->origin + fifo->next)) /* after last available quadword */
    fqw = NULL;
  else
    {
      ASSERT(fifo->quadwords != NULL); /* must be allocated already */
      fqw = fifo->quadwords[qwnum - fifo->origin]; /* pull out pointer from array */
      ASSERT(fqw != NULL); /* must be allocated already */
    }

  return fqw;
}


/* Authorize release of any FIFO entries older than given absolute quadword. */
void
pke_fifo_old(struct pke_fifo* fifo, unsigned_4 qwnum)
{
  /* do we have any too-old FIFO elements? */
  if(fifo->origin + PKE_FIFO_ARCHEOLOGY < qwnum)
    {
      /* count quadwords to forget */
      int horizon = qwnum - (fifo->origin + PKE_FIFO_ARCHEOLOGY); 
      int i;

      /* free quadwords at indices below horizon */
      for(i=0; i < horizon; i++)
	zfree(fifo->quadwords[i]);

      /* move surviving quadword pointers down to beginning of array */
      for(i=horizon; i < fifo->next; i++)
	fifo->quadwords[i-horizon] = fifo->quadwords[i];

      /* clear duplicate pointers */
      for(i=fifo->next - horizon; i < fifo->next; i++)
	fifo->quadwords[i] = NULL;

      /* adjust FIFO pointers */
      fifo->origin = fifo->origin + horizon;
      fifo->next = fifo->next - horizon;
    }
}




/* advance the PC by given number of data words; update STAT/FQC
   field; assume FIFO is filled enough; classify passed-over words;
   write FIFO trace line */

void
pke_pc_advance(struct pke_device* me, int num_words)
{
  int num = num_words;
  struct fifo_quadword* fq = NULL;
  unsigned_4 old_fifo_pc = me->fifo_pc;

  ASSERT(num_words >= 0);

  /* printf("pke %d pc_advance num_words %d\n", me->pke_number, num_words); */

  while(1)
    {
      /* find next quadword, if any */
      fq = pke_fifo_access(& me->fifo, me->fifo_pc);

      /* skip over DMA tag words if present in word 0 or 1 */
      if(fq != NULL && fq->word_class[me->qw_pc] == wc_dma)
	{
	  /* skip by going around loop an extra time */
	  num ++;
	}
      
      /* nothing left to skip / no DMA tag here */
      if(num == 0)
	break;

      /* we are supposed to skip existing words */
      ASSERT(fq != NULL);

      /* one word skipped */
      num --;
      
      /* point to next word */
      me->qw_pc ++;
      if(me->qw_pc == 4)
	{
	  me->qw_pc = 0;
	  me->fifo_pc ++;
	  
	  /* trace the consumption of the FIFO quadword we just skipped over */
	  /* fq still points to it */
	  if(me->fifo_trace_file != NULL)
	    {
	      /* assert complete classification */
	      ASSERT(fq->word_class[3] != wc_unknown);
	      ASSERT(fq->word_class[2] != wc_unknown);
	      ASSERT(fq->word_class[1] != wc_unknown);
	      ASSERT(fq->word_class[0] != wc_unknown);
	      
	      /* print trace record */
	      fprintf(me->fifo_trace_file,
		      "%d 0x%08x_%08x_%08x_%08x 0x%08x %c%c%c%c\n",
		      (me->pke_number == 0 ? 0 : 1),
		      (unsigned) fq->data[3], (unsigned) fq->data[2],
		      (unsigned) fq->data[1], (unsigned) fq->data[0],
		      (unsigned) fq->source_address,
		      fq->word_class[3], fq->word_class[2],
		      fq->word_class[1], fq->word_class[0]);
	    }
	} /* next quadword */
    }

  /* age old entries before PC */
  if(me->fifo_pc != old_fifo_pc) 
    {
      /* we advanced the fifo-pc; authorize disposal of anything
         before previous PKEcode */
      pke_fifo_old(& me->fifo, old_fifo_pc);
    }

  /* clear FQC if FIFO is now empty */ 
  fq = pke_fifo_access(& me->fifo, me->fifo_pc);
  if(fq == NULL)
    {
      PKE_REG_MASK_SET(me, STAT, FQC, 0);
    }
  else /* annote the word where the PC lands as an PKEcode */
    {
      ASSERT(fq->word_class[me->qw_pc] == wc_pkecode || fq->word_class[me->qw_pc] == wc_unknown);
      fq->word_class[me->qw_pc] = wc_pkecode;
    }
}





/* Return pointer to FIFO quadword containing given operand# in FIFO.
   `operand_num' starts at 1.  Return pointer to operand word in last
   argument, if non-NULL.  If FIFO is not full enough, return 0.
   Signal an ER0 indication upon skipping a DMA tag.  */

struct fifo_quadword*
pke_pcrel_fifo(struct pke_device* me, int operand_num, unsigned_4** operand)
{
  int num;
  int new_qw_pc, new_fifo_pc;
  struct fifo_quadword* fq = NULL;

  /* check for validity of last search results in cache */
  if(me->last_fifo_pc == me->fifo_pc &&
     me->last_qw_pc == me->qw_pc &&
     operand_num > me->last_num)
    {
      /* continue search from last stop */
      new_fifo_pc = me->last_new_fifo_pc;
      new_qw_pc = me->last_new_qw_pc;
      num = operand_num - me->last_num;
    }
  else
    {
      /* start search from scratch */
      new_fifo_pc = me->fifo_pc;
      new_qw_pc = me->qw_pc;
      num = operand_num;
    }

  ASSERT(num > 0);

  /* printf("pke %d pcrel_fifo operand_num %d\n", me->pke_number, operand_num); */

  do
    {
      /* one word skipped */
      num --;

      /* point to next word */
      new_qw_pc ++;
      if(new_qw_pc == 4)
	{
	  new_qw_pc = 0;
	  new_fifo_pc ++;
	}

      fq = pke_fifo_access(& me->fifo, new_fifo_pc);

      /* check for FIFO underflow */
      if(fq == NULL)
	break;

      /* skip over DMA tag words if present in word 0 or 1 */
      if(fq->word_class[new_qw_pc] == wc_dma)
	{
	  /* set ER0 */
	  PKE_REG_MASK_SET(me, STAT, ER0, 1);

	  /* mismatch error! */
	  if(! PKE_REG_MASK_GET(me, ERR, ME0))
	    {
	      pke_begin_interrupt_stall(me);
	      /* don't stall just yet -- finish this instruction */
	      /* the PPS_STALL state will be entered by pke_issue() next time */
	    }
	  /* skip by going around loop an extra time */
	  num ++;
	}
    }
  while(num > 0);

  /* return pointer to operand word itself */
  if(fq != NULL)
    {
      *operand = & fq->data[new_qw_pc];

      /* annote the word where the pseudo-PC lands as an PKE operand */
      ASSERT(fq->word_class[new_qw_pc] == wc_pkedata || fq->word_class[new_qw_pc] == wc_unknown);
      fq->word_class[new_qw_pc] = wc_pkedata;

      /* store search results in cache */
      /* keys */
      me->last_fifo_pc = me->fifo_pc;
      me->last_qw_pc = me->qw_pc;
      /* values */
      me->last_num = operand_num;
      me->last_new_fifo_pc = new_fifo_pc;
      me->last_new_qw_pc = new_qw_pc;
    }

  return fq;
}


/* Return pointer to given operand# in FIFO.  `operand_num' starts at 1.
   If FIFO is not full enough, return 0.  Skip over DMA tags, but mark
   them as an error (ER0). */

unsigned_4*
pke_pcrel_operand(struct pke_device* me, int operand_num)
{
  unsigned_4* operand = NULL;
  struct fifo_quadword* fifo_operand;

  fifo_operand = pke_pcrel_fifo(me, operand_num, & operand);

  if(fifo_operand == NULL)
    ASSERT(operand == NULL); /* pke_pcrel_fifo() ought leave it untouched */

  return operand;
}


/* Return a bit-field extract of given operand# in FIFO, and its
   source-addr.  `bit_offset' starts at 0, referring to LSB after PKE
   instruction word.  Width must be >0, <=32.  Assume FIFO is full
   enough.  Skip over DMA tags, but mark them as an error (ER0). */

unsigned_4
pke_pcrel_operand_bits(struct pke_device* me, int bit_offset, int bit_width, unsigned_4* source_addr)
{
  unsigned_4* word = NULL;
  unsigned_4 value;
  struct fifo_quadword* fifo_operand;
  int wordnumber, bitnumber;

  wordnumber = bit_offset/32;
  bitnumber = bit_offset%32;

  /* find operand word with bitfield */
  fifo_operand = pke_pcrel_fifo(me, wordnumber + 1, &word);
  ASSERT(word != NULL);

  /* extract bitfield from word */
  value = BIT_MASK_GET(*word, bitnumber, bitnumber + bit_width - 1);

  /* extract source addr from fifo word */
  *source_addr = fifo_operand->source_address;

  return value;
}



/* check for stall conditions on indicated devices (path* only on
   PKE1), do not change status; return 0 iff no stall */
int
pke_check_stall(struct pke_device* me, enum pke_check_target what)
{
  int any_stall = 0;
  unsigned_4 cop2_stat, gpuif_stat;

  /* read status words */
  ASSERT(sizeof(unsigned_4) == 4);
  PKE_MEM_READ(me, (GIF_REG_STAT),
	       & gpuif_stat,
	       4);
  PKE_MEM_READ(me, (COP2_REG_STAT_ADDR),
	       & cop2_stat,
	       4);

  /* perform checks */
  if(what == chk_vu)
    {
      if(me->pke_number == 0)
	any_stall = BIT_MASK_GET(cop2_stat, COP2_REG_STAT_VBS0_B, COP2_REG_STAT_VBS0_E);
      else /* if(me->pke_number == 1) */
	any_stall = BIT_MASK_GET(cop2_stat, COP2_REG_STAT_VBS1_B, COP2_REG_STAT_VBS1_E);
    }
  else if(what == chk_path1) /* VU -> GPUIF */
    {
      ASSERT(me->pke_number == 1);
      if(BIT_MASK_GET(gpuif_stat, GPUIF_REG_STAT_APATH_B, GPUIF_REG_STAT_APATH_E) == 1)
	any_stall = 1;
    }
  else if(what == chk_path2) /* PKE -> GPUIF */
    {
      ASSERT(me->pke_number == 1);
      if(BIT_MASK_GET(gpuif_stat, GPUIF_REG_STAT_APATH_B, GPUIF_REG_STAT_APATH_E) == 2)
	any_stall = 1;
    }
  else if(what == chk_path3) /* DMA -> GPUIF */
    {
      ASSERT(me->pke_number == 1);
      if(BIT_MASK_GET(gpuif_stat, GPUIF_REG_STAT_APATH_B, GPUIF_REG_STAT_APATH_E) == 3)
	any_stall = 1;
    }
  else
    {
      /* invalid what */
      ASSERT(0);
    }

  /* any stall reasons? */
  return any_stall;
}


/* PKE1 only: flip the DBF bit; recompute TOPS, TOP */
void
pke_flip_dbf(struct pke_device* me)
{
  int newdf;
  /* compute new TOP */
  PKE_REG_MASK_SET(me, TOP, TOP,
		   PKE_REG_MASK_GET(me, TOPS, TOPS));
  /* flip DBF */
  newdf = PKE_REG_MASK_GET(me, DBF, DF) ? 0 : 1;
  PKE_REG_MASK_SET(me, DBF, DF, newdf);
  PKE_REG_MASK_SET(me, STAT, DBF, newdf);
  /* compute new TOPS */
  PKE_REG_MASK_SET(me, TOPS, TOPS,
		   (PKE_REG_MASK_GET(me, BASE, BASE) +
		    newdf * PKE_REG_MASK_GET(me, OFST, OFFSET)));

  /* this is equivalent to last word from okadaa (98-02-25):
     1) TOP=TOPS;
     2) TOPS=BASE + !DBF*OFFSET
     3) DBF=!DBF */
}


/* set the STAT:PIS bit and send an interrupt to the 5900 */
void
pke_begin_interrupt_stall(struct pke_device* me)
{
  /* set PIS */
  PKE_REG_MASK_SET(me, STAT, PIS, 1);
  
  /* XXX: send interrupt to 5900? */
}




/* PKEcode handler functions -- responsible for checking and
   confirming old stall conditions, executing pkecode, updating PC and
   status registers -- may assume being run on correct PKE unit */
   
void 
pke_code_nop(struct pke_device* me, unsigned_4 pkecode)
{
  /* done */
  pke_pc_advance(me, 1);
  PKE_REG_MASK_SET(me, STAT, PPS, PKE_REG_STAT_PPS_IDLE);
}


void
pke_code_stcycl(struct pke_device* me, unsigned_4 pkecode)
{
  int imm = BIT_MASK_GET(pkecode, PKE_OPCODE_IMM_B, PKE_OPCODE_IMM_E);

  /* copy immediate value into CYCLE reg */
  PKE_REG_MASK_SET(me, CYCLE, WL, BIT_MASK_GET(imm, 8, 15));
  PKE_REG_MASK_SET(me, CYCLE, CL, BIT_MASK_GET(imm, 0, 7));
  /* done */
  pke_pc_advance(me, 1);
  PKE_REG_MASK_SET(me, STAT, PPS, PKE_REG_STAT_PPS_IDLE);
}


void
pke_code_offset(struct pke_device* me, unsigned_4 pkecode)
{
  int imm = BIT_MASK_GET(pkecode, PKE_OPCODE_IMM_B, PKE_OPCODE_IMM_E);

  /* copy 10 bits to OFFSET field */
  PKE_REG_MASK_SET(me, OFST, OFFSET, BIT_MASK_GET(imm, 0, 9));
  /* clear DBF bit */
  PKE_REG_MASK_SET(me, DBF, DF, 0);
  /* clear other DBF bit */
  PKE_REG_MASK_SET(me, STAT, DBF, 0);
  /* set TOPS = BASE */
  PKE_REG_MASK_SET(me, TOPS, TOPS, PKE_REG_MASK_GET(me, BASE, BASE));
  /* done */
  pke_pc_advance(me, 1);
  PKE_REG_MASK_SET(me, STAT, PPS, PKE_REG_STAT_PPS_IDLE);
}


void
pke_code_base(struct pke_device* me, unsigned_4 pkecode)
{
  int imm = BIT_MASK_GET(pkecode, PKE_OPCODE_IMM_B, PKE_OPCODE_IMM_E);

  /* copy 10 bits to BASE field */
  PKE_REG_MASK_SET(me, BASE, BASE, BIT_MASK_GET(imm, 0, 9));
  /* done */
  pke_pc_advance(me, 1);
  PKE_REG_MASK_SET(me, STAT, PPS, PKE_REG_STAT_PPS_IDLE);
}


void
pke_code_itop(struct pke_device* me, unsigned_4 pkecode)
{
  int imm = BIT_MASK_GET(pkecode, PKE_OPCODE_IMM_B, PKE_OPCODE_IMM_E);

  /* copy 10 bits to ITOPS field */
  PKE_REG_MASK_SET(me, ITOPS, ITOPS, BIT_MASK_GET(imm, 0, 9));
  /* done */
  pke_pc_advance(me, 1);
  PKE_REG_MASK_SET(me, STAT, PPS, PKE_REG_STAT_PPS_IDLE);
}


void
pke_code_stmod(struct pke_device* me, unsigned_4 pkecode)
{
  int imm = BIT_MASK_GET(pkecode, PKE_OPCODE_IMM_B, PKE_OPCODE_IMM_E);

  /* copy 2 bits to MODE register */
  PKE_REG_MASK_SET(me, MODE, MDE, BIT_MASK_GET(imm, 0, 2));
  /* done */
  pke_pc_advance(me, 1);
  PKE_REG_MASK_SET(me, STAT, PPS, PKE_REG_STAT_PPS_IDLE);
}


void
pke_code_mskpath3(struct pke_device* me, unsigned_4 pkecode)
{
  int imm = BIT_MASK_GET(pkecode, PKE_OPCODE_IMM_B, PKE_OPCODE_IMM_E);
  unsigned_4 gif_mode;

  /* set appropriate bit */
  if(BIT_MASK_GET(imm, PKE_REG_MSKPATH3_B, PKE_REG_MSKPATH3_E) != 0)
    gif_mode = GIF_REG_STAT_M3P;
  else
    gif_mode = 0;

  /* write register to "read-only" register; gpuif code will look at M3P bit only */
  PKE_MEM_WRITE(me, GIF_REG_VIF_M3P, & gif_mode, 4);

  /* done */
  pke_pc_advance(me, 1);
  PKE_REG_MASK_SET(me, STAT, PPS, PKE_REG_STAT_PPS_IDLE);
}


void
pke_code_pkemark(struct pke_device* me, unsigned_4 pkecode)
{
  int imm = BIT_MASK_GET(pkecode, PKE_OPCODE_IMM_B, PKE_OPCODE_IMM_E);
  /* copy 16 bits to MARK register */
  PKE_REG_MASK_SET(me, MARK, MARK, BIT_MASK_GET(imm, 0, 15));
  /* set MRK bit in STAT register - CPU2 v2.1 docs incorrect */
  PKE_REG_MASK_SET(me, STAT, MRK, 1);
  /* done */
  pke_pc_advance(me, 1);
  PKE_REG_MASK_SET(me, STAT, PPS, PKE_REG_STAT_PPS_IDLE);
}


void
pke_code_flushe(struct pke_device* me, unsigned_4 pkecode)
{
  /* compute next PEW bit */
  if(pke_check_stall(me, chk_vu))
    {
      /* VU busy */
      PKE_REG_MASK_SET(me, STAT, PEW, 1);
      PKE_REG_MASK_SET(me, STAT, PPS, PKE_REG_STAT_PPS_STALL);
      /* try again next cycle */
    }
  else
    {
      /* VU idle */
      PKE_REG_MASK_SET(me, STAT, PEW, 0);
      PKE_REG_MASK_SET(me, STAT, PPS, PKE_REG_STAT_PPS_IDLE);
      pke_pc_advance(me, 1);
    }
}


void
pke_code_flush(struct pke_device* me, unsigned_4 pkecode)
{
  int something_busy = 0;

  /* compute next PEW, PGW bits */
  if(pke_check_stall(me, chk_vu))
    {
      something_busy = 1;
      PKE_REG_MASK_SET(me, STAT, PEW, 1);
    }
  else
    PKE_REG_MASK_SET(me, STAT, PEW, 0);


  if(pke_check_stall(me, chk_path1) ||
     pke_check_stall(me, chk_path2))
    {
      something_busy = 1;
      PKE_REG_MASK_SET(me, STAT, PGW, 1);
    }
  else
    PKE_REG_MASK_SET(me, STAT, PGW, 0);

  /* go or no go */
  if(something_busy)
    {
      PKE_REG_MASK_SET(me, STAT, PPS, PKE_REG_STAT_PPS_WAIT);
      /* try again next cycle */
    }
  else
    {
      /* all idle */
      PKE_REG_MASK_SET(me, STAT, PPS, PKE_REG_STAT_PPS_IDLE);
      pke_pc_advance(me, 1);
    }
}


void
pke_code_flusha(struct pke_device* me, unsigned_4 pkecode)
{
  int something_busy = 0;

  /* compute next PEW, PGW bits */
  if(pke_check_stall(me, chk_vu))
    {
      something_busy = 1;
      PKE_REG_MASK_SET(me, STAT, PEW, 1);
    }
  else
    PKE_REG_MASK_SET(me, STAT, PEW, 0);


  if(pke_check_stall(me, chk_path1) ||
     pke_check_stall(me, chk_path2) ||
     pke_check_stall(me, chk_path3))
    {
      something_busy = 1;
      PKE_REG_MASK_SET(me, STAT, PGW, 1);
    }
  else
    PKE_REG_MASK_SET(me, STAT, PGW, 0);

  if(something_busy)
    {
      PKE_REG_MASK_SET(me, STAT, PPS, PKE_REG_STAT_PPS_WAIT);
      /* try again next cycle */
    }
  else
    {
      /* all idle */
      PKE_REG_MASK_SET(me, STAT, PPS, PKE_REG_STAT_PPS_IDLE);
      pke_pc_advance(me, 1);
    }
}


void
pke_code_pkemscal(struct pke_device* me, unsigned_4 pkecode)
{
  /* compute next PEW bit */
  if(pke_check_stall(me, chk_vu))
    {
      /* VU busy */
      PKE_REG_MASK_SET(me, STAT, PEW, 1);
      PKE_REG_MASK_SET(me, STAT, PPS, PKE_REG_STAT_PPS_STALL);
      /* try again next cycle */
    }
  else
    {
      unsigned_4 vu_pc;
      int imm = BIT_MASK_GET(pkecode, PKE_OPCODE_IMM_B, PKE_OPCODE_IMM_E);

      /* VU idle */
      PKE_REG_MASK_SET(me, STAT, PEW, 0);

      /* flip DBF on PKE1 */
      if(me->pke_number == 1)
	pke_flip_dbf(me);

      /* compute new PC for VU (host byte-order) */
      vu_pc = BIT_MASK_GET(imm, 0, 15);
      vu_pc = T2H_4(vu_pc);

      /* write new PC; callback function gets VU running */
      ASSERT(sizeof(unsigned_4) == 4);
      PKE_MEM_WRITE(me, (me->pke_number == 0 ? VU0_CIA : VU1_CIA),
		    & vu_pc,
		    4);

      /* copy ITOPS field to ITOP */
      PKE_REG_MASK_SET(me, ITOP, ITOP, PKE_REG_MASK_GET(me, ITOPS, ITOPS));

      /* done */
      PKE_REG_MASK_SET(me, STAT, PPS, PKE_REG_STAT_PPS_IDLE);
      pke_pc_advance(me, 1);
    }
}



void
pke_code_pkemscnt(struct pke_device* me, unsigned_4 pkecode)
{
  /* compute next PEW bit */
  if(pke_check_stall(me, chk_vu))
    {
      /* VU busy */
      PKE_REG_MASK_SET(me, STAT, PEW, 1);
      PKE_REG_MASK_SET(me, STAT, PPS, PKE_REG_STAT_PPS_STALL);
      /* try again next cycle */
    }
  else
    {
      unsigned_4 vu_pc;

      /* VU idle */
      PKE_REG_MASK_SET(me, STAT, PEW, 0);

      /* flip DBF on PKE1 */
      if(me->pke_number == 1)
	pke_flip_dbf(me);

      /* read old PC */
      ASSERT(sizeof(unsigned_4) == 4);
      PKE_MEM_READ(me, (me->pke_number == 0 ? VU0_CIA : VU1_CIA),
		   & vu_pc,
		   4);

      /* rewrite new PC; callback function gets VU running */
      ASSERT(sizeof(unsigned_4) == 4);
      PKE_MEM_WRITE(me, (me->pke_number == 0 ? VU0_CIA : VU1_CIA),
		    & vu_pc,
		    4);

      /* copy ITOPS field to ITOP */
      PKE_REG_MASK_SET(me, ITOP, ITOP, PKE_REG_MASK_GET(me, ITOPS, ITOPS));

      /* done */
      PKE_REG_MASK_SET(me, STAT, PPS, PKE_REG_STAT_PPS_IDLE);
      pke_pc_advance(me, 1);
    }
}


void
pke_code_pkemscalf(struct pke_device* me, unsigned_4 pkecode)
{
  int something_busy = 0;

  /* compute next PEW, PGW bits */
  if(pke_check_stall(me, chk_vu))
    {
      something_busy = 1;
      PKE_REG_MASK_SET(me, STAT, PEW, 1);
    }
  else
    PKE_REG_MASK_SET(me, STAT, PEW, 0);


  if(pke_check_stall(me, chk_path1) ||
     pke_check_stall(me, chk_path2) ||
     pke_check_stall(me, chk_path3))
    {
      something_busy = 1;
      PKE_REG_MASK_SET(me, STAT, PGW, 1);
    }
  else
    PKE_REG_MASK_SET(me, STAT, PGW, 0);

  /* go or no go */
  if(something_busy)
    {
      PKE_REG_MASK_SET(me, STAT, PPS, PKE_REG_STAT_PPS_WAIT);
      /* try again next cycle */
    }
  else
    {
      unsigned_4 vu_pc;
      int imm = BIT_MASK_GET(pkecode, PKE_OPCODE_IMM_B, PKE_OPCODE_IMM_E);
      
      /* flip DBF on PKE1 */
      if(me->pke_number == 1)
	pke_flip_dbf(me);

      /* compute new PC for VU (host byte-order) */
      vu_pc = BIT_MASK_GET(imm, 0, 15);
      vu_pc = T2H_4(vu_pc);

      /* rewrite new PC; callback function gets VU running */
      ASSERT(sizeof(unsigned_4) == 4);
      PKE_MEM_WRITE(me, (me->pke_number == 0 ? VU0_CIA : VU1_CIA),
		    & vu_pc,
		    4);

      /* copy ITOPS field to ITOP */
      PKE_REG_MASK_SET(me, ITOP, ITOP, PKE_REG_MASK_GET(me, ITOPS, ITOPS));

      /* done */
      PKE_REG_MASK_SET(me, STAT, PPS, PKE_REG_STAT_PPS_IDLE);
      pke_pc_advance(me, 1);
    }
}


void
pke_code_stmask(struct pke_device* me, unsigned_4 pkecode)
{
  unsigned_4* mask;

  /* check that FIFO has one more word for STMASK operand */
  mask = pke_pcrel_operand(me, 1);
  if(mask != NULL)
    {
      /* "transferring" operand */
      PKE_REG_MASK_SET(me, STAT, PPS, PKE_REG_STAT_PPS_XFER);

      /* set NUM */
      PKE_REG_MASK_SET(me, NUM, NUM, 1);

      /* fill the register */
      PKE_REG_MASK_SET(me, MASK, MASK, *mask);

      /* set NUM */
      PKE_REG_MASK_SET(me, NUM, NUM, 0);

      /* done */
      PKE_REG_MASK_SET(me, STAT, PPS, PKE_REG_STAT_PPS_IDLE);
      pke_pc_advance(me, 2);
    }
  else
    {
      /* need to wait for another word */
      PKE_REG_MASK_SET(me, STAT, PPS, PKE_REG_STAT_PPS_WAIT);
      /* try again next cycle */
    }
}


void
pke_code_strow(struct pke_device* me, unsigned_4 pkecode)
{
  /* check that FIFO has four more words for STROW operand */
  unsigned_4* last_op;
  
  last_op = pke_pcrel_operand(me, 4);
  if(last_op != NULL)
    {
      /* "transferring" operand */
      PKE_REG_MASK_SET(me, STAT, PPS, PKE_REG_STAT_PPS_XFER);
      
      /* set NUM */
      PKE_REG_MASK_SET(me, NUM, NUM, 1);

      /* copy ROW registers: must all exist if 4th operand exists */
      me->regs[PKE_REG_R0][0] = * pke_pcrel_operand(me, 1);
      me->regs[PKE_REG_R1][0] = * pke_pcrel_operand(me, 2);
      me->regs[PKE_REG_R2][0] = * pke_pcrel_operand(me, 3);
      me->regs[PKE_REG_R3][0] = * pke_pcrel_operand(me, 4);
      
      /* set NUM */
      PKE_REG_MASK_SET(me, NUM, NUM, 0);

      /* done */
      PKE_REG_MASK_SET(me, STAT, PPS, PKE_REG_STAT_PPS_IDLE);
      pke_pc_advance(me, 5);
    }
  else
    {
      /* need to wait for another word */
      PKE_REG_MASK_SET(me, STAT, PPS, PKE_REG_STAT_PPS_WAIT);
      /* try again next cycle */
    }
}


void
pke_code_stcol(struct pke_device* me, unsigned_4 pkecode)
{
  /* check that FIFO has four more words for STCOL operand */
  unsigned_4* last_op;
  
  last_op = pke_pcrel_operand(me, 4);
  if(last_op != NULL)
    {
      /* "transferring" operand */
      PKE_REG_MASK_SET(me, STAT, PPS, PKE_REG_STAT_PPS_XFER);
      
      /* set NUM */
      PKE_REG_MASK_SET(me, NUM, NUM, 1);

      /* copy COL registers: must all exist if 4th operand exists */
      me->regs[PKE_REG_C0][0] = * pke_pcrel_operand(me, 1);
      me->regs[PKE_REG_C1][0] = * pke_pcrel_operand(me, 2);
      me->regs[PKE_REG_C2][0] = * pke_pcrel_operand(me, 3);
      me->regs[PKE_REG_C3][0] = * pke_pcrel_operand(me, 4);
      
      /* set NUM */
      PKE_REG_MASK_SET(me, NUM, NUM, 0);

      /* done */
      PKE_REG_MASK_SET(me, STAT, PPS, PKE_REG_STAT_PPS_IDLE);
      pke_pc_advance(me, 5);
    }
  else
    {
      /* need to wait for another word */
      PKE_REG_MASK_SET(me, STAT, PPS, PKE_REG_STAT_PPS_WAIT);
      /* try again next cycle */
    }
}


void
pke_code_mpg(struct pke_device* me, unsigned_4 pkecode)
{
  unsigned_4* last_mpg_word;
  int num = BIT_MASK_GET(pkecode, PKE_OPCODE_NUM_B, PKE_OPCODE_NUM_E);
  int imm = BIT_MASK_GET(pkecode, PKE_OPCODE_IMM_B, PKE_OPCODE_IMM_E);

  /* assert 64-bit alignment of MPG operand */
  if(me->qw_pc != 3 && me->qw_pc != 1)
    return pke_code_error(me, pkecode);

  /* map zero to max+1 */
  if(num==0) num=0x100;
  
  /* check that FIFO has a few more words for MPG operand */
  last_mpg_word = pke_pcrel_operand(me, num*2); /* num: number of 64-bit words */
  if(last_mpg_word != NULL)
    {
      /* perform implied FLUSHE */
      if(pke_check_stall(me, chk_vu))
	{
	  /* VU busy */
	  PKE_REG_MASK_SET(me, STAT, PPS, PKE_REG_STAT_PPS_STALL);
	  /* retry this instruction next clock */
	}
      else
	{
	  /* VU idle */
	  int i;
	  
	  /* "transferring" operand */
	  PKE_REG_MASK_SET(me, STAT, PPS, PKE_REG_STAT_PPS_XFER);
	  
	  /* set NUM */
	  PKE_REG_MASK_SET(me, NUM, NUM, num);

	  /* transfer VU instructions, one word-pair per iteration */
	  for(i=0; i<num; i++)
	    {
	      address_word vu_addr_base, vu_addr;
	      address_word vutrack_addr_base, vutrack_addr;
	      address_word vu_addr_max_size;
	      unsigned_4 vu_lower_opcode, vu_upper_opcode;
	      unsigned_4* operand;
	      struct fifo_quadword* fq;
	      int next_num;

	      /* decrement NUM */
	      next_num = PKE_REG_MASK_GET(me, NUM, NUM) - 1;
	      PKE_REG_MASK_SET(me, NUM, NUM, next_num);
	      
	      /* imm: in 64-bit units for MPG instruction */
	      /* VU*_MEM0 : instruction memory */
	      vu_addr_base = (me->pke_number == 0) ?
		VU0_MEM0_WINDOW_START : VU1_MEM0_WINDOW_START;
	      vu_addr_max_size = (me->pke_number == 0) ?
		VU0_MEM0_SIZE : VU1_MEM0_SIZE;
	      vutrack_addr_base = (me->pke_number == 0) ?
		VU0_MEM0_SRCADDR_START : VU1_MEM0_SRCADDR_START;

	      /* compute VU address for this word-pair */
	      vu_addr = vu_addr_base + (imm + i) * 8;
	      /* check for vu_addr overflow */
	      while(vu_addr >= vu_addr_base + vu_addr_max_size)
		vu_addr -= vu_addr_max_size;

	      /* compute VU tracking address */
	      vutrack_addr = vutrack_addr_base + ((signed_8)vu_addr - (signed_8)vu_addr_base) / 2;

	      /* Fetch operand words; assume they are already little-endian for VU imem */
	      fq = pke_pcrel_fifo(me, i*2 + 1, & operand);
	      vu_lower_opcode = *operand;
	      vu_upper_opcode = *pke_pcrel_operand(me, i*2 + 2);
	      
	      /* write data into VU memory */
	      /* lower (scalar) opcode comes in first word ; macro performs H2T! */
	      PKE_MEM_WRITE(me, vu_addr,
			    & vu_lower_opcode,
			    4);
	      /* upper (vector) opcode comes in second word ; H2T */
	      ASSERT(sizeof(unsigned_4) == 4);
	      PKE_MEM_WRITE(me, vu_addr + 4,
			    & vu_upper_opcode,
			    4);
	      
	      /* write tracking address in target byte-order */
	      ASSERT(sizeof(unsigned_4) == 4);
	      PKE_MEM_WRITE(me, vutrack_addr,
			    & fq->source_address,
			    4);
	    } /* VU xfer loop */

	  /* check NUM */
	  ASSERT(PKE_REG_MASK_GET(me, NUM, NUM) == 0);
	  
	  /* done */
	  PKE_REG_MASK_SET(me, STAT, PPS, PKE_REG_STAT_PPS_IDLE);
	  pke_pc_advance(me, 1 + num*2);
	}
    } /* if FIFO full enough */
  else
    {
      /* need to wait for another word */
      PKE_REG_MASK_SET(me, STAT, PPS, PKE_REG_STAT_PPS_WAIT);
      /* retry this instruction next clock */
    }
}


void
pke_code_direct(struct pke_device* me, unsigned_4 pkecode)
{
  /* check that FIFO has a few more words for DIRECT operand */
  unsigned_4* last_direct_word;
  int imm = BIT_MASK_GET(pkecode, PKE_OPCODE_IMM_B, PKE_OPCODE_IMM_E);
  
  /* assert 128-bit alignment of DIRECT operand */
  if(me->qw_pc != 3)
    return pke_code_error(me, pkecode);

  /* map zero to max+1 */
  if(imm==0) imm=0x10000;
  
  last_direct_word = pke_pcrel_operand(me, imm*4); /* imm: number of 128-bit words */
  if(last_direct_word != NULL)
    {
      /* VU idle */
      int i;
      unsigned_16 fifo_data;
      
      /* "transferring" operand */
      PKE_REG_MASK_SET(me, STAT, PPS, PKE_REG_STAT_PPS_XFER);
      
      /* transfer GPUIF quadwords, one word per iteration */
      for(i=0; i<imm*4; i++)
	{
	  unsigned_4* operand = pke_pcrel_operand(me, 1+i);
	  
	  /* collect word into quadword */
	  *A4_16(&fifo_data, 3 - (i % 4)) = *operand;

	  /* write to GPUIF FIFO only with full quadword */
	  if(i % 4 == 3)
	    {
	      ASSERT(sizeof(fifo_data) == 16);
	      PKE_MEM_WRITE(me, GIF_PATH2_FIFO_ADDR,
			    & fifo_data,
			    16);
	    } /* write collected quadword */
	} /* GPUIF xfer loop */
      
      /* done */
      PKE_REG_MASK_SET(me, STAT, PPS, PKE_REG_STAT_PPS_IDLE);
      pke_pc_advance(me, 1 + imm*4);
    } /* if FIFO full enough */
  else
    {
      /* need to wait for another word */
      PKE_REG_MASK_SET(me, STAT, PPS, PKE_REG_STAT_PPS_WAIT);
      /* retry this instruction next clock */
    }
}


void
pke_code_directhl(struct pke_device* me, unsigned_4 pkecode)
{
  /* treat the same as DIRECTH */
  pke_code_direct(me, pkecode);
}


void
pke_code_unpack(struct pke_device* me, unsigned_4 pkecode)
{
  int imm = BIT_MASK_GET(pkecode, PKE_OPCODE_IMM_B, PKE_OPCODE_IMM_E);
  int cmd = BIT_MASK_GET(pkecode, PKE_OPCODE_CMD_B, PKE_OPCODE_CMD_E);
  int num = BIT_MASK_GET(pkecode, PKE_OPCODE_NUM_B, PKE_OPCODE_NUM_E);
  int nummx = (num == 0) ? 0x0100 : num;
  short vn = BIT_MASK_GET(cmd, 2, 3); /* unpack shape controls */
  short vl = BIT_MASK_GET(cmd, 0, 1);
  int m = BIT_MASK_GET(cmd, 4, 4);
  short cl = PKE_REG_MASK_GET(me, CYCLE, CL); /* cycle controls */
  short wl = PKE_REG_MASK_GET(me, CYCLE, WL);
  short addrwl = (wl == 0) ? 0x0100 : wl;
  int r = BIT_MASK_GET(imm, 15, 15); /* indicator bits in imm value */
  int usn = BIT_MASK_GET(imm, 14, 14);

  int n, num_operands;
  unsigned_4* last_operand_word = NULL;

  /* catch all illegal UNPACK variants */
  if(vl == 3 && vn < 3)
    {
      pke_code_error(me, pkecode);
      return;
    }
  
  /* compute PKEcode length, as given in CPU2 spec, v2.1 pg. 11 */
  if(cl >= addrwl)
    n = num;
  else
    n = cl * (nummx / addrwl) + PKE_LIMIT(nummx % addrwl, cl);
  num_operands = (31 + (32 >> vl) * (vn+1) * n)/32; /* round up to next word */
  
  /* confirm that FIFO has enough words in it */
  if(num_operands > 0)
    last_operand_word = pke_pcrel_operand(me, num_operands);
  if(last_operand_word != NULL || num_operands == 0)
    {
      address_word vu_addr_base, vutrack_addr_base;
      address_word vu_addr_max_size;
      int vector_num_out, vector_num_in;
      
      /* "transferring" operand */
      PKE_REG_MASK_SET(me, STAT, PPS, PKE_REG_STAT_PPS_XFER);
      
      /* don't check whether VU is idle */

      /* compute VU address base */
      if(me->pke_number == 0)
	{
	  vu_addr_base = VU0_MEM1_WINDOW_START;
	  vu_addr_max_size = VU0_MEM1_SIZE;
	  vutrack_addr_base = VU0_MEM1_SRCADDR_START;
	  r = 0;
	}
      else
	{
	  vu_addr_base = VU1_MEM1_WINDOW_START;
	  vu_addr_max_size = VU1_MEM1_SIZE;
	  vutrack_addr_base = VU1_MEM1_SRCADDR_START;
	}

      /* set NUM */
      PKE_REG_MASK_SET(me, NUM, NUM, nummx);

      /* transfer given number of vectors */
      vector_num_out = 0;  /* output vector number being processed */
      vector_num_in = 0;  /* argument vector number being processed */
      do
	{
	  quadword vu_old_data;
	  quadword vu_new_data;
	  quadword unpacked_data;
	  address_word vu_addr;
	  address_word vutrack_addr;
	  unsigned_4 source_addr = 0;
	  int i;
	  int next_num;

	  /* decrement NUM */
	  next_num = PKE_REG_MASK_GET(me, NUM, NUM) - 1;
	  PKE_REG_MASK_SET(me, NUM, NUM, next_num);

	  /* compute VU destination address, as bytes in R5900 memory */
	  if(cl >= wl)
	    {
	      /* map zero to max+1 */
	      vu_addr = vu_addr_base + 16 * (BIT_MASK_GET(imm, 0, 9) +
					     (vector_num_out / addrwl) * cl +
					     (vector_num_out % addrwl));
	    }
	  else
	    vu_addr = vu_addr_base + 16 * (BIT_MASK_GET(imm, 0, 9) +
					   vector_num_out);
	  
	  /* handle "R" double-buffering bit */
	  if(r)
	    vu_addr += 16 * PKE_REG_MASK_GET(me, TOPS, TOPS);

	  /* check for vu_addr overflow */
	  while(vu_addr >= vu_addr_base + vu_addr_max_size)
	    vu_addr -= vu_addr_max_size;

	  /* compute address of tracking table entry */
	  vutrack_addr = vutrack_addr_base + ((signed_8)vu_addr - (signed_8)vu_addr_base) / 4;

	  /* read old VU data word at address; reverse words if needed */
	  {
	    unsigned_16 vu_old_badwords;
	    ASSERT(sizeof(vu_old_badwords) == 16);
	    PKE_MEM_READ(me, vu_addr,
			 &vu_old_badwords, 16);
	    vu_old_data[0] = * A4_16(& vu_old_badwords, 3);
	    vu_old_data[1] = * A4_16(& vu_old_badwords, 2);
	    vu_old_data[2] = * A4_16(& vu_old_badwords, 1);
	    vu_old_data[3] = * A4_16(& vu_old_badwords, 0);
	  }

	  /* For cyclic unpack, next operand quadword may come from instruction stream
	     or be zero. */
	  if((cl < addrwl) &&
	     (vector_num_out % addrwl) >= cl)
	    {
	      /* clear operand - used only in a "indeterminate" state */
	      for(i = 0; i < 4; i++)
		unpacked_data[i] = 0;
	    }
	  else
	    {
	      /* compute packed vector dimensions */
	      int vectorbits = 0, unitbits = 0;

	      if(vl < 3) /* PKE_UNPACK_*_{32,16,8} */
		{
		  unitbits = (32 >> vl);
		  vectorbits = unitbits * (vn+1);
		}
	      else if(vl == 3 && vn == 3) /* PKE_UNPACK_V4_5 */
		{
		  unitbits = 5;
		  vectorbits = 16;
		}
	      else /* illegal unpack variant */
		{
		  /* should have been caught at top of function */
		  ASSERT(0);
		}
	      
	      /* loop over columns */
	      for(i=0; i<=vn; i++)
		{
		  unsigned_4 operand;

		  /* offset in bits in current operand word */
		  int bitoffset =
		    (vector_num_in * vectorbits) + (i * unitbits); /* # of bits from PKEcode */

		  /* last unit of V4_5 is only one bit wide */
		  if(vl == 3 && vn == 3 && i == 3) /* PKE_UNPACK_V4_5 */
		    unitbits = 1;

		  /* confirm we're not reading more than we said we needed */
		  if(vector_num_in * vectorbits >= num_operands * 32)
		    {
		      /* this condition may be triggered by illegal
                         PKEcode / CYCLE combinations. */
		      pke_code_error(me, pkecode);
		      /* XXX: this case needs to be better understood,
                         and detected at a better time. */
		      return;
		    }

		  /* fetch bitfield operand */
		  operand = pke_pcrel_operand_bits(me, bitoffset, unitbits, & source_addr);

		  /* selectively sign-extend; not for V4_5 1-bit value */
		  if(usn || unitbits == 1)
		    unpacked_data[i] = operand;
		  else
		    unpacked_data[i] = SEXT32(operand, unitbits-1);
		}

	      /* set remaining top words in vector */
	      for(i=vn+1; i<4; i++)
		{
		  if(vn == 0) /* S_{32,16,8}: copy lowest element */
		    unpacked_data[i] = unpacked_data[0];
		  else
		    unpacked_data[i] = 0;
		}

	      /* consumed a vector from the PKE instruction stream */
	      vector_num_in ++;
	    } /* unpack word from instruction operand */
	  
	  /* process STMOD register for accumulation operations */
	  switch(PKE_REG_MASK_GET(me, MODE, MDE))
	    {
	    case PKE_MODE_ADDROW: /* add row registers to output data */
	    case PKE_MODE_ACCROW: /* same .. later conditionally accumulate */
	      for(i=0; i<4; i++)
		/* exploit R0..R3 contiguity */
		unpacked_data[i] += me->regs[PKE_REG_R0 + i][0];
	      break;

	    case PKE_MODE_INPUT: /* pass data through */
	    default: /* specified as undefined */
	      ;
	    }

	  /* compute replacement word */
	  if(m) /* use mask register? */
	    {
	      /* compute index into mask register for this word */
	      int mask_index = PKE_LIMIT(vector_num_out % addrwl, 3);
	      
	      for(i=0; i<4; i++) /* loop over columns */
		{
		  int mask_op = PKE_MASKREG_GET(me, mask_index, i);
		  unsigned_4* masked_value = NULL;
		  
		  switch(mask_op)
		    {
		    case PKE_MASKREG_INPUT: 
		      masked_value = & unpacked_data[i];

		      /* conditionally accumulate */
		      if(PKE_REG_MASK_GET(me, MODE, MDE) == PKE_MODE_ACCROW)
			me->regs[PKE_REG_R0 + i][0] = unpacked_data[i];

		      break;
		      
		    case PKE_MASKREG_ROW: /* exploit R0..R3 contiguity */
		      masked_value = & me->regs[PKE_REG_R0 + i][0];
		      break;
		      
		    case PKE_MASKREG_COLUMN: /* exploit C0..C3 contiguity */
		      masked_value = & me->regs[PKE_REG_C0 + mask_index][0];
		      break;
		      
		    case PKE_MASKREG_NOTHING:
		      /* "write inhibit" by re-copying old data */
		      masked_value = & vu_old_data[i];
		      break;
		      
		    default:
		      ASSERT(0);
		      /* no other cases possible */
		    }
		  
		  /* copy masked value for column */
		  vu_new_data[i] = *masked_value;
		} /* loop over columns */
	    } /* mask */
	  else
	    {
	      /* no mask - just copy over entire unpacked quadword */
	      memcpy(vu_new_data, unpacked_data, sizeof(unpacked_data));

	      /* conditionally store accumulated row results */
	      if(PKE_REG_MASK_GET(me, MODE, MDE) == PKE_MODE_ACCROW)
		for(i=0; i<4; i++)
		  me->regs[PKE_REG_R0 + i][0] = unpacked_data[i];
	    }

	  /* write new VU data word at address; reverse words if needed */
	  {
	    unsigned_16 vu_new_badwords;
	    * A4_16(& vu_new_badwords, 3) = vu_new_data[0];
	    * A4_16(& vu_new_badwords, 2) = vu_new_data[1];
	    * A4_16(& vu_new_badwords, 1) = vu_new_data[2];
	    * A4_16(& vu_new_badwords, 0) = vu_new_data[3];
	    ASSERT(sizeof(vu_new_badwords) == 16);
	    PKE_MEM_WRITE(me, vu_addr,
			 &vu_new_badwords, 16);
	  }

	  /* write tracking address */
	  ASSERT(sizeof(unsigned_4) == 4);
	  PKE_MEM_WRITE(me, vutrack_addr,
			& source_addr,
			4);

	  /* next vector please */
	  vector_num_out ++;
	} /* vector transfer loop */
      while(PKE_REG_MASK_GET(me, NUM, NUM) > 0);

      /* confirm we've written as many vectors as told */
      ASSERT(nummx == vector_num_out);

      /* done */
      PKE_REG_MASK_SET(me, STAT, PPS, PKE_REG_STAT_PPS_IDLE);
      pke_pc_advance(me, 1 + num_operands);
    } /* PKE FIFO full enough */
  else
    {
      /* need to wait for another word */
      PKE_REG_MASK_SET(me, STAT, PPS, PKE_REG_STAT_PPS_WAIT);
      /* retry this instruction next clock */
    }
}


void
pke_code_error(struct pke_device* me, unsigned_4 pkecode)
{
  /* set ER1 flag in STAT register */
  PKE_REG_MASK_SET(me, STAT, ER1, 1);

  if(! PKE_REG_MASK_GET(me, ERR, ME1))
    {
      pke_begin_interrupt_stall(me);
      PKE_REG_MASK_SET(me, STAT, PPS, PKE_REG_STAT_PPS_STALL);
    }
  else
    {
      PKE_REG_MASK_SET(me, STAT, PPS, PKE_REG_STAT_PPS_IDLE);
    }

  /* advance over faulty word */
  pke_pc_advance(me, 1);
}