summaryrefslogtreecommitdiff
path: root/linux/src/drivers/scsi/AM53C974.c
blob: 5178ccf7bdc5d0f9d35af98d5173118460cc136f (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
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
#include <linux/module.h>

#include <linux/config.h>
#include <linux/delay.h>
#include <linux/signal.h>
#include <linux/sched.h>
#include <linux/errno.h>
#include <linux/bios32.h>
#include <linux/pci.h>
#include <linux/string.h>
#include <linux/blk.h>

#include <asm/io.h>
#include <asm/system.h>

#include "scsi.h"
#include "hosts.h"
#include "AM53C974.h"
#include "constants.h"
#include "sd.h"

/* AM53/79C974 (PCscsi) driver release 0.5
 *
 * The architecture and much of the code of this device
 * driver was originally developed by Drew Eckhardt for
 * the NCR5380. The following copyrights apply:
 *  For the architecture and all pieces of code which can also be found 
 *    in the NCR5380 device driver:
 *   Copyright 1993, Drew Eckhardt
 *	Visionary Computing 
 *	(Unix and Linux consulting and custom programming)
 * 	drew@colorado.edu
 *	+1 (303) 666-5836
 *
 *  The AM53C974_nobios_detect code was originally developed by
 *   Robin Cutshaw (robin@xfree86.org) and is used here in a 
 *   slightly modified form.
 *
 *  For the remaining code:
 *    Copyright 1994, D. Frieauff
 *    EMail: fri@rsx42sun0.dofn.de
 *    Phone: x49-7545-8-2256 , x49-7541-42305
 */

#ifdef AM53C974_DEBUG
 #define DEB(x) x
 #ifdef AM53C974_DEBUG_KEYWAIT
   #define KEYWAIT() AM53C974_keywait()
  #else
   #define KEYWAIT()
  #endif
 #ifdef AM53C974_DEBUG_INIT
   #define DEB_INIT(x) x
  #else
   #define DEB_INIT(x)
  #endif
 #ifdef AM53C974_DEBUG_MSG
   #define DEB_MSG(x) x
  #else
   #define DEB_MSG(x)
  #endif
 #ifdef AM53C974_DEB_RESEL
   #define DEB_RESEL(x) x
  #else
   #define DEB_RESEL(x)
  #endif
 #ifdef AM53C974_DEBUG_QUEUE
  #define DEB_QUEUE(x) x
  #define LIST(x,y) {printk("LINE:%d   Adding %p to %p\n", __LINE__, (void*)(x), (void*)(y)); if ((x)==(y)) udelay(5); }
  #define REMOVE(w,x,y,z) {printk("LINE:%d   Removing: %p->%p  %p->%p \n", __LINE__, (void*)(w), (void*)(x), (void*)(y), (void*)(z)); if ((x)==(y)) udelay(5); }
 #else
  #define DEB_QUEUE(x)
  #define LIST(x,y)
  #define REMOVE(w,x,y,z)
 #endif
 #ifdef AM53C974_DEBUG_INFO
   #define DEB_INFO(x) x
  #else
   #define DEB_INFO(x)
  #endif
 #ifdef AM53C974_DEBUG_LINKED
   #define DEB_LINKED(x) x
  #else
   #define DEB_LINKED(x)
  #endif
 #ifdef AM53C974_DEBUG_INTR
   #define DEB_INTR(x) x
  #else
   #define DEB_INTR(x)
  #endif
#else
 #define DEB_INIT(x)
 #define DEB(x)
 #define DEB_QUEUE(x)
 #define LIST(x,y)
 #define REMOVE(w,x,y,z)
 #define DEB_INFO(x)
 #define DEB_LINKED(x)
 #define DEB_INTR(x)
 #define DEB_MSG(x)
 #define DEB_RESEL(x)
 #define KEYWAIT()
#endif
 #ifdef AM53C974_DEBUG_ABORT
   #define DEB_ABORT(x) x
  #else
   #define DEB_ABORT(x)
  #endif

#ifdef VERBOSE_AM53C974_DEBUG
#define VDEB(x) x
#else
#define VDEB(x)
#endif

#define INSIDE(x,l,h) ( ((x) >= (l)) && ((x) <= (h)) )

#ifdef AM53C974_DEBUG
static void AM53C974_print_pci(struct Scsi_Host *instance);
static void AM53C974_print_phase(struct Scsi_Host *instance);
static void AM53C974_print_queues(struct Scsi_Host *instance);
#endif /* AM53C974_DEBUG */
static void AM53C974_print(struct Scsi_Host *instance);
static void AM53C974_keywait(void);
static int AM53C974_bios_detect(Scsi_Host_Template *tpnt);
static int AM53C974_nobios_detect(Scsi_Host_Template *tpnt);
static int AM53C974_init(Scsi_Host_Template *tpnt, pci_config_t pci_config);
static void AM53C974_config_after_reset(struct Scsi_Host *instance);
static __inline__ void initialize_SCp(Scsi_Cmnd *cmd);
static __inline__ void run_main(void);
static void AM53C974_main (void);
static void AM53C974_intr(int irq, void *dev_id, struct pt_regs *regs);
static void AM53C974_intr_disconnect(struct Scsi_Host *instance); 
static int AM53C974_sync_neg(struct Scsi_Host *instance, int target, unsigned char *msg);
static __inline__ void AM53C974_set_async(struct Scsi_Host *instance, int target);
static __inline__ void AM53C974_set_sync(struct Scsi_Host *instance, int target);
static void AM53C974_information_transfer(struct Scsi_Host *instance, 
                                          unsigned char statreg, unsigned char isreg,
                                          unsigned char instreg, unsigned char cfifo,
                                          unsigned char dmastatus);
static int AM53C974_message(struct Scsi_Host *instance, Scsi_Cmnd *cmd, unsigned char msg);
static void AM53C974_select(struct Scsi_Host *instance, Scsi_Cmnd *cmd, int tag);
static void AM53C974_intr_reselect(struct Scsi_Host *instance, unsigned char statreg);
static  __inline__ void AM53C974_transfer_dma(struct Scsi_Host *instance, short dir,
                                              unsigned long length, char *data);
static void AM53C974_dma_blast(struct Scsi_Host *instance, unsigned char dmastatus, 
                               unsigned char statreg);
static void AM53C974_intr_bus_reset(struct Scsi_Host *instance);

static struct Scsi_Host *first_instance = NULL;
static Scsi_Host_Template *the_template = NULL;
static struct Scsi_Host *first_host = NULL;	/* Head of list of AMD boards */
static volatile int main_running = 0;
static int commandline_current = 0;
override_t overrides[7] = { {-1, 0, 0, 0}, };   /* LILO overrides */

struct proc_dir_entry proc_scsi_am53c974 = {
	PROC_SCSI_AM53C974, 8, "am53c974",
	S_IFDIR | S_IRUGO | S_IXUGO, 2
};

#ifdef AM53C974_DEBUG
static int deb_stop = 1;

/**************************************************************************
 * Function : void AM53C974_print_pci(struct Scsi_Host *instance)
 *
 * Purpose : dump the PCI registers for debugging purposes
 *
 * Input : instance - which AM53C974
 **************************************************************************/
static void AM53C974_print_pci(struct Scsi_Host *instance)
{
int            i;
unsigned short vendor_id, device_id, command, status, scratch[8];
unsigned long  class_revision, base; 
unsigned char  irq, cache_line_size, latency_timer, header_type;

AM53C974_PCIREG_OPEN();

for (i = 0; i < 8; i++) *(scratch + i) = AM53C974_PCIREG_READ_WORD(instance, PCI_SCRATCH_REG_0 + 2*i);
vendor_id = AM53C974_PCIREG_READ_WORD(instance, PCI_VENDOR_ID);
device_id = AM53C974_PCIREG_READ_WORD(instance, PCI_DEVICE_ID);
command   = AM53C974_PCIREG_READ_WORD(instance, PCI_COMMAND);
status    = AM53C974_PCIREG_READ_WORD(instance, PCI_STATUS);
class_revision = AM53C974_PCIREG_READ_DWORD(instance, PCI_CLASS_REVISION);
cache_line_size = AM53C974_PCIREG_READ_BYTE(instance, PCI_CACHE_LINE_SIZE);
latency_timer = AM53C974_PCIREG_READ_BYTE(instance, PCI_LATENCY_TIMER);
header_type = AM53C974_PCIREG_READ_BYTE(instance, PCI_HEADER_TYPE);
base = AM53C974_PCIREG_READ_DWORD(instance, PCI_BASE_ADDRESS_0);
irq = AM53C974_PCIREG_READ_BYTE(instance, PCI_INTERRUPT_LINE);

AM53C974_PCIREG_CLOSE();


printk("------------- start of PCI register dump -------------\n");
printk("PCI_VENDOR_ID:       0x%x\n", vendor_id);
printk("PCI_DEVICE_ID:       0x%x\n", device_id);
printk("PCI_COMMAND:         0x%x\n", command);
printk("PCI_STATUS:          0x%x\n", status);
printk("PCI_CLASS_REVISION:  0x%lx\n", class_revision);
printk("PCI_CACHE_LINE_SIZE: 0x%x\n", cache_line_size);
printk("PCI_LATENCY_TIMER:   0x%x\n", latency_timer);
printk("PCI_HEADER_TYPE:     0x%x\n", header_type);
printk("PCI_BASE_ADDRESS_0:  0x%lx\n", base);
printk("PCI_INTERRUPT_LINE:  %d\n", irq);
for (i = 0; i < 8; i++) printk("PCI_SCRATCH_%d:       0x%x\n", i, scratch[i]);
printk("------------- end of PCI register dump -------------\n\n");
}

static struct {
    unsigned char value;
    char *name;
} phases[] = {
{PHASE_DATAOUT, "DATAOUT"}, {PHASE_DATAIN, "DATAIN"}, {PHASE_CMDOUT, "CMDOUT"},
{PHASE_STATIN, "STATIN"}, {PHASE_MSGOUT, "MSGOUT"}, {PHASE_MSGIN, "MSGIN"},
{PHASE_RES_0, "RESERVED 0"}, {PHASE_RES_1, "RESERVED 1"}};

/************************************************************************** 
 * Function : void AM53C974_print_phase(struct Scsi_Host *instance)
 *
 * Purpose : print the current SCSI phase for debugging purposes
 *
 * Input : instance - which AM53C974
 **************************************************************************/
static void AM53C974_print_phase(struct Scsi_Host *instance)
{
AM53C974_local_declare();
unsigned char statreg, latched;
int           i;
AM53C974_setio(instance);

latched = (AM53C974_read_8(CNTLREG2)) & CNTLREG2_ENF;
statreg = AM53C974_read_8(STATREG);
for (i = 0; (phases[i].value != PHASE_RES_1) && 
     (phases[i].value != (statreg & STATREG_PHASE)); ++i); 
if (latched)
   printk("scsi%d : phase %s, latched at end of last command\n", instance->host_no, phases[i].name);
  else
   printk("scsi%d : phase %s, real time\n", instance->host_no, phases[i].name);
}

/**************************************************************************
 * Function : void AM53C974_print_queues(struct Scsi_Host *instance)
 *
 * Purpose : print commands in the various queues
 *
 * Inputs : instance - which AM53C974
 **************************************************************************/
static void AM53C974_print_queues(struct Scsi_Host *instance)
{
struct AM53C974_hostdata *hostdata = (struct AM53C974_hostdata *)instance->hostdata;
Scsi_Cmnd *ptr;

printk("AM53C974: coroutine is%s running.\n", main_running ? "" : "n't");
    
cli();
    
if (!hostdata->connected) {
   printk ("scsi%d: no currently connected command\n", instance->host_no); } 
  else {
   print_Scsi_Cmnd ((Scsi_Cmnd *)hostdata->connected); }
if (!hostdata->sel_cmd) {
   printk ("scsi%d: no currently arbitrating command\n", instance->host_no); } 
  else {
   print_Scsi_Cmnd ((Scsi_Cmnd *)hostdata->sel_cmd); }

printk ("scsi%d: issue_queue ", instance->host_no);
if (!hostdata->issue_queue)
   printk("empty\n");
  else {
   printk(":\n");
   for (ptr = (Scsi_Cmnd *)hostdata->issue_queue; ptr; ptr = (Scsi_Cmnd *)ptr->host_scribble) 
       print_Scsi_Cmnd (ptr); }

printk ("scsi%d: disconnected_queue ", instance->host_no);
if (!hostdata->disconnected_queue)
   printk("empty\n");
  else {
   printk(":\n");
   for (ptr = (Scsi_Cmnd *) hostdata->disconnected_queue; ptr; ptr = (Scsi_Cmnd *)ptr->host_scribble) 
       print_Scsi_Cmnd (ptr); }
    
sti();
}

#endif /* AM53C974_DEBUG */

/**************************************************************************
 * Function : void AM53C974_print(struct Scsi_Host *instance)
 *
 * Purpose : dump the chip registers for debugging purposes
 *
 * Input : instance - which AM53C974
 **************************************************************************/
static void AM53C974_print(struct Scsi_Host *instance)
{
AM53C974_local_declare();
unsigned long ctcreg, dmastc, dmaspa, dmawbc, dmawac;
unsigned char cmdreg, statreg, isreg, cfireg, cntlreg[4], dmacmd, dmastatus;
AM53C974_setio(instance);

cli();
ctcreg = AM53C974_read_8(CTCHREG) << 16;
ctcreg |= AM53C974_read_8(CTCMREG) << 8;
ctcreg |= AM53C974_read_8(CTCLREG);
cmdreg = AM53C974_read_8(CMDREG);
statreg = AM53C974_read_8(STATREG);
isreg = AM53C974_read_8(ISREG);
cfireg = AM53C974_read_8(CFIREG);
cntlreg[0] = AM53C974_read_8(CNTLREG1);
cntlreg[1] = AM53C974_read_8(CNTLREG2);
cntlreg[2] = AM53C974_read_8(CNTLREG3);
cntlreg[3] = AM53C974_read_8(CNTLREG4);
dmacmd = AM53C974_read_8(DMACMD);
dmastc = AM53C974_read_32(DMASTC);
dmaspa = AM53C974_read_32(DMASPA);
dmawbc = AM53C974_read_32(DMAWBC);
dmawac = AM53C974_read_32(DMAWAC);
dmastatus = AM53C974_read_8(DMASTATUS);
sti();

printk("AM53C974 register dump:\n");
printk("IO base: 0x%04lx; CTCREG: 0x%04lx; CMDREG: 0x%02x; STATREG: 0x%02x; ISREG: 0x%02x\n",
       io_port, ctcreg, cmdreg, statreg, isreg);
printk("CFIREG: 0x%02x; CNTLREG1-4: 0x%02x; 0x%02x; 0x%02x; 0x%02x\n",
        cfireg, cntlreg[0], cntlreg[1], cntlreg[2], cntlreg[3]);
printk("DMACMD: 0x%02x; DMASTC: 0x%04lx; DMASPA: 0x%04lx\n", dmacmd, dmastc, dmaspa);
printk("DMAWBC: 0x%04lx; DMAWAC: 0x%04lx; DMASTATUS: 0x%02x\n", dmawbc, dmawac, dmastatus);
printk("---------------------------------------------------------\n");
}

/**************************************************************************
* Function : void AM53C974_keywait(void)
*
* Purpose : wait until a key is pressed, if it was the 'r' key leave singlestep mode;
*           this function is used for debugging only
*
* Input : none
**************************************************************************/
static void AM53C974_keywait(void)
{
#ifdef AM53C974_DEBUG
int key;

if (!deb_stop) return;
#endif

cli();
while ((inb_p(0x64) & 0x01) != 0x01) ;
#ifdef AM53C974_DEBUG
key = inb(0x60);
if (key == 0x93) deb_stop = 0;  /* don't stop if 'r' was pressed */
#endif
sti();
}

/**************************************************************************
* Function : AM53C974_setup(char *str, int *ints)
*
* Purpose : LILO command line initialization of the overrides array,
* 
* Inputs : str - unused, ints - array of integer parameters with ints[0]
*	    equal to the number of ints.
*
* NOTE : this function needs to be declared as an external function
*         in init/main.c and included there in the bootsetups list
***************************************************************************/
void AM53C974_setup(char *str, int *ints)
{
if (ints[0] < 4) 
   printk("AM53C974_setup: wrong number of parameters;\n correct syntax is: AM53C974=host-scsi-id, target-scsi-id, max-rate, max-offset\n");
  else {
   if (commandline_current < (sizeof(overrides) / sizeof(override_t))) {
      if ((ints[1] < 0) || (ints[1] > 7) ||
          (ints[2] < 0) || (ints[2] > 7) ||
          (ints[1] == ints[2]) ||
          (ints[3] < (DEF_CLK / MAX_PERIOD)) || (ints[3] > (DEF_CLK / MIN_PERIOD)) ||
          (ints[4] < 0) || (ints[4] > MAX_OFFSET))
         printk("AM53C974_setup: illegal parameter\n");
        else {
         overrides[commandline_current].host_scsi_id = ints[1];
         overrides[commandline_current].target_scsi_id = ints[2];
         overrides[commandline_current].max_rate = ints[3];
         overrides[commandline_current].max_offset = ints[4];
         commandline_current++; }
      }
     else
      printk("AM53C974_setup: too many overrides\n");
   }
}

#if defined (CONFIG_PCI)
/**************************************************************************
* Function : int AM53C974_bios_detect(Scsi_Host_Template *tpnt)
*
* Purpose : detects and initializes AM53C974 SCSI chips with PCI Bios
*
* Inputs : tpnt - host template
* 
* Returns : number of host adapters detected
**************************************************************************/
int AM53C974_bios_detect(Scsi_Host_Template *tpnt)
{
int count = 0;        /* number of boards detected */
int pci_index;
pci_config_t pci_config;

for (pci_index = 0; pci_index <= 16; ++pci_index) {
    unsigned char pci_bus, pci_device_fn;
    if (pcibios_find_device(PCI_VENDOR_ID_AMD, PCI_DEVICE_ID_AMD_SCSI, pci_index, &pci_bus, &pci_device_fn) != 0)
       break;

    pcibios_read_config_word(pci_bus, pci_device_fn, PCI_VENDOR_ID, &pci_config._vendor);
    pcibios_read_config_word(pci_bus, pci_device_fn, PCI_DEVICE_ID, &pci_config._device);
    pcibios_read_config_word(pci_bus, pci_device_fn, PCI_COMMAND, &pci_config._command);
    pcibios_read_config_word(pci_bus, pci_device_fn, PCI_STATUS, &pci_config._status);
    pcibios_read_config_dword(pci_bus, pci_device_fn, PCI_CLASS_REVISION, &pci_config._class_revision);
    pcibios_read_config_byte(pci_bus, pci_device_fn, PCI_CACHE_LINE_SIZE, &pci_config._cache_line_size);
    pcibios_read_config_byte(pci_bus, pci_device_fn, PCI_LATENCY_TIMER, &pci_config._latency_timer);
    pcibios_read_config_byte(pci_bus, pci_device_fn, PCI_HEADER_TYPE, &pci_config._header_type);
    pcibios_read_config_byte(pci_bus, pci_device_fn, PCI_BIST, &pci_config._bist);
    pcibios_read_config_dword(pci_bus, pci_device_fn, PCI_BASE_ADDRESS_0, &pci_config._base0);
    pcibios_read_config_dword(pci_bus, pci_device_fn, PCI_BASE_ADDRESS_1, &pci_config._base1);
    pcibios_read_config_dword(pci_bus, pci_device_fn, PCI_BASE_ADDRESS_2, &pci_config._base2);
    pcibios_read_config_dword(pci_bus, pci_device_fn, PCI_BASE_ADDRESS_3, &pci_config._base3);
    pcibios_read_config_dword(pci_bus, pci_device_fn, PCI_BASE_ADDRESS_4, &pci_config._base4);
    pcibios_read_config_dword(pci_bus, pci_device_fn, PCI_BASE_ADDRESS_5, &pci_config._base5);
    pcibios_read_config_dword(pci_bus, pci_device_fn, PCI_ROM_ADDRESS, &pci_config._baserom);
    pcibios_read_config_byte(pci_bus, pci_device_fn, PCI_INTERRUPT_LINE, &pci_config._int_line);
    pcibios_read_config_byte(pci_bus, pci_device_fn, PCI_INTERRUPT_PIN, &pci_config._int_pin);
    pcibios_read_config_byte(pci_bus, pci_device_fn, PCI_MIN_GNT, &pci_config._min_gnt);
    pcibios_read_config_byte(pci_bus, pci_device_fn, PCI_MAX_LAT, &pci_config._max_lat);
    pci_config._pcibus = 0xFFFFFFFF;
    pci_config._cardnum = 0xFFFFFFFF;
 
    /* check whether device is I/O mapped -- should be */
    if (!(pci_config._command & PCI_COMMAND_IO)) continue;

    /* PCI Spec 2.1 states that it is either the driver's or the PCI card's responsibility
       to set the PCI Master Enable Bit if needed. 
       (from Mark Stockton <marks@schooner.sys.hou.compaq.com>) */
    if (!(pci_config._command & PCI_COMMAND_MASTER)) {
       pci_config._command |= PCI_COMMAND_MASTER;
       printk("PCI Master Bit has not been set. Setting...\n");
       pcibios_write_config_word(pci_bus, pci_device_fn, PCI_COMMAND, pci_config._command); }

    /* everything seems OK now, so initialize */
    if (AM53C974_init(tpnt, pci_config)) count++ ;
    }
return (count);
}
#endif

/**************************************************************************
* Function : int AM53C974_nobios_detect(Scsi_Host_Template *tpnt)
*
* Purpose : detects and initializes AM53C974 SCSI chips using PCI config 2 
*
* Inputs : tpnt - host template
* 
* Returns : number of host adapters detected
*
* NOTE : This code assumes the controller on PCI bus 0.
*
* Origin: Robin Cutshaw (robin@xfree86.org)
**************************************************************************/
int AM53C974_nobios_detect(Scsi_Host_Template *tpnt)
{
int          count = 0;		/* number of boards detected */
pci_config_t pci_config;

/* first try PCI config method 1 */
for (pci_config._pcibus = 0; pci_config._pcibus < 0x10; pci_config._pcibus++) {
    for (pci_config._cardnum = 0; pci_config._cardnum < 0x20; pci_config._cardnum++) {
        unsigned long config_cmd;
	config_cmd = 0x80000000 | (pci_config._pcibus<<16) | (pci_config._cardnum<<11);

        outl(config_cmd, 0xCF8);         /* ioreg 0 */
        pci_config._device_vendor = inl(0xCFC);

        if ((pci_config._vendor == PCI_VENDOR_ID_AMD) && (pci_config._device == PCI_DEVICE_ID_AMD_SCSI)) {
           outl(config_cmd | PCI_COMMAND, 0xCF8); pci_config._status_command  = inl(0xCFC);
           outl(config_cmd | PCI_CLASS_REVISION, 0xCF8); pci_config._class_revision = inl(0xCFC);
           outl(config_cmd | PCI_CACHE_LINE_SIZE, 0xCF8); pci_config._bist_header_latency_cache = inl(0xCFC);
           outl(config_cmd | PCI_BASE_ADDRESS_0, 0xCF8); pci_config._base0 = inl(0xCFC);
           outl(config_cmd | PCI_BASE_ADDRESS_1, 0xCF8); pci_config._base1 = inl(0xCFC);
           outl(config_cmd | PCI_BASE_ADDRESS_2, 0xCF8); pci_config._base2 = inl(0xCFC);
           outl(config_cmd | PCI_BASE_ADDRESS_3, 0xCF8); pci_config._base3 = inl(0xCFC);
           outl(config_cmd | PCI_BASE_ADDRESS_4, 0xCF8); pci_config._base4 = inl(0xCFC);
           outl(config_cmd | PCI_BASE_ADDRESS_5, 0xCF8); pci_config._base5 = inl(0xCFC);
           outl(config_cmd | PCI_ROM_ADDRESS, 0xCF8); pci_config._baserom = inl(0xCFC);
           outl(config_cmd | PCI_INTERRUPT_LINE, 0xCF8); pci_config._max_min_ipin_iline = inl(0xCFC);

           /* check whether device is I/O mapped -- should be */
           if (!(pci_config._command & PCI_COMMAND_IO)) continue;

           /* PCI Spec 2.1 states that it is either the driver's or the PCI card's responsibility
              to set the PCI Master Enable Bit if needed. 
              From Mark Stockton <marks@schooner.sys.hou.compaq.com> */
           if (!(pci_config._command & PCI_COMMAND_MASTER)) {
              pci_config._command |= PCI_COMMAND_MASTER;
              printk("Config 1; PCI Master Bit has not been set. Setting...\n");
              outl(config_cmd | PCI_COMMAND, 0xCF8); outw(pci_config._command, 0xCFC); }

           /* everything seems OK now, so initialize */
           if (AM53C974_init(tpnt, pci_config)) count++ ;
           }
        }
    }
outb(0, 0xCF8); /* is this really necessary? */

/* try PCI config method 2, if no device was detected by method 1 */
if (!count) {
   AM53C974_PCIREG_OPEN();

   pci_config._pcibus = 0xFFFFFFFF;
   pci_config._cardnum = 0xFFFFFFFF;

   for (pci_config._ioaddr = 0xC000; pci_config._ioaddr < 0xD000; pci_config._ioaddr += 0x0100) {
       pci_config._device_vendor = inl(pci_config._ioaddr);

       if ((pci_config._vendor == PCI_VENDOR_ID_AMD) && (pci_config._device == PCI_DEVICE_ID_AMD_SCSI)) {
          pci_config._status_command = inl(pci_config._ioaddr + PCI_COMMAND);
          pci_config._class_revision = inl(pci_config._ioaddr + PCI_CLASS_REVISION);
          pci_config._bist_header_latency_cache = inl(pci_config._ioaddr + PCI_CACHE_LINE_SIZE);
          pci_config._base0 = inl(pci_config._ioaddr + PCI_BASE_ADDRESS_0);
          pci_config._base1 = inl(pci_config._ioaddr + PCI_BASE_ADDRESS_1);
          pci_config._base2 = inl(pci_config._ioaddr + PCI_BASE_ADDRESS_2);
          pci_config._base3 = inl(pci_config._ioaddr + PCI_BASE_ADDRESS_3);
          pci_config._base4 = inl(pci_config._ioaddr + PCI_BASE_ADDRESS_4);
          pci_config._base5 = inl(pci_config._ioaddr + PCI_BASE_ADDRESS_5);
          pci_config._baserom = inl(pci_config._ioaddr + PCI_ROM_ADDRESS);
          pci_config._max_min_ipin_iline = inl(pci_config._ioaddr + PCI_INTERRUPT_LINE);

          /* check whether device is I/O mapped -- should be */
          if (!(pci_config._command & PCI_COMMAND_IO)) continue;

          /* PCI Spec 2.1 states that it is either the driver's or the PCI card's responsibility
             to set the PCI Master Enable Bit if needed.
             From Mark Stockton <marks@schooner.sys.hou.compaq.com> */
          if (!(pci_config._command & PCI_COMMAND_MASTER)) {
              pci_config._command |= PCI_COMMAND_MASTER;
              printk("Config 2; PCI Master Bit has not been set. Setting...\n");
              outw(pci_config._command, pci_config._ioaddr + PCI_COMMAND); }

          /* everything seems OK now, so initialize */
          if (AM53C974_init(tpnt, pci_config)) count++ ;
          }
       }
   AM53C974_PCIREG_CLOSE();
   }

return(count);
}

/**************************************************************************
* Function : int AM53C974_detect(Scsi_Host_Template *tpnt)
*
* Purpose : detects and initializes AM53C974 SCSI chips
*
* Inputs : tpnt - host template
* 
* Returns : number of host adapters detected
**************************************************************************/
int AM53C974_detect(Scsi_Host_Template *tpnt)
{
int count;        /* number of boards detected */

tpnt->proc_dir = &proc_scsi_am53c974;

#if defined (CONFIG_PCI)
if (pcibios_present())
   count = AM53C974_bios_detect(tpnt);
  else
#endif
count = AM53C974_nobios_detect(tpnt);
return (count);
}

/**************************************************************************
* Function : int AM53C974_init(Scsi_Host_Template *tpnt, pci_config_t pci_config)
*
* Purpose : initializes instance and corresponding AM53/79C974 chip,
*
* Inputs : tpnt - template, pci_config - PCI configuration,
* 
* Returns : 1 on success, 0 on failure.
* 
* NOTE: If no override for the controller's SCSI id is given and AM53C974_SCSI_ID 
*       is not defined we assume that the SCSI address of this controller is correctly
*       set up by the BIOS (as reflected by contents of register CNTLREG1).
*       This is the only BIOS assistance we need.
**************************************************************************/
static int AM53C974_init(Scsi_Host_Template *tpnt, pci_config_t pci_config)
{
AM53C974_local_declare();
int                      i, j;
struct Scsi_Host         *instance, *search;
struct AM53C974_hostdata *hostdata;

#ifdef AM53C974_OPTION_DEBUG_PROBE_ONLY
   printk ("AM53C974: probe only enabled, aborting initialization\n");
   return 0;
#endif

instance = scsi_register(tpnt, sizeof(struct AM53C974_hostdata));
hostdata = (struct AM53C974_hostdata *)instance->hostdata;
instance->base = NULL;
instance->io_port = pci_config._base0 & (pci_config._base0 & 0x1 ? 
                                         0xFFFFFFFC : 0xFFFFFFF0);
instance->irq = pci_config._int_line;
instance->dma_channel = -1;
AM53C974_setio(instance);

#ifdef AM53C974_SCSI_ID
instance->this_id = AM53C974_SCSI_ID;
AM53C974_write_8(CNTLREG1, instance->this_id & CNTLREG1_SID);
#else
instance->this_id = AM53C974_read_8(CNTLREG1) & CNTLREG1_SID;
if (instance->this_id != 7) 
   printk("scsi%d: WARNING: unusual hostadapter SCSI id %d; please verify!\n", 
          instance->host_no, instance->this_id);
#endif

for (i = 0; i < sizeof(hostdata->msgout); i++) {
    hostdata->msgout[i] = NOP;
    hostdata->last_message[i] = NOP; }
for (i = 0; i < 8; i++) {
    hostdata->busy[i] = 0;
    hostdata->sync_per[i] = DEF_STP;
    hostdata->sync_off[i] = 0;
    hostdata->sync_neg[i] = 0;
    hostdata->sync_en[i] = DEFAULT_SYNC_NEGOTIATION_ENABLED;
    hostdata->max_rate[i] = DEFAULT_RATE;
    hostdata->max_offset[i] = DEFAULT_SYNC_OFFSET; }

/* overwrite defaults by LILO overrides */
for (i = 0; i < commandline_current; i++) {
    if (overrides[i].host_scsi_id == instance->this_id) {
       j = overrides[i].target_scsi_id;
       hostdata->sync_en[j] = 1;
       hostdata->max_rate[j] = overrides[i].max_rate;
       hostdata->max_offset[j] = overrides[i].max_offset; 
       }
    }

hostdata->sel_cmd = NULL;
hostdata->connected = NULL;
hostdata->issue_queue = NULL;
hostdata->disconnected_queue = NULL;
hostdata->in_reset = 0;
hostdata->aborted = 0;
hostdata->selecting = 0;
hostdata->disconnecting = 0;
hostdata->dma_busy = 0;

/* Set up an interrupt handler if we aren't already sharing an IRQ with another board */
for (search = first_host; 
     search && ( ((the_template != NULL) && (search->hostt != the_template)) || 
                 (search->irq != instance->irq) || (search == instance) );
     search = search->next);
if (!search) {
   if (request_irq(instance->irq, AM53C974_intr, SA_INTERRUPT, "AM53C974", NULL)) {
      printk("scsi%d: IRQ%d not free, detaching\n", instance->host_no, instance->irq);
      scsi_unregister(instance);
      return 0; } 
   }
  else {
   printk("scsi%d: using interrupt handler previously installed for scsi%d\n",
	  instance->host_no, search->host_no); }

if (!the_template) {
   the_template = instance->hostt;
   first_instance = instance; }

/* do hard reset */
AM53C974_write_8(CMDREG, CMDREG_RDEV);     /* reset device */
udelay(5);
AM53C974_write_8(CMDREG, CMDREG_NOP);
AM53C974_write_8(CNTLREG1, CNTLREG1_DISR | instance->this_id); 
AM53C974_write_8(CMDREG, CMDREG_RBUS);     /* reset SCSI bus */
udelay(10);
AM53C974_config_after_reset(instance);
udelay(500000);
return(1);
}

/*********************************************************************
* Function : AM53C974_config_after_reset(struct Scsi_Host *instance) *
*                                                                    *
* Purpose : initializes chip registers after reset                   *
*                                                                    *
* Inputs : instance - which AM53C974                                 *
*                                                                    *
* Returns : nothing                                                  *
**********************************************************************/
static void AM53C974_config_after_reset(struct Scsi_Host *instance)
{
AM53C974_local_declare(); 
AM53C974_setio(instance);

/* clear SCSI FIFO */
AM53C974_write_8(CMDREG, CMDREG_CFIFO);

/* configure device */
AM53C974_write_8(STIMREG, DEF_SCSI_TIMEOUT);
AM53C974_write_8(STPREG, DEF_STP & STPREG_STP);
AM53C974_write_8(SOFREG, (DEF_SOF_RAD<<6) | (DEF_SOF_RAA<<4));
AM53C974_write_8(CLKFREG, DEF_CLKF & CLKFREG_MASK);
AM53C974_write_8(CNTLREG1, (DEF_ETM<<7) | CNTLREG1_DISR | (DEF_PERE<<4) | instance->this_id);
AM53C974_write_8(CNTLREG2, (DEF_ENF<<6));
AM53C974_write_8(CNTLREG3, (DEF_ADIDCHK<<7) | (DEF_FASTSCSI<<4) | (DEF_FASTCLK<<3));
AM53C974_write_8(CNTLREG4, (DEF_GLITCH<<6) | (DEF_PWD<<5) | (DEF_RAE<<3) | (DEF_RADE<<2) | CNTLREG4_RES);
}

/***********************************************************************
* Function : const char *AM53C974_info(struct Scsi_Host *instance)     *
*                                                                      *
* Purpose : return device driver information                           *
*                                                                      *
* Inputs : instance - which AM53C974                                   *
*                                                                      *
* Returns : info string                                                *
************************************************************************/
const char *AM53C974_info(struct Scsi_Host *instance)
{
static char       info[100];

sprintf(info, "AM53/79C974 PCscsi driver rev. %d.%d; host I/O address: 0x%x; irq: %d\n", 
        AM53C974_DRIVER_REVISION_MAJOR, AM53C974_DRIVER_REVISION_MINOR,
        instance->io_port, instance->irq);
return (info);
}

/************************************************************************** 
* Function : int AM53C974_command (Scsi_Cmnd *SCpnt)                      *
*                                                                         *
* Purpose : the unqueued SCSI command function, replaced by the           *
*           AM53C974_queue_command function                               *
*                                                                         *
* Inputs : SCpnt - pointer to command structure                           *
*                                                                         *
* Returns :status, see hosts.h for details                                *
***************************************************************************/
int AM53C974_command(Scsi_Cmnd *SCpnt)
{
DEB(printk("AM53C974_command called\n"));
return 0;
}

/**************************************************************************
* Function : void initialize_SCp(Scsi_Cmnd *cmd)                          *
*                                                                         *
* Purpose : initialize the saved data pointers for cmd to point to the    *
*	    start of the buffer.                                          *                              
*                                                                         *
* Inputs : cmd - Scsi_Cmnd structure to have pointers reset.              *
*                                                                         *
* Returns : nothing                                                       *
**************************************************************************/
static __inline__ void initialize_SCp(Scsi_Cmnd *cmd)
{
if (cmd->use_sg) {
   cmd->SCp.buffer = (struct scatterlist *)cmd->buffer;
   cmd->SCp.buffers_residual = cmd->use_sg - 1;
   cmd->SCp.ptr = (char *)cmd->SCp.buffer->address;
   cmd->SCp.this_residual = cmd->SCp.buffer->length; }
  else {
   cmd->SCp.buffer = NULL;
   cmd->SCp.buffers_residual = 0;
   cmd->SCp.ptr = (char *)cmd->request_buffer;
   cmd->SCp.this_residual = cmd->request_bufflen; }
}

/**************************************************************************
* Function : run_main(void)                                               *
*                                                                         *
* Purpose : insure that the coroutine is running and will process our     *
* 	    request.  main_running is checked/set here (in an inline      *
*           function rather than in AM53C974_main itself to reduce the    *
*           chances of stack overflow.                                    *
*                                                                         *
*                                                                         *
* Inputs : none                                                           *
*                                                                         *
* Returns : nothing                                                       *
**************************************************************************/
static __inline__ void run_main(void)
{
cli();
if (!main_running) {
   /* main_running is cleared in AM53C974_main once it can't do 
      more work, and AM53C974_main exits with interrupts disabled. */
   main_running = 1;
   AM53C974_main();
   sti(); }
  else 
   sti();
}

/************************************************************************** 
* Function : int AM53C974_queue_command(Scsi_Cmnd *cmd, void (*done)(Scsi_Cmnd *))
*
* Purpose : writes SCSI command into AM53C974 FIFO 
*
* Inputs : cmd - SCSI command, done - function called on completion, with
*	a pointer to the command descriptor.
* 
* Returns : status, see hosts.h for details
*
* Side effects : 
*      cmd is added to the per instance issue_queue, with minor 
*	twiddling done to the host specific fields of cmd.  If the 
*	main coroutine is not running, it is restarted.
**************************************************************************/
int AM53C974_queue_command(Scsi_Cmnd *cmd, void (*done)(Scsi_Cmnd *))
{
struct Scsi_Host         *instance = cmd->host;
struct AM53C974_hostdata *hostdata = (struct AM53C974_hostdata *)instance->hostdata;
Scsi_Cmnd                *tmp;

cli();
DEB_QUEUE(printk(SEPARATOR_LINE));
DEB_QUEUE(printk("scsi%d: AM53C974_queue_command called\n", instance->host_no));
DEB_QUEUE(printk("cmd=%02x target=%02x lun=%02x bufflen=%d use_sg = %02x\n", 
	   cmd->cmnd[0], cmd->target, cmd->lun, cmd->request_bufflen, cmd->use_sg));

/* We use the host_scribble field as a pointer to the next command in a queue */
cmd->host_scribble = NULL;
cmd->scsi_done = done;
cmd->result = 0;
cmd->device->disconnect = 0;

/* Insert the cmd into the issue queue. Note that REQUEST SENSE 
 * commands are added to the head of the queue since any command will
 * clear the contingent allegiance condition that exists and the 
 * sense data is only guaranteed to be valid while the condition exists. */
if (!(hostdata->issue_queue) || (cmd->cmnd[0] == REQUEST_SENSE)) {
   LIST(cmd, hostdata->issue_queue);
   cmd->host_scribble = (unsigned char *)hostdata->issue_queue;
   hostdata->issue_queue = cmd; }
  else {
   for (tmp = (Scsi_Cmnd *)hostdata->issue_queue; tmp->host_scribble; 
	tmp = (Scsi_Cmnd *)tmp->host_scribble);
   LIST(cmd, tmp);
   tmp->host_scribble = (unsigned char *)cmd; }

DEB_QUEUE(printk("scsi%d : command added to %s of queue\n", instance->host_no,
	  (cmd->cmnd[0] == REQUEST_SENSE) ? "head" : "tail"));

/* Run the coroutine if it isn't already running. */
run_main();
return 0;
}

/**************************************************************************
 * Function : AM53C974_main (void) 
 *
 * Purpose : AM53C974_main is a coroutine that runs as long as more work can 
 *	be done on the AM53C974 host adapters in a system.  Both 
 *	AM53C974_queue_command() and AM53C974_intr() will try to start it 
 *	in case it is not running.
 * 
 * NOTE : AM53C974_main exits with interrupts *disabled*, the caller should 
 *  reenable them.  This prevents reentrancy and kernel stack overflow.
 **************************************************************************/  
static void AM53C974_main(void)
{
AM53C974_local_declare(); 
Scsi_Cmnd                *tmp, *prev;
struct Scsi_Host         *instance;
struct AM53C974_hostdata *hostdata;
int                      done;

/* We run (with interrupts disabled) until we're sure that none of 
 * the host adapters have anything that can be done, at which point 
 * we set main_running to 0 and exit. */

do {
   cli(); /* Freeze request queues */
   done = 1;
   for (instance = first_instance; instance && instance->hostt == the_template;
        instance = instance->next) {
       hostdata = (struct AM53C974_hostdata *)instance->hostdata;
       AM53C974_setio(instance);
       /* start to select target if we are not connected and not in the 
          selection process */
       if (!hostdata->connected && !hostdata->sel_cmd) {
          /* Search through the issue_queue for a command destined for a target 
             that is not busy. */
          for (tmp = (Scsi_Cmnd *)hostdata->issue_queue, prev = NULL; tmp; 
               prev = tmp, tmp = (Scsi_Cmnd *)tmp->host_scribble) {
	      /*  When we find one, remove it from the issue queue. */
	      if (!(hostdata->busy[tmp->target] & (1 << tmp->lun))) {
		 if (prev) {
		    REMOVE(prev, (Scsi_Cmnd *)(prev->host_scribble), tmp,
                           (Scsi_Cmnd *)(tmp->host_scribble));
		    prev->host_scribble = tmp->host_scribble; } 
                   else {
		    REMOVE(-1, hostdata->issue_queue, tmp, tmp->host_scribble);
		    hostdata->issue_queue = (Scsi_Cmnd *)tmp->host_scribble; }
		 tmp->host_scribble = NULL;

                 /* go into selection mode, disable reselection and wait for
                    SO interrupt which will continue with the selection process */
                 hostdata->selecting = 1;
                 hostdata->sel_cmd = tmp;
                 AM53C974_write_8(CMDREG, CMDREG_DSR); 
                 break;                 
		 } /* if target/lun is not busy */

	      } /* for */
          } /* if (!hostdata->connected) */
         else {		
          DEB(printk("main: connected; cmd = 0x%lx, sel_cmd = 0x%lx\n",
                 (long)hostdata->connected, (long)hostdata->sel_cmd));
	  }
       } /* for instance */
   } while (!done);
main_running = 0;
}

/************************************************************************
* Function : AM53C974_intr(int irq, void *dev_id, struct pt_regs *regs) *
*                                                                       *
* Purpose : interrupt handler                                           *
*                                                                       *
* Inputs : irq - interrupt line, regs - ?                               *
*                                                                       *
* Returns : nothing                                                     *
************************************************************************/
static void AM53C974_intr(int irq, void *dev_id, struct pt_regs *regs)
{
AM53C974_local_declare(); 
struct Scsi_Host         *instance;
struct AM53C974_hostdata *hostdata;
unsigned char            cmdreg, dmastatus, statreg, isreg, instreg, cfifo;

/* find AM53C974 hostadapter responsible for this interrupt */
for (instance = first_instance; instance; instance = instance->next)
    if ((instance->irq == irq) && (instance->hostt == the_template)) goto FOUND;
sti();
return;

/* found; now decode and process */
FOUND:
hostdata = (struct AM53C974_hostdata *)instance->hostdata;
AM53C974_setio(instance);
dmastatus = AM53C974_read_8(DMASTATUS);

DEB_INTR(printk(SEPARATOR_LINE));
DEB_INTR(printk("AM53C974 interrupt; dmastatus=0x%02x\n", dmastatus));
KEYWAIT();

/*** DMA related interrupts ***/
if (hostdata->connected && (dmastatus & (DMASTATUS_ERROR | DMASTATUS_PWDN | 
                                         DMASTATUS_ABORT))) {
   /* DMA error or POWERDOWN */
   printk("scsi%d: DMA error or powerdown; dmastatus: 0x%02x\n",
          instance->host_no, dmastatus);
#ifdef AM53C974_DEBUG
   deb_stop = 1;
#endif
   panic("scsi%d: cannot recover\n", instance->host_no); }

if (hostdata->connected && (dmastatus & DMASTATUS_DONE)) {     
   /* DMA transfer done */
   unsigned long residual;
   cli();
   if (!(AM53C974_read_8(DMACMD) & DMACMD_DIR)) {
      do {
         dmastatus = AM53C974_read_8(DMASTATUS);
         residual  = AM53C974_read_8(CTCLREG) | (AM53C974_read_8(CTCMREG) << 8) |
                    (AM53C974_read_8(CTCHREG) << 16);
         residual += AM53C974_read_8(CFIREG) & CFIREG_CF;
         } while (!(dmastatus & DMASTATUS_SCSIINT) && residual);
      residual = AM53C974_read_8(CTCLREG) | (AM53C974_read_8(CTCMREG) << 8) |
                 (AM53C974_read_8(CTCHREG) << 16);
      residual += AM53C974_read_8(CFIREG) & CFIREG_CF;
      }
     else
      residual = 0;
   hostdata->connected->SCp.ptr += hostdata->connected->SCp.this_residual - residual;
   hostdata->connected->SCp.this_residual = residual;

   AM53C974_write_8(DMACMD, DMACMD_IDLE);

   /* if service request missed before, process it now (ugly) */
   if (hostdata->dma_busy) {
      hostdata->dma_busy = 0;
      cmdreg = AM53C974_read_8(CMDREG);
      statreg = AM53C974_read_8(STATREG);
      isreg = AM53C974_read_8(ISREG);
      instreg = AM53C974_read_8(INSTREG);
      cfifo = AM53C974_cfifo();
      AM53C974_information_transfer(instance, statreg, isreg, instreg, cfifo,
                                    dmastatus); }
   sti();
   }
   
if (!(dmastatus & DMASTATUS_SCSIINT)) {
   sti();
   return; }

/*** SCSI related interrupts ***/
cmdreg = AM53C974_read_8(CMDREG);
statreg = AM53C974_read_8(STATREG);
isreg = AM53C974_read_8(ISREG);
instreg = AM53C974_read_8(INSTREG);
cfifo = AM53C974_cfifo();

DEB_INTR(printk("scsi%d: statreg: 0x%02x; isreg: 0x%02x; instreg: 0x%02x; cfifo: 0x%02x\n",
                instance->host_no, statreg, isreg, instreg, cfifo));

if (statreg & STATREG_PE) {
   /* parity error */
#ifdef AM53C974_DEBUG
   deb_stop = 1;
#endif
   printk("scsi%d : PARITY error\n", instance->host_no);
   if (hostdata->connected) hostdata->sync_off[hostdata->connected->target] = 0; /* setup asynchronous transfer */
   hostdata->aborted = 1; }

if (statreg & STATREG_IOE) {
   /* illegal operation error */
#ifdef AM53C974_DEBUG
   deb_stop = 1;
#endif
   printk("scsi%d : ILLEGAL OPERATION error\n", instance->host_no);
   printk("cmdreg:  0x%02x; dmacmd:  0x%02x; statreg: 0x%02x; \n"
          "isreg:   0x%02x; instreg: 0x%02x; cfifo:   0x%02x\n",
           cmdreg, AM53C974_read_8(DMACMD), statreg, isreg, instreg, cfifo); }
if (hostdata->in_reset && (instreg & INSTREG_SRST)) {
   /* RESET INTERRUPT */
#ifdef AM53C974_DEBUG
   deb_stop = 1;
#endif
   DEB(printk("Bus reset interrupt received\n"));
   AM53C974_intr_bus_reset(instance);
   cli();
   if (hostdata->connected) {
      hostdata->connected->result = DID_RESET << 16;
      hostdata->connected->scsi_done((Scsi_Cmnd *)hostdata->connected);
      hostdata->connected = NULL; }
     else { 
      if (hostdata->sel_cmd) {
         hostdata->sel_cmd->result = DID_RESET << 16;
         hostdata->sel_cmd->scsi_done((Scsi_Cmnd *)hostdata->sel_cmd);
         hostdata->sel_cmd = NULL; }
      }
   sti();
   if (hostdata->in_reset == 1) goto EXIT;
     else return;
   }

if (instreg & INSTREG_ICMD) {
   /* INVALID COMMAND INTERRUPT */
#ifdef AM53C974_DEBUG
   deb_stop = 1;
#endif
   printk("scsi%d: Invalid command interrupt\n", instance->host_no);
   printk("cmdreg:  0x%02x; dmacmd:  0x%02x; statreg: 0x%02x; dmastatus: 0x%02x; \n"
          "isreg:   0x%02x; instreg: 0x%02x; cfifo:   0x%02x\n",
           cmdreg, AM53C974_read_8(DMACMD), statreg, dmastatus, isreg, instreg, cfifo);
   panic("scsi%d: cannot recover\n", instance->host_no); }

if (instreg & INSTREG_DIS) {
   /* DISCONNECT INTERRUPT */
   DEB_INTR(printk("Disconnect interrupt received; "));
   cli();
   AM53C974_intr_disconnect(instance);
   sti();
   goto EXIT; }

if (instreg & INSTREG_RESEL) {
   /* RESELECTION INTERRUPT */
   DEB_INTR(printk("Reselection interrupt received\n"));
   cli();
   AM53C974_intr_reselect(instance, statreg);
   sti();
   goto EXIT; }

if (instreg & INSTREG_SO) {
   DEB_INTR(printk("Successful operation interrupt received\n"));
   if (hostdata->selecting) {
      DEB_INTR(printk("DSR completed, starting select\n"));
      cli();
      AM53C974_select(instance, (Scsi_Cmnd *)hostdata->sel_cmd,
                          (hostdata->sel_cmd->cmnd[0] == REQUEST_SENSE) ? 
                                                  TAG_NONE : TAG_NEXT);
      hostdata->selecting = 0;
      AM53C974_set_sync(instance, hostdata->sel_cmd->target);
      sti();
      return; }

   if (hostdata->sel_cmd != NULL) {
      if ( ((isreg & ISREG_IS) != ISREG_OK_NO_STOP) &&
           ((isreg & ISREG_IS) != ISREG_OK_STOP) ) {
         /* UNSUCCESSFUL SELECTION */
         DEB_INTR(printk("unsuccessful selection\n"));
         cli();
         hostdata->dma_busy = 0;
	 LIST(hostdata->sel_cmd, hostdata->issue_queue);
	 hostdata->sel_cmd->host_scribble = (unsigned char *)hostdata->issue_queue;
         hostdata->issue_queue = hostdata->sel_cmd;
         hostdata->sel_cmd = NULL;
         hostdata->selecting = 0;
         sti();
         goto EXIT; }
        else {
         /* SUCCESSFUL SELECTION */
         DEB(printk("successful selection; cmd=0x%02lx\n", (long)hostdata->sel_cmd));
         cli();
         hostdata->dma_busy = 0;
         hostdata->disconnecting = 0;
         hostdata->connected = hostdata->sel_cmd;
         hostdata->sel_cmd = NULL;
         hostdata->selecting = 0;
#ifdef SCSI2
         if (!hostdata->connected->device->tagged_queue)
#endif    
            hostdata->busy[hostdata->connected->target] |= (1 << hostdata->connected->lun);
         /* very strange -- use_sg is sometimes nonzero for request sense commands !! */
         if ((hostdata->connected->cmnd[0] == REQUEST_SENSE) && hostdata->connected->use_sg) {
            DEB(printk("scsi%d: REQUEST_SENSE command with nonzero use_sg\n", instance->host_no));
            KEYWAIT();
            hostdata->connected->use_sg = 0; }
         initialize_SCp((Scsi_Cmnd *)hostdata->connected);
         hostdata->connected->SCp.phase = PHASE_CMDOUT;
         AM53C974_information_transfer(instance, statreg, isreg, instreg, cfifo, dmastatus);
         sti();
         return; }
      }
     else {
      cli();
      AM53C974_information_transfer(instance, statreg, isreg, instreg, cfifo, dmastatus);
      sti();
      return; }
   }
    
if (instreg & INSTREG_SR) {
   DEB_INTR(printk("Service request interrupt received, "));
   if (hostdata->connected) {
      DEB_INTR(printk("calling information_transfer\n"));
      cli();
      AM53C974_information_transfer(instance, statreg, isreg, instreg, cfifo, dmastatus);
      sti(); }
     else {
      printk("scsi%d: weird: service request when no command connected\n", instance->host_no);
      AM53C974_write_8(CMDREG, CMDREG_CFIFO); }   /* clear FIFO */
   return;
   }

EXIT:
  DEB_INTR(printk("intr: starting main\n"));
  run_main();
  DEB_INTR(printk("end of intr\n"));
}

/************************************************************************** 
* Function : AM53C974_intr_disconnect(struct Scsi_Host *instance)
*
* Purpose : manage target disconnection
*
* Inputs : instance -- which AM53C974
* 
* Returns : nothing
**************************************************************************/
static void AM53C974_intr_disconnect(struct Scsi_Host *instance) 
{
AM53C974_local_declare(); 
struct AM53C974_hostdata *hostdata = (struct AM53C974_hostdata *)instance->hostdata;
Scsi_Cmnd                *cmd;
AM53C974_setio(instance);

if (hostdata->sel_cmd != NULL) {
   /* normal selection timeout, typical for nonexisting targets */
   cmd = (Scsi_Cmnd *)hostdata->sel_cmd;
   DEB_INTR(printk("bad target\n"));
   cmd->result = DID_BAD_TARGET << 16;
   goto EXIT_FINISHED; }

if (!hostdata->connected) {
   /* can happen if controller was reset, a device tried to reconnect,
      failed and disconnects now */
   AM53C974_write_8(CMDREG, CMDREG_CFIFO);
   return; }

if (hostdata->disconnecting) {
   /* target sent disconnect message, so we are prepared */
   cmd = (Scsi_Cmnd *)hostdata->connected;
   AM53C974_set_async(instance, cmd->target);
   DEB_INTR(printk("scsi%d : disc. from cmnd %d for ta %d, lun %d\n",
   	           instance->host_no, cmd->cmnd[0], cmd->target, cmd->lun));
   if (cmd->device->disconnect) {
      /* target wants to reselect later */
      DEB_INTR(printk("ok, re-enabling selection\n"));
      LIST(cmd,hostdata->disconnected_queue);
      cmd->host_scribble = (unsigned char *)hostdata->disconnected_queue;
      hostdata->disconnected_queue = cmd;
      DEB_QUEUE(printk("scsi%d : command for target %d lun %d this %d was moved from connected to"
   	               "  the disconnected_queue\n", instance->host_no, cmd->target,
                        cmd->lun, hostdata->disconnected_queue->SCp.this_residual));
      DEB_QUEUE(AM53C974_print_queues(instance));
      goto EXIT_UNFINISHED; }
     else {
      /* target does not want to reselect later, we are really finished */
#ifdef AM53C974_DEBUG
      if (cmd->cmnd[0] == REQUEST_SENSE) {
        int i;
        printk("Request sense data dump:\n");
        for (i = 0; i < cmd->request_bufflen; i++) {
             printk("%02x ", *((char *)(cmd->request_buffer) + i));
             if (i && !(i % 16)) printk("\n"); }
        printk("\n"); }
#endif
      goto EXIT_FINISHED; } /* !cmd->device->disconnect */
   } /* if (hostdata->disconnecting) */

/* no disconnect message received; unexpected disconnection */
cmd = (Scsi_Cmnd *)hostdata->connected;
if (cmd) {
#ifdef AM53C974_DEBUG
   deb_stop = 1;
#endif
   AM53C974_set_async(instance, cmd->target);
   printk("scsi%d: Unexpected disconnect; phase: %d; target: %d; this_residual: %d; buffers_residual: %d; message: %d\n",
           instance->host_no, cmd->SCp.phase, cmd->target, cmd->SCp.this_residual, cmd->SCp.buffers_residual,
           cmd->SCp.Message);
   printk("cmdreg: 0x%02x; statreg: 0x%02x; isreg: 0x%02x; cfifo: 0x%02x\n",
          AM53C974_read_8(CMDREG), AM53C974_read_8(STATREG), AM53C974_read_8(ISREG),
           AM53C974_read_8(CFIREG) & CFIREG_CF);

    if ((hostdata->last_message[0] == EXTENDED_MESSAGE) && 
        (hostdata->last_message[2] == EXTENDED_SDTR)) {
        /* sync. negotiation was aborted, setup asynchronous transfer with target */
        hostdata->sync_off[cmd->target] = 0; }
   if (hostdata->aborted || hostdata->msgout[0] == ABORT)
      cmd->result = DID_ABORT << 16;
     else
      cmd->result = DID_ERROR << 16;
   goto EXIT_FINISHED; }

EXIT_FINISHED:
hostdata->aborted = 0;
hostdata->msgout[0] = NOP;
hostdata->sel_cmd = NULL;
hostdata->connected = NULL;
hostdata->selecting = 0;
hostdata->disconnecting = 0;
hostdata->dma_busy = 0;
hostdata->busy[cmd->target] &= ~(1 << cmd->lun);
AM53C974_write_8(CMDREG, CMDREG_CFIFO);
DEB(printk("disconnect; issue_queue: 0x%lx, disconnected_queue: 0x%lx\n", 
       (long)hostdata->issue_queue, (long)hostdata->disconnected_queue));
cmd->scsi_done(cmd);

if (!hostdata->selecting) {
   AM53C974_set_async(instance, cmd->target); 
   AM53C974_write_8(CMDREG, CMDREG_ESR); } /* allow reselect */
return;

EXIT_UNFINISHED:
hostdata->msgout[0] = NOP;
hostdata->sel_cmd = NULL;
hostdata->connected = NULL;
hostdata->aborted = 0;
hostdata->selecting = 0;
hostdata->disconnecting = 0;
hostdata->dma_busy = 0;
DEB(printk("disconnect; issue_queue: 0x%lx, disconnected_queue: 0x%lx\n", 
       (long)hostdata->issue_queue, (long)hostdata->disconnected_queue));
if (!hostdata->selecting) {
   AM53C974_set_async(instance, cmd->target); 
   AM53C974_write_8(CMDREG, CMDREG_ESR); } /* allow reselect */
return;
}

/************************************************************************** 
* Function : int AM53C974_sync_neg(struct Scsi_Host *instance, int target, unsigned char *msg)
*
* Purpose : setup message string for sync. negotiation
*
* Inputs : instance -- which AM53C974
*          target -- which SCSI target to deal with
*          msg -- input message string
* 
* Returns : 0 if parameters accepted or 1 if not accepted
*
* Side effects: hostdata is changed
*
* Note: we assume here that fastclk is enabled
**************************************************************************/
static int AM53C974_sync_neg(struct Scsi_Host *instance, int target, unsigned char *msg) 
{
AM53C974_local_declare(); 
struct AM53C974_hostdata *hostdata = (struct AM53C974_hostdata *)instance->hostdata;
int                      period, offset, i, rate, rate_rem;
AM53C974_setio(instance);

period = (DEF_CLK * msg[3] * 8 + 1000) / 2000;
if (period < MIN_PERIOD) {
    period = MIN_PERIOD;
    hostdata->msgout[3] = period / 4; }
   else
    if (period > MAX_PERIOD) {
       period = MAX_PERIOD;
       hostdata->msgout[3] = period / 4; }
      else
       hostdata->msgout[3] = msg[3];
offset = msg[4]; 
if (offset > MAX_OFFSET) offset = MAX_OFFSET;
hostdata->msgout[4] = offset;
hostdata->sync_per[target] = period;
hostdata->sync_off[target] = offset;
for (i = 0; i < 3; i++) hostdata->msgout[i] = msg[i];
if ((hostdata->msgout[3] != msg[3]) || (msg[4] != offset)) return(1);

rate = DEF_CLK / period;
rate_rem = 10 * (DEF_CLK - period * rate) / period;

if (offset)
   printk("\ntarget %d: rate=%d.%d Mhz, synchronous, sync offset=%d bytes\n",
          target, rate, rate_rem, offset);
  else
   printk("\ntarget %d: rate=%d.%d Mhz, asynchronous\n", target, rate, rate_rem);

return(0);
}

/************************************************************************** 
* Function : AM53C974_set_async(struct Scsi_Host *instance, int target)
*
* Purpose : put controller into async. mode
*
* Inputs : instance -- which AM53C974
*          target -- which SCSI target to deal with
* 
* Returns : nothing
**************************************************************************/
static __inline__ void AM53C974_set_async(struct Scsi_Host *instance, int target)
{
AM53C974_local_declare(); 
struct AM53C974_hostdata *hostdata = (struct AM53C974_hostdata *)instance->hostdata;
AM53C974_setio(instance);

AM53C974_write_8(STPREG, hostdata->sync_per[target]);
AM53C974_write_8(SOFREG, (DEF_SOF_RAD<<6) | (DEF_SOF_RAA<<4));
}

/************************************************************************** 
* Function : AM53C974_set_sync(struct Scsi_Host *instance, int target)
*
* Purpose : put controller into sync. mode
*
* Inputs : instance -- which AM53C974
*          target -- which SCSI target to deal with
* 
* Returns : nothing
**************************************************************************/
static __inline__ void AM53C974_set_sync(struct Scsi_Host *instance, int target)
{
AM53C974_local_declare(); 
struct AM53C974_hostdata *hostdata = (struct AM53C974_hostdata *)instance->hostdata;
AM53C974_setio(instance);

AM53C974_write_8(STPREG, hostdata->sync_per[target]);
AM53C974_write_8(SOFREG, (SOFREG_SO & hostdata->sync_off[target]) | 
                (DEF_SOF_RAD<<6) | (DEF_SOF_RAA<<4));
}

/***********************************************************************
* Function : AM53C974_information_transfer(struct Scsi_Host *instance, *
*                          unsigned char statreg, unsigned char isreg, *
*                         unsigned char instreg, unsigned char cfifo,  *
*                         unsigned char dmastatus)                     *
*                                                                      *
* Purpose : handle phase changes                                       *
*                                                                      *
* Inputs : instance - which AM53C974                                   *
*          statreg - status register                                     *
*          isreg - internal state register                             *
*          instreg - interrupt status register                         *
*          cfifo - number of bytes in FIFO                             *
*          dmastatus - dma status register                             *
*                                                                      *
* Returns : nothing                                                    *
************************************************************************/
static void AM53C974_information_transfer(struct Scsi_Host *instance, 
                                          unsigned char statreg, unsigned char isreg,
                                          unsigned char instreg, unsigned char cfifo,
                                          unsigned char dmastatus)
{
AM53C974_local_declare(); 
struct AM53C974_hostdata *hostdata = (struct AM53C974_hostdata *)instance->hostdata;
Scsi_Cmnd                *cmd = (Scsi_Cmnd *)hostdata->connected;
int                      ret, i, len, residual=-1;
AM53C974_setio(instance);

DEB_INFO(printk(SEPARATOR_LINE));
switch (statreg & STATREG_PHASE) {	/* scsi phase */
  case PHASE_DATAOUT:
    DEB_INFO(printk("Dataout phase; cmd=0x%lx, sel_cmd=0x%lx, this_residual=%d, buffers_residual=%d\n",
                    (long)hostdata->connected, (long)hostdata->sel_cmd, cmd->SCp.this_residual, cmd->SCp.buffers_residual));
    cmd->SCp.phase = PHASE_DATAOUT;
    goto PHASE_DATA_IO;

  case PHASE_DATAIN:
    DEB_INFO(printk("Datain phase; cmd=0x%lx, sel_cmd=0x%lx, this_residual=%d, buffers_residual=%d\n",
                     (long)hostdata->connected, (long)hostdata->sel_cmd, cmd->SCp.this_residual, cmd->SCp.buffers_residual));
    cmd->SCp.phase = PHASE_DATAIN;
    PHASE_DATA_IO:
    if (hostdata->aborted) {
       AM53C974_write_8(DMACMD, DMACMD_IDLE);
       AM53C974_write_8(CMDREG, CMDREG_CFIFO);
       AM53C974_write_8(CMDREG, CMDREG_SATN);
       return; }
    if ((!cmd->SCp.this_residual) && cmd->SCp.buffers_residual) {
       cmd->SCp.buffer++;
       cmd->SCp.buffers_residual--;
       cmd->SCp.ptr = (unsigned char *)cmd->SCp.buffer->address;
       cmd->SCp.this_residual = cmd->SCp.buffer->length; }
    if (cmd->SCp.this_residual) {
       if (!(AM53C974_read_8(DMACMD) & DMACMD_START)) {
          hostdata->dma_busy = 0;
          AM53C974_transfer_dma(instance, statreg & STATREG_IO,
                                (unsigned long)cmd->SCp.this_residual,
                                cmd->SCp.ptr); }
         else
          hostdata->dma_busy = 1;
       }
    return;

  case PHASE_MSGIN:
    DEB_INFO(printk("Message-In phase; cmd=0x%lx, sel_cmd=0x%lx\n",
                    (long)hostdata->connected, (long)hostdata->sel_cmd));
    AM53C974_set_async(instance, cmd->target);
    if (cmd->SCp.phase == PHASE_DATAIN)
       AM53C974_dma_blast(instance, dmastatus, statreg);
    if ((cmd->SCp.phase == PHASE_DATAOUT) && (AM53C974_read_8(DMACMD) & DMACMD_START)) {
       AM53C974_write_8(DMACMD, DMACMD_IDLE);
       residual = cfifo + (AM53C974_read_8(CTCLREG) | (AM53C974_read_8(CTCMREG) << 8) |
                          (AM53C974_read_8(CTCHREG) << 16));
       cmd->SCp.ptr += cmd->SCp.this_residual - residual;
       cmd->SCp.this_residual = residual;
       if (cfifo) { AM53C974_write_8(CMDREG, CMDREG_CFIFO); cfifo = 0; }
       }
    if (cmd->SCp.phase == PHASE_STATIN) {
       while ((AM53C974_read_8(CFIREG) & CFIREG_CF) < 2) ;
       cmd->SCp.Status = AM53C974_read_8(FFREG);
       cmd->SCp.Message = AM53C974_read_8(FFREG); 
       DEB_INFO(printk("Message-In phase; status=0x%02x, message=0x%02x\n",
                       cmd->SCp.Status, cmd->SCp.Message));
       ret = AM53C974_message(instance, cmd, cmd->SCp.Message); }
      else {
       if (!cfifo) {
          AM53C974_write_8(CMDREG, CMDREG_IT); 
          AM53C974_poll_int();
          cmd->SCp.Message = AM53C974_read_8(FFREG);
          }
       ret = AM53C974_message(instance, cmd, cmd->SCp.Message);
       }
    cmd->SCp.phase = PHASE_MSGIN;
    AM53C974_set_sync(instance, cmd->target);
    break;
  case PHASE_MSGOUT:
    DEB_INFO(printk("Message-Out phase; cfifo=%d; msgout[0]=0x%02x\n",
                    AM53C974_read_8(CFIREG) & CFIREG_CF, hostdata->msgout[0]));
    AM53C974_write_8(DMACMD, DMACMD_IDLE);
    AM53C974_set_async(instance, cmd->target);
    for (i = 0; i < sizeof(hostdata->last_message); i++) 
        hostdata->last_message[i] = hostdata->msgout[i];
    if ((hostdata->msgout[0] == 0) || INSIDE(hostdata->msgout[0], 0x02, 0x1F) || 
        INSIDE(hostdata->msgout[0], 0x80, 0xFF)) 
       len = 1;
      else {
       if (hostdata->msgout[0] == EXTENDED_MESSAGE) {
#ifdef AM53C974_DEBUG_INFO
          printk("Extended message dump:\n");
          for (i = 0; i < hostdata->msgout[1] + 2; i++) {
              printk("%02x ", hostdata->msgout[i]);
              if (i && !(i % 16)) printk("\n"); }
          printk("\n");
#endif
          len = hostdata->msgout[1] + 2; }
         else
          len = 2;
       }
    for (i = 0; i < len; i++) AM53C974_write_8(FFREG, hostdata->msgout[i]);
    AM53C974_write_8(CMDREG, CMDREG_IT);
    cmd->SCp.phase = PHASE_MSGOUT;
    hostdata->msgout[0] = NOP;
    AM53C974_set_sync(instance, cmd->target);
    break;

  case PHASE_CMDOUT:
    DEB_INFO(printk("Command-Out phase\n"));
    AM53C974_set_async(instance, cmd->target);
    for (i = 0; i < cmd->cmd_len; i++) AM53C974_write_8(FFREG, cmd->cmnd[i]);
    AM53C974_write_8(CMDREG, CMDREG_IT);
    cmd->SCp.phase = PHASE_CMDOUT;
    AM53C974_set_sync(instance, cmd->target);
    break;

  case PHASE_STATIN:
    DEB_INFO(printk("Status phase\n"));
    if (cmd->SCp.phase == PHASE_DATAIN)
       AM53C974_dma_blast(instance, dmastatus, statreg);
    AM53C974_set_async(instance, cmd->target);
    if (cmd->SCp.phase == PHASE_DATAOUT) {
       unsigned long residual;

       if (AM53C974_read_8(DMACMD) & DMACMD_START) {
          AM53C974_write_8(DMACMD, DMACMD_IDLE);
          residual = cfifo + (AM53C974_read_8(CTCLREG) | (AM53C974_read_8(CTCMREG) << 8) |
                              (AM53C974_read_8(CTCHREG) << 16));
          cmd->SCp.ptr += cmd->SCp.this_residual - residual;
          cmd->SCp.this_residual = residual; }
       if (cfifo) { AM53C974_write_8(CMDREG, CMDREG_CFIFO); cfifo = 0; }
       }
    cmd->SCp.phase = PHASE_STATIN;
    AM53C974_write_8(CMDREG, CMDREG_ICCS);  /* command complete */
    break;

  case PHASE_RES_0:
  case PHASE_RES_1:
#ifdef AM53C974_DEBUG
   deb_stop = 1;
#endif
    DEB_INFO(printk("Reserved phase\n"));
    break;
  }
KEYWAIT();
}

/******************************************************************************
* Function : int AM53C974_message(struct Scsi_Host *instance, Scsi_Cmnd *cmd,
*                                 unsigned char msg)                
*
* Purpose : handle SCSI messages
*
* Inputs : instance -- which AM53C974
*          cmd -- SCSI command the message belongs to
*          msg -- message id byte
* 
* Returns : 1 on success, 0 on failure.
**************************************************************************/
static int AM53C974_message(struct Scsi_Host *instance, Scsi_Cmnd *cmd,
                            unsigned char msg)
{
AM53C974_local_declare(); 
static unsigned char     extended_msg[10];
unsigned char            statreg;
int                      len, ret = 0;
unsigned char            *p;
#ifdef AM53C974_DEBUG_MSG
int                      j;
#endif
struct AM53C974_hostdata *hostdata = (struct AM53C974_hostdata *)instance->hostdata;
AM53C974_setio(instance);

DEB_MSG(printk(SEPARATOR_LINE));

/* Linking lets us reduce the time required to get the 
 * next command out to the device, hopefully this will
 * mean we don't waste another revolution due to the delays
 * required by ARBITRATION and another SELECTION.
 * In the current implementation proposal, low level drivers
 * merely have to start the next command, pointed to by 
 * next_link, done() is called as with unlinked commands. */
switch (msg) {
#ifdef LINKED
  case LINKED_CMD_COMPLETE:
  case LINKED_FLG_CMD_COMPLETE:
    /* Accept message by releasing ACK */
    DEB_LINKED(printk("scsi%d : target %d lun %d linked command complete.\n",
			instance->host_no, cmd->target, cmd->lun));
    /* Sanity check : A linked command should only terminate with
     * one of these messages if there are more linked commands available. */
    if (!cmd->next_link) {
       printk("scsi%d : target %d lun %d linked command complete, no next_link\n"
	       instance->host_no, cmd->target, cmd->lun);
       hostdata->aborted = 1;
       AM53C974_write_8(CMDREG, CMDREG_SATN);
       AM53C974_write_8(CMDREG, CMDREG_MA);
       break; }
    if (hostdata->aborted) {
       DEB_ABORT(printk("ATN set for cmnd %d upon reception of LINKED_CMD_COMPLETE or"
                        "LINKED_FLG_CMD_COMPLETE message\n", cmd->cmnd[0]));
       AM53C974_write_8(CMDREG, CMDREG_SATN); }
    AM53C974_write_8(CMDREG, CMDREG_MA);

    initialize_SCp(cmd->next_link);
    /* The next command is still part of this process */
    cmd->next_link->tag = cmd->tag;
    cmd->result = cmd->SCp.Status | (cmd->SCp.Message << 8); 
    DEB_LINKED(printk("scsi%d : target %d lun %d linked request done, calling scsi_done().\n",
		      instance->host_no, cmd->target, cmd->lun));
    cmd->scsi_done(cmd);
    cmd = hostdata->connected;
    break;

#endif /* def LINKED */

  case ABORT:
  case COMMAND_COMPLETE: 
    DEB_MSG(printk("scsi%d: command complete message received; cmd %d for target %d, lun %d\n",
	           instance->host_no, cmd->cmnd[0], cmd->target, cmd->lun));
    hostdata->disconnecting = 1;
    cmd->device->disconnect = 0;

    /* I'm not sure what the correct thing to do here is : 
     * 
     * If the command that just executed is NOT a request 
     * sense, the obvious thing to do is to set the result
     * code to the values of the stored parameters.
     * If it was a REQUEST SENSE command, we need some way 
     * to differentiate between the failure code of the original
     * and the failure code of the REQUEST sense - the obvious
     * case is success, where we fall through and leave the result
     * code unchanged.
     * 
     * The non-obvious place is where the REQUEST SENSE failed  */
    if (cmd->cmnd[0] != REQUEST_SENSE) 
       cmd->result = cmd->SCp.Status | (cmd->SCp.Message << 8); 
      else if (cmd->SCp.Status != GOOD)
       cmd->result = (cmd->result & 0x00ffff) | (DID_ERROR << 16);		    
    if (hostdata->aborted) {
       AM53C974_write_8(CMDREG, CMDREG_SATN);
       AM53C974_write_8(CMDREG, CMDREG_MA);
       DEB_ABORT(printk("ATN set for cmnd %d upon reception of ABORT or"
                        "COMMAND_COMPLETE message\n", cmd->cmnd[0]));
       break; }
    if ((cmd->cmnd[0] != REQUEST_SENSE) && (cmd->SCp.Status == CHECK_CONDITION)) {
       DEB_MSG(printk("scsi%d : performing request sense\n", instance->host_no));
       cmd->cmnd[0] = REQUEST_SENSE;
       cmd->cmnd[1] &= 0xe0;
       cmd->cmnd[2] = 0;
       cmd->cmnd[3] = 0;
       cmd->cmnd[4] = sizeof(cmd->sense_buffer);
       cmd->cmnd[5] = 0;
       cmd->SCp.buffer = NULL;
       cmd->SCp.buffers_residual = 0;
       cmd->SCp.ptr = (char *)cmd->sense_buffer;
       cmd->SCp.this_residual = sizeof(cmd->sense_buffer);
       LIST(cmd,hostdata->issue_queue);
       cmd->host_scribble = (unsigned char *)hostdata->issue_queue;
       hostdata->issue_queue = (Scsi_Cmnd *)cmd;
       DEB_MSG(printk("scsi%d : REQUEST SENSE added to head of issue queue\n",instance->host_no));
       }

    /* Accept message by clearing ACK */
    AM53C974_write_8(CMDREG, CMDREG_MA);
    break;
		
  case MESSAGE_REJECT:
    DEB_MSG(printk("scsi%d: reject message received; cmd %d for target %d, lun %d\n",
	           instance->host_no, cmd->cmnd[0], cmd->target, cmd->lun));
    switch (hostdata->last_message[0]) {
      case EXTENDED_MESSAGE:
        if (hostdata->last_message[2] == EXTENDED_SDTR) {
           /* sync. negotiation was rejected, setup asynchronous transfer with target */
           printk("\ntarget %d: rate=%d Mhz, asynchronous (sync. negotiation rejected)\n",
                  cmd->target,  DEF_CLK / DEF_STP);
           hostdata->sync_off[cmd->target] = 0;
           hostdata->sync_per[cmd->target] = DEF_STP; }
        break;
      case HEAD_OF_QUEUE_TAG:
      case ORDERED_QUEUE_TAG:
      case SIMPLE_QUEUE_TAG:
        cmd->device->tagged_queue = 0;
        hostdata->busy[cmd->target] |= (1 << cmd->lun);
        break;
      default:
        break;
      }
    if (hostdata->aborted) AM53C974_write_8(CMDREG, CMDREG_SATN);
    AM53C974_write_8(CMDREG, CMDREG_MA);
    break;
	
  case DISCONNECT:
    DEB_MSG(printk("scsi%d: disconnect message received; cmd %d for target %d, lun %d\n",
	           instance->host_no, cmd->cmnd[0], cmd->target, cmd->lun));
    cmd->device->disconnect = 1;
    hostdata->disconnecting = 1;
    AM53C974_write_8(CMDREG, CMDREG_MA); /* Accept message by clearing ACK */
    break;
		
  case SAVE_POINTERS:
  case RESTORE_POINTERS:
    DEB_MSG(printk("scsi%d: save/restore pointers message received; cmd %d for target %d, lun %d\n",
	           instance->host_no, cmd->cmnd[0], cmd->target, cmd->lun));
    /* The SCSI data pointer is *IMPLICITLY* saved on a disconnect
     * operation, in violation of the SCSI spec so we can safely 
     * ignore SAVE/RESTORE pointers calls.
     *
     * Unfortunately, some disks violate the SCSI spec and 
     * don't issue the required SAVE_POINTERS message before
     * disconnecting, and we have to break spec to remain 
     * compatible. */
    if (hostdata->aborted) {
       DEB_ABORT(printk("ATN set for cmnd %d upon reception of SAVE/REST. POINTERS message\n",
                         cmd->cmnd[0]));
       AM53C974_write_8(CMDREG, CMDREG_SATN); }
    AM53C974_write_8(CMDREG, CMDREG_MA);
    break;

  case EXTENDED_MESSAGE:
    DEB_MSG(printk("scsi%d: extended message received; cmd %d for target %d, lun %d\n",
	           instance->host_no, cmd->cmnd[0], cmd->target, cmd->lun));
   /* Extended messages are sent in the following format :
    * Byte 	
    * 0		  EXTENDED_MESSAGE == 1
    * 1		  length (includes one byte for code, doesn't include first two bytes)
    * 2 	  code
    * 3..length+1 arguments
    */
   /* BEWARE!! THIS CODE IS EXTREMELY UGLY */
    extended_msg[0] = EXTENDED_MESSAGE;
    AM53C974_read_8(INSTREG) ; /* clear int */
    AM53C974_write_8(CMDREG, CMDREG_MA);  /* ack. msg byte, then wait for SO */  
    AM53C974_poll_int();
    /* get length */
    AM53C974_write_8(CMDREG, CMDREG_IT); 
    AM53C974_poll_int();
    AM53C974_write_8(CMDREG, CMDREG_MA);  /* ack. msg byte, then wait for SO */   
    AM53C974_poll_int();
    extended_msg[1] = len = AM53C974_read_8(FFREG); /* get length */
    p = extended_msg+2;
    /* read the remaining (len) bytes */
    while (len) {
      AM53C974_write_8(CMDREG, CMDREG_IT); 
      AM53C974_poll_int();
      if (len > 1) {
         AM53C974_write_8(CMDREG, CMDREG_MA);  /* ack. msg byte, then wait for SO */   
         AM53C974_poll_int(); }
      *p = AM53C974_read_8(FFREG);
      p++; len--; }

#ifdef AM53C974_DEBUG_MSG
    printk("scsi%d: received extended message: ", instance->host_no);
    for (j = 0; j < extended_msg[1] + 2; j++) {
        printk("0x%02x ", extended_msg[j]);
        if (j && !(j % 16)) printk("\n"); }
    printk("\n");
#endif

    /* check message */
    if (extended_msg[2] == EXTENDED_SDTR)
       ret = AM53C974_sync_neg(instance, cmd->target, extended_msg);
    if (ret || hostdata->aborted) AM53C974_write_8(CMDREG, CMDREG_SATN);

    AM53C974_write_8(CMDREG, CMDREG_MA); 
    break;

  default:
    printk("scsi%d: unknown message 0x%02x received\n",instance->host_no, msg);
#ifdef AM53C974_DEBUG
   deb_stop = 1;
#endif
    /* reject message */
    hostdata->msgout[0] = MESSAGE_REJECT; 
    AM53C974_write_8(CMDREG, CMDREG_SATN);
    AM53C974_write_8(CMDREG, CMDREG_MA);
    return(0);
    break;

  } /* switch (msg) */
KEYWAIT();
return(1);
}

/************************************************************************** 
* Function : AM53C974_select(struct Scsi_Host *instance, Scsi_Cmnd *cmd, int tag)
*
* Purpose : try to establish nexus for the command;
*           start sync negotiation via start stop and transfer the command in 
*           cmdout phase in case of an inquiry or req. sense command with no 
*           sync. neg. performed yet
*
* Inputs : instance -- which AM53C974
*          cmd -- command which requires the selection
*          tag -- tagged queueing
* 
* Returns : nothing
*        
* Note: this function initializes the selection process, which is continued 
*       in the interrupt handler
**************************************************************************/
static void AM53C974_select(struct Scsi_Host *instance, Scsi_Cmnd *cmd, int tag)
{
AM53C974_local_declare(); 
struct AM53C974_hostdata *hostdata = (struct AM53C974_hostdata *)instance->hostdata;
unsigned char            cfifo, tmp[3];
unsigned int             i, len, cmd_size = COMMAND_SIZE(cmd->cmnd[0]);
AM53C974_setio(instance);

cfifo = AM53C974_cfifo();
if (cfifo) {
   printk("scsi%d: select error; %d residual bytes in FIFO\n", instance->host_no, cfifo);
   AM53C974_write_8(CMDREG, CMDREG_CFIFO); /* clear FIFO */
   }                  

tmp[0] = IDENTIFY(1, cmd->lun);

#ifdef SCSI2
if (cmd->device->tagged_queue && (tag != TAG_NONE)) {
   tmp[1] = SIMPLE_QUEUE_TAG;
   if (tag == TAG_NEXT) {
      /* 0 is TAG_NONE, used to imply no tag for this command */
      if (cmd->device->current_tag == 0) cmd->device->current_tag = 1;
      cmd->tag = cmd->device->current_tag;
      cmd->device->current_tag++; }
     else  
      cmd->tag = (unsigned char)tag;
   tmp[2] = cmd->tag;
   hostdata->last_message[0] = SIMPLE_QUEUE_TAG;
   len = 3;
   AM53C974_write_8(FFREG, tmp[0]);
   AM53C974_write_8(FFREG, tmp[1]);
   AM53C974_write_8(FFREG, tmp[2]);
   }
  else
#endif /* def SCSI2 */
   {
   len = 1;
   AM53C974_write_8(FFREG, tmp[0]);
   cmd->tag = 0; }

/* in case of an inquiry or req. sense command with no sync. neg performed yet, we start
   sync negotiation via start stops and transfer the command in cmdout phase */
if (((cmd->cmnd[0] == INQUIRY) || (cmd->cmnd[0] == REQUEST_SENSE)) &&
    !(hostdata->sync_neg[cmd->target]) && hostdata->sync_en[cmd->target]) {
   hostdata->sync_neg[cmd->target] = 1;
   hostdata->msgout[0] = EXTENDED_MESSAGE;
   hostdata->msgout[1] = 3;
   hostdata->msgout[2] = EXTENDED_SDTR;
   hostdata->msgout[3] = 250 / (int)hostdata->max_rate[cmd->target];
   hostdata->msgout[4] = hostdata->max_offset[cmd->target];
   len += 5; }

AM53C974_write_8(SDIDREG, SDIREG_MASK & cmd->target);       /* setup dest. id  */
AM53C974_write_8(STIMREG, DEF_SCSI_TIMEOUT);                /* setup timeout reg */
switch (len) {
  case 1:
   for (i = 0; i < cmd_size; i++) AM53C974_write_8(FFREG, cmd->cmnd[i]);
   AM53C974_write_8(CMDREG, CMDREG_SAS);                    /* select with ATN, 1 msg byte */
   hostdata->msgout[0] = NOP;
   break;
  case 3:
   for (i = 0; i < cmd_size; i++) AM53C974_write_8(FFREG, cmd->cmnd[i]);
   AM53C974_write_8(CMDREG, CMDREG_SA3S);                   /* select with ATN, 3 msg bytes */
   hostdata->msgout[0] = NOP;
   break;
  default:
   AM53C974_write_8(CMDREG, CMDREG_SASS);   /* select with ATN, stop steps; continue in message out phase */
   break;
  }
}

/************************************************************************** 
* Function : AM53C974_intr_select(struct Scsi_Host *instance, unsigned char statreg)
*
* Purpose : handle reselection 
*
* Inputs : instance -- which AM53C974
*          statreg -- status register
* 
* Returns : nothing
*
* side effects: manipulates hostdata
**************************************************************************/
static void AM53C974_intr_reselect(struct Scsi_Host *instance, unsigned char statreg)
{
AM53C974_local_declare(); 
struct AM53C974_hostdata *hostdata = (struct AM53C974_hostdata *)instance->hostdata;
unsigned char            cfifo, msg[3], lun, t, target = 0;
#ifdef SCSI2
 unsigned                char tag;
#endif
Scsi_Cmnd                *tmp = NULL, *prev;
AM53C974_setio(instance);

cfifo = AM53C974_cfifo();

if (hostdata->selecting) {
   /* caught reselect interrupt in selection process;
      put selecting command back into the issue queue and continue with the
      reselecting command */
   DEB_RESEL(printk("AM53C974_intr_reselect: in selection process\n"));
   LIST(hostdata->sel_cmd, hostdata->issue_queue);
   hostdata->sel_cmd->host_scribble = (unsigned char *)hostdata->issue_queue;
   hostdata->issue_queue = hostdata->sel_cmd;
   hostdata->sel_cmd = NULL;
   hostdata->selecting = 0; }

/* 2 bytes must be in the FIFO now */
if (cfifo != 2) {
   printk("scsi %d: error: %d bytes in fifo, 2 expected\n", instance->host_no, cfifo);
   hostdata->aborted = 1;
   goto EXIT_ABORT; }

/* determine target which reselected */
t = AM53C974_read_8(FFREG);
if (!(t & (1 << instance->this_id))) {
   printk("scsi %d: error: invalid host id\n", instance->host_no);
   hostdata->aborted = 1;
   goto EXIT_ABORT; }
t ^= (1 << instance->this_id);
target = 0; while (t != 1) { t >>= 1; target++; }
DEB_RESEL(printk("scsi %d: reselect; target: %d\n", instance->host_no, target));
      
if (hostdata->aborted) goto EXIT_ABORT;

if ((statreg & STATREG_PHASE) != PHASE_MSGIN) {
   printk("scsi %d: error: upon reselection interrupt not in MSGIN\n", instance->host_no);
   hostdata->aborted = 1;
   goto EXIT_ABORT; }

msg[0] = AM53C974_read_8(FFREG);
if (!msg[0] & 0x80) {
   printk("scsi%d: error: expecting IDENTIFY message, got ", instance->host_no);
   print_msg(msg);
   hostdata->aborted = 1;
   goto EXIT_ABORT; }

lun = (msg[0] & 0x07);

/* We need to add code for SCSI-II to track which devices have
 * I_T_L_Q nexuses established, and which have simple I_T_L
 * nexuses so we can chose to do additional data transfer. */
#ifdef SCSI2
#error "SCSI-II tagged queueing is not supported yet"
#endif

/* Find the command corresponding to the I_T_L or I_T_L_Q  nexus we 
 * just reestablished, and remove it from the disconnected queue. */
for (tmp = (Scsi_Cmnd *)hostdata->disconnected_queue, prev = NULL; 
     tmp; prev = tmp, tmp = (Scsi_Cmnd *)tmp->host_scribble) 
    if ((target == tmp->target) && (lun == tmp->lun) 
#ifdef SCSI2
         && (tag == tmp->tag) 
#endif
       ) {
       if (prev) {
	  REMOVE(prev, (Scsi_Cmnd *)(prev->host_scribble), tmp,
                 (Scsi_Cmnd *)(tmp->host_scribble));
	  prev->host_scribble = tmp->host_scribble; } 
         else {
	  REMOVE(-1, hostdata->disconnected_queue, tmp, tmp->host_scribble);
	  hostdata->disconnected_queue = (Scsi_Cmnd *)tmp->host_scribble; }
       tmp->host_scribble = NULL;
       hostdata->connected = tmp;
       break; }

if (!tmp) {
#ifdef SCSI2
   printk("scsi%d: warning : target %d lun %d tag %d not in disconnect_queue.\n",
         instance->host_no, target, lun, tag);
#else
   printk("scsi%d: warning : target %d lun %d not in disconnect_queue.\n",
         instance->host_no, target, lun);
#endif
   /* Since we have an established nexus that we can't do anything with, we must abort it. */
   hostdata->aborted = 1;
   DEB(AM53C974_keywait());
   goto EXIT_ABORT; }
  else
   goto EXIT_OK;

EXIT_ABORT: 
AM53C974_write_8(CMDREG, CMDREG_SATN);
AM53C974_write_8(CMDREG, CMDREG_MA);
return;

EXIT_OK:
DEB_RESEL(printk("scsi%d: nexus established, target = %d, lun = %d, tag = %d\n",
	  instance->host_no, target, tmp->lun, tmp->tag));
AM53C974_set_sync(instance, target);
AM53C974_write_8(SDIDREG, SDIREG_MASK & target);       /* setup dest. id  */
AM53C974_write_8(CMDREG, CMDREG_MA);
hostdata->dma_busy = 0;
hostdata->connected->SCp.phase = PHASE_CMDOUT;
}

/************************************************************************** 
* Function : AM53C974_transfer_dma(struct Scsi_Host *instance, short dir,
*                                  unsigned long length, char *data)
*
* Purpose : setup DMA transfer
*
* Inputs : instance -- which AM53C974
*          dir -- direction flag, 0: write to device, read from memory; 
*                                 1: read from device, write to memory
*          length -- number of bytes to transfer to from buffer
*          data -- pointer to data buffer
* 
* Returns : nothing
**************************************************************************/
static __inline__ void AM53C974_transfer_dma(struct Scsi_Host *instance, short dir,
                                             unsigned long length, char *data)
{
AM53C974_local_declare();
AM53C974_setio(instance);

AM53C974_write_8(CMDREG, CMDREG_NOP);
AM53C974_write_8(DMACMD, (dir << 7) | DMACMD_INTE_D);  /* idle command */
AM53C974_write_8(STCLREG, (unsigned char)(length & 0xff));
AM53C974_write_8(STCMREG, (unsigned char)((length & 0xff00) >> 8));
AM53C974_write_8(STCHREG, (unsigned char)((length & 0xff0000) >> 16));
AM53C974_write_32(DMASTC, length & 0xffffff);
AM53C974_write_32(DMASPA, virt_to_bus(data));
AM53C974_write_8(CMDREG, CMDREG_IT | CMDREG_DMA);
AM53C974_write_8(DMACMD, (dir << 7) | DMACMD_INTE_D | DMACMD_START);
}

/************************************************************************** 
* Function : AM53C974_dma_blast(struct Scsi_Host *instance, unsigned char dmastatus,
*                               unsigned char statreg)
*
* Purpose : cleanup DMA transfer
*
* Inputs : instance -- which AM53C974
*          dmastatus -- dma status register
*          statreg -- status register
* 
* Returns : nothing
**************************************************************************/
static void AM53C974_dma_blast(struct Scsi_Host *instance, unsigned char dmastatus,
                               unsigned char statreg)
{
AM53C974_local_declare();
struct AM53C974_hostdata *hostdata = (struct AM53C974_hostdata *)instance->hostdata;
unsigned long            ctcreg;
int                      dir = statreg & STATREG_IO;
int                      cfifo, pio, i = 0;
AM53C974_setio(instance);

do {
   cfifo = AM53C974_cfifo();
   i++;
   } while (cfifo && (i < 50000));
pio = (i == 50000) ? 1: 0;

if (statreg & STATREG_CTZ) { AM53C974_write_8(DMACMD, DMACMD_IDLE); return; }

if (dmastatus & DMASTATUS_DONE) { AM53C974_write_8(DMACMD, DMACMD_IDLE); return; }

AM53C974_write_8(DMACMD, ((dir << 7) & DMACMD_DIR) | DMACMD_BLAST);
while(!(AM53C974_read_8(DMASTATUS) & DMASTATUS_BCMPLT)) ;
AM53C974_write_8(DMACMD, DMACMD_IDLE);

if (pio) {
   /* transfer residual bytes via PIO */
   unsigned char *wac = (unsigned char *)AM53C974_read_32(DMAWAC);
   printk("pio mode, residual=%d\n", AM53C974_read_8(CFIREG) & CFIREG_CF);
   while (AM53C974_read_8(CFIREG) & CFIREG_CF) *(wac++) = AM53C974_read_8(FFREG);
   }

ctcreg = AM53C974_read_8(CTCLREG) | (AM53C974_read_8(CTCMREG) << 8) |
         (AM53C974_read_8(CTCHREG) << 16);

hostdata->connected->SCp.ptr += hostdata->connected->SCp.this_residual - ctcreg;
hostdata->connected->SCp.this_residual = ctcreg;
}

/************************************************************************** 
* Function : AM53C974_intr_bus_reset(struct Scsi_Host *instance)
*
* Purpose : handle bus reset interrupt
*
* Inputs : instance -- which AM53C974
* 
* Returns : nothing
**************************************************************************/
static void AM53C974_intr_bus_reset(struct Scsi_Host *instance)
{
AM53C974_local_declare();
unsigned char cntlreg1;
AM53C974_setio(instance);

AM53C974_write_8(CMDREG, CMDREG_CFIFO);
AM53C974_write_8(CMDREG, CMDREG_NOP);

cntlreg1 = AM53C974_read_8(CNTLREG1);
AM53C974_write_8(CNTLREG1, cntlreg1 | CNTLREG1_DISR);
}

/**************************************************************************
* Function : int AM53C974_abort(Scsi_Cmnd *cmd)
*
* Purpose : abort a command
*
* Inputs : cmd - the Scsi_Cmnd to abort, code - code to set the 
* 	host byte of the result field to, if zero DID_ABORTED is 
*	used.
*
* Returns : 0 - success, -1 on failure.
 **************************************************************************/
int AM53C974_abort(Scsi_Cmnd *cmd)
{
AM53C974_local_declare();
struct Scsi_Host         *instance = cmd->host;
struct AM53C974_hostdata *hostdata = (struct AM53C974_hostdata *)instance->hostdata;
Scsi_Cmnd                *tmp, **prev;

#ifdef AM53C974_DEBUG
   deb_stop = 1;
#endif
cli();
AM53C974_setio(instance);

DEB_ABORT(printk(SEPARATOR_LINE));
DEB_ABORT(printk("scsi%d : AM53C974_abort called -- trouble starts!!\n", instance->host_no));
DEB_ABORT(AM53C974_print(instance));
DEB_ABORT(AM53C974_keywait());

/* Case 1 : If the command is the currently executing command, 
            we'll set the aborted flag and return control so that the
            information transfer routine can exit cleanly. */
if ((hostdata->connected == cmd) || (hostdata->sel_cmd == cmd)) {
   DEB_ABORT(printk("scsi%d: aborting connected command\n", instance->host_no));
   hostdata->aborted = 1;
   hostdata->msgout[0] = ABORT;
   sti();
   return(SCSI_ABORT_PENDING); }

/* Case 2 : If the command hasn't been issued yet,
            we simply remove it from the issue queue. */
for (prev = (Scsi_Cmnd **)&(hostdata->issue_queue), 
     tmp = (Scsi_Cmnd *)hostdata->issue_queue; tmp; 
     prev = (Scsi_Cmnd **)&(tmp->host_scribble),
     tmp = (Scsi_Cmnd *)tmp->host_scribble) {
    if (cmd == tmp) {
       DEB_ABORT(printk("scsi%d : abort removed command from issue queue.\n", instance->host_no));
       REMOVE(5, *prev, tmp, tmp->host_scribble);
       (*prev) = (Scsi_Cmnd *)tmp->host_scribble;
       tmp->host_scribble = NULL;
       tmp->result = DID_ABORT << 16;
       sti();
       tmp->done(tmp);
       return(SCSI_ABORT_SUCCESS); }
#ifdef AM53C974_DEBUG_ABORT
      else {
       if (prev == (Scsi_Cmnd **)tmp) 
          printk("scsi%d : LOOP\n", instance->host_no); 
       }
#endif
    }
 
/* Case 3 : If any commands are connected, we're going to fail the abort
 *	    and let the high level SCSI driver retry at a later time or 
 *	    issue a reset.
 *
 *	    Timeouts, and therefore aborted commands, will be highly unlikely
 *          and handling them cleanly in this situation would make the common
 *	    case of noresets less efficient, and would pollute our code.  So,
 *	    we fail. */
if (hostdata->connected || hostdata->sel_cmd) {
   DEB_ABORT(printk("scsi%d : abort failed, other command connected.\n", instance->host_no));
   sti();
   return(SCSI_ABORT_NOT_RUNNING); }

/* Case 4: If the command is currently disconnected from the bus, and 
 * 	   there are no connected commands, we reconnect the I_T_L or 
 *	   I_T_L_Q nexus associated with it, go into message out, and send 
 *         an abort message. */
for (tmp = (Scsi_Cmnd *)hostdata->disconnected_queue; tmp; 
     tmp = (Scsi_Cmnd *)tmp->host_scribble) {
     if (cmd == tmp) {
        DEB_ABORT(printk("scsi%d: aborting disconnected command\n", instance->host_no));
        hostdata->aborted = 1;
        hostdata->msgout[0] = ABORT;
        hostdata->selecting = 1;
        hostdata->sel_cmd = tmp;
        AM53C974_write_8(CMDREG, CMDREG_DSR);
        sti();
        return(SCSI_ABORT_PENDING); }
     }

/* Case 5 : If we reached this point, the command was not found in any of 
 *	    the queues.
 *
 * We probably reached this point because of an unlikely race condition
 * between the command completing successfully and the abortion code,
 * so we won't panic, but we will notify the user in case something really
 * broke. */
DEB_ABORT(printk("scsi%d : abort failed, command not found.\n", instance->host_no));
sti();
return(SCSI_ABORT_NOT_RUNNING);
}

/************************************************************************** 
* Function : int AM53C974_reset(Scsi_Cmnd *cmd)
*
* Purpose : reset the SCSI controller and bus
*
* Inputs : cmd -- which command within the command block was responsible for the reset
* 
* Returns : status (SCSI_ABORT_SUCCESS)
**************************************************************************/
int AM53C974_reset(Scsi_Cmnd *cmd, unsigned int flags)
{
AM53C974_local_declare();
int                      i;
struct Scsi_Host         *instance = cmd->host;
struct AM53C974_hostdata *hostdata = (struct AM53C974_hostdata *)instance->hostdata;
AM53C974_setio(instance);

cli();
DEB(printk("AM53C974_reset called; "));

printk("AM53C974_reset called\n");
AM53C974_print(instance);
AM53C974_keywait();

/* do hard reset */
AM53C974_write_8(CMDREG, CMDREG_RDEV);
AM53C974_write_8(CMDREG, CMDREG_NOP);
hostdata->msgout[0] = NOP;
for (i = 0; i < 8; i++) {
    hostdata->busy[i] = 0;
    hostdata->sync_per[i] = DEF_STP;
    hostdata->sync_off[i] = 0;
    hostdata->sync_neg[i] = 0; }
hostdata->last_message[0] = NOP;
hostdata->sel_cmd = NULL;
hostdata->connected = NULL;
hostdata->issue_queue = NULL;
hostdata->disconnected_queue = NULL;
hostdata->in_reset = 0;
hostdata->aborted = 0;
hostdata->selecting = 0;
hostdata->disconnecting = 0;
hostdata->dma_busy = 0;

/* reset bus */
AM53C974_write_8(CNTLREG1, CNTLREG1_DISR | instance->this_id); /* disable interrupt upon SCSI RESET */
AM53C974_write_8(CMDREG, CMDREG_RBUS);     /* reset SCSI bus */
udelay(40);
AM53C974_config_after_reset(instance);

sti();
cmd->result = DID_RESET << 16;
cmd->scsi_done(cmd);
return SCSI_ABORT_SUCCESS;
}


/*
 * AM53C974_release()
 *
 * Release resources allocated for a single AM53C974 adapter.
 */
int
AM53C974_release(struct Scsi_Host *shp)
{
	free_irq(shp->irq, NULL);
	scsi_unregister(shp);
	return 0;
}


#ifdef MODULE
/* Eventually this will go into an include file, but this will be later */
Scsi_Host_Template driver_template = AM53C974;

#include "scsi_module.c"
#endif