summaryrefslogtreecommitdiff
path: root/sys/dev/ic/aac.c
blob: abdfe81fbb1e4b5382f369eb02f2f84a2bc0f614 (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
/*	$OpenBSD: aac.c,v 1.14 2002/03/27 15:02:59 niklas Exp $	*/

/*-
 * Copyright (c) 2000 Michael Smith
 * Copyright (c) 2000 BSDi
 * Copyright (c) 2000 Niklas Hallqvist
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 *
 *	$FreeBSD: /c/ncvs/src/sys/dev/aac/aac.c,v 1.1 2000/09/13 03:20:34 msmith Exp $
 */

/*
 * Driver for the Adaptec 'FSA' family of PCI/SCSI RAID adapters.
 */

/*
 * This driver would not have rewritten for OpenBSD if it was not for the
 * hardware donation from Nocom.  I want to thank them for their support.
 * Of course, credit should go to Mike Smith for the original work he did
 * in the FreeBSD driver where I found lots of reusable code and inspiration.
 * - Niklas Hallqvist
 */

#include <sys/param.h>
#include <sys/systm.h>
#include <sys/buf.h>
#include <sys/device.h>
#include <sys/kernel.h>
#include <sys/malloc.h>

#include <machine/bus.h>

#include <uvm/uvm_extern.h>

#include <scsi/scsi_all.h>
#include <scsi/scsi_disk.h>
#include <scsi/scsiconf.h>

#include <dev/ic/aacreg.h>
#include <dev/ic/aacvar.h>
#include <dev/ic/aac_tables.h>

/* Geometry constants. */
#define AAC_MAXCYLS		1024
#define AAC_HEADS		64
#define AAC_SECS		32	/* mapping 64*32 */
#define AAC_MEDHEADS		127
#define AAC_MEDSECS		63	/* mapping 127*63 */
#define AAC_BIGHEADS		255
#define AAC_BIGSECS		63	/* mapping 255*63 */
#define AAC_SECS32		0x1f	/* round capacity */

void	aac_bio_complete(struct aac_ccb *);
void	aac_complete(void *, int);
void	aac_copy_internal_data(struct scsi_xfer *, u_int8_t *, size_t);
struct scsi_xfer *aac_dequeue(struct aac_softc *);
int	aac_dequeue_fib(struct aac_softc *, int, u_int32_t *,
    struct aac_fib **);
char   *aac_describe_code(struct aac_code_lookup *, u_int32_t);
void	aac_describe_controller(struct aac_softc *);
void	aac_enqueue(struct aac_softc *, struct scsi_xfer *, int);
void	aac_enqueue_ccb(struct aac_softc *, struct aac_ccb *);
int	aac_enqueue_fib(struct aac_softc *, int, struct aac_ccb *);
void	aac_eval_mapping(u_int32_t, int *, int *, int *);
int	aac_exec_ccb(struct aac_ccb *);
void	aac_free_ccb(struct aac_softc *, struct aac_ccb *);
struct aac_ccb *aac_get_ccb(struct aac_softc *, int);
#if 0
void	aac_handle_aif(struct aac_softc *, struct aac_aif_command *);
#endif
void	aac_host_command(struct aac_softc *);
void	aac_host_response(struct aac_softc *);
int	aac_init(struct aac_softc *);
int	aac_internal_cache_cmd(struct scsi_xfer *);
int	aac_map_command(struct aac_ccb *);
#ifdef AAC_DEBUG
void	aac_print_fib(struct aac_softc *, struct aac_fib *, char *);
#endif
int	aac_raw_scsi_cmd(struct scsi_xfer *);
int	aac_scsi_cmd(struct scsi_xfer *);
int	aac_start(struct aac_ccb *);
void	aac_start_ccbs(struct aac_softc *);
void	aac_startup(struct aac_softc *);
int	aac_sync_command(struct aac_softc *, u_int32_t, u_int32_t,
    u_int32_t, u_int32_t, u_int32_t, u_int32_t *);
int	aac_sync_fib(struct aac_softc *, u_int32_t, u_int32_t, void *,
    u_int16_t, void *, u_int16_t *);
void	aac_timeout(void *);
void	aac_unmap_command(struct aac_ccb *);
void	aac_watchdog(void *);

struct cfdriver aac_cd = {
	NULL, "aac", DV_DULL
};

struct scsi_adapter aac_switch = {
	aac_scsi_cmd, aacminphys, 0, 0,
};

struct scsi_adapter aac_raw_switch = {
	aac_raw_scsi_cmd, aacminphys, 0, 0,
};

struct scsi_device aac_dev = {
	NULL, NULL, NULL, NULL
};

/* i960Rx interface */    
int	aac_rx_get_fwstatus(struct aac_softc *);
void	aac_rx_qnotify(struct aac_softc *, int);
int	aac_rx_get_istatus(struct aac_softc *);
void	aac_rx_clear_istatus(struct aac_softc *, int);
void	aac_rx_set_mailbox(struct aac_softc *, u_int32_t, u_int32_t,
    u_int32_t, u_int32_t, u_int32_t);
int	aac_rx_get_mailboxstatus(struct aac_softc *);
void	aac_rx_set_interrupts(struct aac_softc *, int);

/* StrongARM interface */
int	aac_sa_get_fwstatus(struct aac_softc *);
void	aac_sa_qnotify(struct aac_softc *, int);
int	aac_sa_get_istatus(struct aac_softc *);
void	aac_sa_clear_istatus(struct aac_softc *, int);
void	aac_sa_set_mailbox(struct aac_softc *, u_int32_t, u_int32_t,
    u_int32_t, u_int32_t, u_int32_t);
int	aac_sa_get_mailboxstatus(struct aac_softc *);
void	aac_sa_set_interrupts(struct aac_softc *, int);

struct aac_interface aac_rx_interface = {
	aac_rx_get_fwstatus,
	aac_rx_qnotify,
	aac_rx_get_istatus,
	aac_rx_clear_istatus,
	aac_rx_set_mailbox,
	aac_rx_get_mailboxstatus,
	aac_rx_set_interrupts
};

struct aac_interface aac_sa_interface = {
	aac_sa_get_fwstatus,
	aac_sa_qnotify,
	aac_sa_get_istatus,
	aac_sa_clear_istatus,
	aac_sa_set_mailbox,
	aac_sa_get_mailboxstatus,
	aac_sa_set_interrupts
};

#ifdef AAC_DEBUG
int	aac_debug = AAC_DEBUG;
#endif

int
aac_attach(sc)
	struct aac_softc *sc;
{
	int i, error;
	bus_dma_segment_t seg;
	int nsegs;
	struct aac_ccb *ccb;

	TAILQ_INIT(&sc->sc_free_ccb);
	TAILQ_INIT(&sc->sc_ccbq);
	TAILQ_INIT(&sc->sc_completed);
	LIST_INIT(&sc->sc_queue);

	/* disable interrupts before we enable anything */
	AAC_MASK_INTERRUPTS(sc);

	/* mark controller as suspended until we get ourselves organised */
	sc->sc_state |= AAC_STATE_SUSPEND;

	/*
	 * Initialise the adapter.
	 */
	error = aac_init(sc);
	if (error)
		return (error);

	/* 
	 * Print a little information about the controller.
	 */
	aac_describe_controller(sc);

	/* Initialize the ccbs */
	for (i = 0; i < AAC_ADAP_NORM_CMD_ENTRIES; i++) {
		ccb = &sc->sc_ccbs[i];
		error = bus_dmamap_create(sc->sc_dmat,
		    (AAC_MAXSGENTRIES - 1) << PGSHIFT, AAC_MAXSGENTRIES,
		    (AAC_MAXSGENTRIES - 1) << PGSHIFT, 0,
		    BUS_DMA_NOWAIT | BUS_DMA_ALLOCNOW, &ccb->ac_dmamap_xfer);
		if (error) {
			printf("%s: cannot create ccb dmamap (%d)",
			    sc->sc_dev.dv_xname, error);
			/* XXX cleanup */
			return (1);
		}

		/* allocate the FIB cluster in DMAable memory and load it */
		if (bus_dmamem_alloc(sc->sc_dmat, sizeof *ccb->ac_fib, 1, 0,
		    &seg, 1, &nsegs, BUS_DMA_NOWAIT)) {
			printf("%s: can't allocate FIB structure\n",
			    sc->sc_dev.dv_xname);
			/* XXX cleanup */
			return (1);
		}
		ccb->ac_fibphys = seg.ds_addr;
		if (bus_dmamem_map(sc->sc_dmat, &seg, nsegs,
		    sizeof *ccb->ac_fib, (caddr_t *)&ccb->ac_fib, 0)) {
			printf("%s: can't map FIB structure\n",
			    sc->sc_dev.dv_xname);
			/* XXX cleanup */
			return (1);
		}

		TAILQ_INSERT_TAIL(&sc->sc_free_ccb, &sc->sc_ccbs[i],
		    ac_chain);
	}

	/* Fill in the prototype scsi_link. */
	sc->sc_link.adapter_softc = sc;
	sc->sc_link.adapter = &aac_switch;
	sc->sc_link.device = &aac_dev;
	sc->sc_link.openings = AAC_ADAP_NORM_CMD_ENTRIES; /* XXX optimal? */
	sc->sc_link.adapter_buswidth = AAC_MAX_CONTAINERS;
	sc->sc_link.adapter_target = AAC_MAX_CONTAINERS;

	config_found(&sc->sc_dev, &sc->sc_link, scsiprint);

	return (0);
}

/*
 * Look up a text description of a numeric error code and return a pointer to
 * same.
 */
char *
aac_describe_code(table, code)
	struct aac_code_lookup *table;
	u_int32_t code;
{
	int i;

	for (i = 0; table[i].string != NULL; i++)
		if (table[i].code == code)
			return (table[i].string);
	return (table[i + 1].string);
}

void
aac_describe_controller(sc)
	struct aac_softc *sc;
{
	u_int8_t buf[AAC_FIB_DATASIZE];	/* XXX a bit big for the stack */
	u_int16_t bufsize;
	struct aac_adapter_info *info;
	u_int8_t arg;

	arg = 0;
	if (aac_sync_fib(sc, RequestAdapterInfo, 0, &arg, sizeof arg, &buf,
	    &bufsize)) {
		printf("%s: RequestAdapterInfo failed\n", sc->sc_dev.dv_xname);
		return;
	}
	if (bufsize != sizeof *info) {
		printf("%s: "
		    "RequestAdapterInfo returned wrong data size (%d != %d)\n",
		    sc->sc_dev.dv_xname, bufsize, sizeof *info);
		return;
	}
	info = (struct aac_adapter_info *)&buf[0];

	printf("%s: %s %dMHz, %dMB, %s (%d) Kernel %d.%d-%d\n",
	    sc->sc_dev.dv_xname,
	    aac_describe_code(aac_cpu_variant, info->CpuVariant),
	    info->ClockSpeed, info->TotalMem / (1024 * 1024),
	    aac_describe_code(aac_battery_platform, info->batteryPlatform),
	    info->batteryPlatform, info->KernelRevision.external.comp.major,
	    info->KernelRevision.external.comp.minor,
	    info->KernelRevision.external.comp.dash);

	/* save the kernel revision structure for later use */
	sc->sc_revision = info->KernelRevision;
}

int
aac_init(sc)
	struct aac_softc *sc;
{
	bus_dma_segment_t seg;
	int nsegs;
	int i, error;
	int state = 0;
	struct aac_adapter_init	*ip;
	u_int32_t code;
	u_int8_t *qaddr;

	/*
	 * First wait for the adapter to come ready.
	 */
	for (i = 0; i < AAC_BOOT_TIMEOUT * 1000; i++) {
		code = AAC_GET_FWSTATUS(sc);
		if (code & AAC_SELF_TEST_FAILED) {
			printf("%s: FATAL: selftest failed\n",
			    sc->sc_dev.dv_xname);
			return (ENXIO);
		}
		if (code & AAC_KERNEL_PANIC) {
			printf("%s: FATAL: controller kernel panic\n",
			    sc->sc_dev.dv_xname);
			return (ENXIO);
		}
		if (code & AAC_UP_AND_RUNNING)
			break;
		DELAY(1000);
	}
	if (i == AAC_BOOT_TIMEOUT * 1000) {
		printf("%s: FATAL: controller not coming ready, status %x\n",
		    sc->sc_dev.dv_xname, code);
		return (ENXIO);
	}

	if (bus_dmamem_alloc(sc->sc_dmat, sizeof *sc->sc_common, 1, 0, &seg, 1,
	    &nsegs, BUS_DMA_NOWAIT)) {
		printf("%s: can't allocate common structure\n",
		    sc->sc_dev.dv_xname);
		return (ENOMEM);
	}
	state++;
	sc->sc_common_busaddr = seg.ds_addr;
	if (bus_dmamem_map(sc->sc_dmat, &seg, nsegs, sizeof *sc->sc_common,
	    (caddr_t *)&sc->sc_common, 0)) {
		printf("%s: can't map common structure\n",
		    sc->sc_dev.dv_xname);
		error = ENOMEM;
		goto bail_out;
	}
	state++;
	bzero(sc->sc_common, sizeof *sc->sc_common);
    
	/*
	 * Fill in the init structure.  This tells the adapter about
	 * the physical location * of various important shared data
	 * structures.
	 */
	ip = &sc->sc_common->ac_init;
	ip->InitStructRevision = AAC_INIT_STRUCT_REVISION;

	ip->AdapterFibsPhysicalAddress =
	    sc->sc_common_busaddr + offsetof(struct aac_common, ac_fibs);
	ip->AdapterFibsVirtualAddress = &sc->sc_common->ac_fibs[0];
	ip->AdapterFibsSize = AAC_ADAPTER_FIBS * sizeof(struct aac_fib);
	ip->AdapterFibAlign = sizeof(struct aac_fib);

	ip->PrintfBufferAddress =
	    sc->sc_common_busaddr + offsetof(struct aac_common, ac_printf);
	ip->PrintfBufferSize = AAC_PRINTF_BUFSIZE;

	ip->HostPhysMemPages = 0;	/* not used? */
	ip->HostElapsedSeconds = 0;	/* reset later if invalid */

	/*
	 * Initialise FIB queues.  Note that it appears that the
	 * layout of the indexes and the segmentation of the entries
	 * is mandated by the adapter, which is only told about the
	 * base of the queue index fields.
	 *
	 * The initial values of the indices are assumed to inform the
	 * adapter of the sizes of the respective queues.
	 *
	 * The Linux driver uses a much more complex scheme whereby
	 * several header * records are kept for each queue.  We use a
	 * couple of generic list manipulation functions which
	 * 'know' the size of each list by virtue of a table.
	 */
	qaddr = &sc->sc_common->ac_qbuf[0] + AAC_QUEUE_ALIGN;
	qaddr -= (u_int32_t)qaddr % AAC_QUEUE_ALIGN; 	/* XXX not portable */
	sc->sc_queues = (struct aac_queue_table *)qaddr;
	ip->CommHeaderAddress = sc->sc_common_busaddr +
	    ((char *)sc->sc_queues - (char *)sc->sc_common);
	bzero(sc->sc_queues, sizeof(struct aac_queue_table));

	sc->sc_queues->qt_qindex[AAC_HOST_NORM_CMD_QUEUE][AAC_PRODUCER_INDEX] =
	    AAC_HOST_NORM_CMD_ENTRIES;
	sc->sc_queues->qt_qindex[AAC_HOST_NORM_CMD_QUEUE][AAC_CONSUMER_INDEX] =
	    AAC_HOST_NORM_CMD_ENTRIES;
	sc->sc_queues->qt_qindex[AAC_HOST_HIGH_CMD_QUEUE][AAC_PRODUCER_INDEX] =
	    AAC_HOST_HIGH_CMD_ENTRIES;
	sc->sc_queues->qt_qindex[AAC_HOST_HIGH_CMD_QUEUE][AAC_CONSUMER_INDEX] =
	    AAC_HOST_HIGH_CMD_ENTRIES;
	sc->sc_queues->qt_qindex[AAC_ADAP_NORM_CMD_QUEUE][AAC_PRODUCER_INDEX] =
	    AAC_ADAP_NORM_CMD_ENTRIES;
	sc->sc_queues->qt_qindex[AAC_ADAP_NORM_CMD_QUEUE][AAC_CONSUMER_INDEX] =
	    AAC_ADAP_NORM_CMD_ENTRIES;
	sc->sc_queues->qt_qindex[AAC_ADAP_HIGH_CMD_QUEUE][AAC_PRODUCER_INDEX] =
	    AAC_ADAP_HIGH_CMD_ENTRIES;
	sc->sc_queues->qt_qindex[AAC_ADAP_HIGH_CMD_QUEUE][AAC_CONSUMER_INDEX] =
	    AAC_ADAP_HIGH_CMD_ENTRIES;
	sc->sc_queues->
	    qt_qindex[AAC_HOST_NORM_RESP_QUEUE][AAC_PRODUCER_INDEX] =
	    AAC_HOST_NORM_RESP_ENTRIES;
	sc->sc_queues->
	    qt_qindex[AAC_HOST_NORM_RESP_QUEUE][AAC_CONSUMER_INDEX] =
	    AAC_HOST_NORM_RESP_ENTRIES;
	sc->sc_queues->
	    qt_qindex[AAC_HOST_HIGH_RESP_QUEUE][AAC_PRODUCER_INDEX] =
	    AAC_HOST_HIGH_RESP_ENTRIES;
	sc->sc_queues->
	    qt_qindex[AAC_HOST_HIGH_RESP_QUEUE][AAC_CONSUMER_INDEX] =
	    AAC_HOST_HIGH_RESP_ENTRIES;
	sc->sc_queues->
	    qt_qindex[AAC_ADAP_NORM_RESP_QUEUE][AAC_PRODUCER_INDEX] =
	    AAC_ADAP_NORM_RESP_ENTRIES;
	sc->sc_queues->
	    qt_qindex[AAC_ADAP_NORM_RESP_QUEUE][AAC_CONSUMER_INDEX] =
	    AAC_ADAP_NORM_RESP_ENTRIES;
	sc->sc_queues->
	    qt_qindex[AAC_ADAP_HIGH_RESP_QUEUE][AAC_PRODUCER_INDEX] =
	    AAC_ADAP_HIGH_RESP_ENTRIES;
	sc->sc_queues->
	    qt_qindex[AAC_ADAP_HIGH_RESP_QUEUE][AAC_CONSUMER_INDEX] =
	    AAC_ADAP_HIGH_RESP_ENTRIES;
	sc->sc_qentries[AAC_HOST_NORM_CMD_QUEUE] =
	    &sc->sc_queues->qt_HostNormCmdQueue[0];
	sc->sc_qentries[AAC_HOST_HIGH_CMD_QUEUE] =
	    &sc->sc_queues->qt_HostHighCmdQueue[0];
	sc->sc_qentries[AAC_ADAP_NORM_CMD_QUEUE] =
	    &sc->sc_queues->qt_AdapNormCmdQueue[0];
	sc->sc_qentries[AAC_ADAP_HIGH_CMD_QUEUE] =
	    &sc->sc_queues->qt_AdapHighCmdQueue[0];
	sc->sc_qentries[AAC_HOST_NORM_RESP_QUEUE] =
	    &sc->sc_queues->qt_HostNormRespQueue[0];
	sc->sc_qentries[AAC_HOST_HIGH_RESP_QUEUE] =
	    &sc->sc_queues->qt_HostHighRespQueue[0];
	sc->sc_qentries[AAC_ADAP_NORM_RESP_QUEUE] =
	    &sc->sc_queues->qt_AdapNormRespQueue[0];
	sc->sc_qentries[AAC_ADAP_HIGH_RESP_QUEUE] =
	    &sc->sc_queues->qt_AdapHighRespQueue[0];

	/*
	 * Do controller-type-specific initialisation
	 */
	switch (sc->sc_hwif) {
	case AAC_HWIF_I960RX:
		AAC_SETREG4(sc, AAC_RX_ODBR, ~0);
		break;
	}

	/*
	 * Give the init structure to the controller.
	 */
	if (aac_sync_command(sc, AAC_MONKER_INITSTRUCT, 
	    sc->sc_common_busaddr + offsetof(struct aac_common, ac_init), 0, 0,
	    0, NULL)) {
		printf("%s: error establishing init structure\n",
		    sc->sc_dev.dv_xname);
		error = EIO;
		goto bail_out;
	}

	aac_startup(sc);

	return (0);

 bail_out:
	if (state > 1)
		bus_dmamem_unmap(sc->sc_dmat, (caddr_t)sc->sc_common,
		    sizeof *sc->sc_common);
	if (state > 0)
		bus_dmamem_free(sc->sc_dmat, &seg, 1);
	return (error);
}

/*
 * Probe for containers, create disks.
 */
void
aac_startup (sc)
	struct aac_softc *sc;
{
	struct aac_mntinfo mi;
	struct aac_mntinforesponse mir;
	u_int16_t rsize;	
	int i, drv_cyls, drv_hds, drv_secs;

	/* loop over possible containers */
	mi.Command = VM_NameServe;
	mi.MntType = FT_FILESYS;
	for (i = 0; i < AAC_MAX_CONTAINERS; i++) {
		/* request information on this container */
		mi.MntCount = i;
		if (aac_sync_fib(sc, ContainerCommand, 0, &mi, sizeof mi, &mir,
		    &rsize)) {
			printf("%s: error probing container %d",
			    sc->sc_dev.dv_xname, i);
			continue;
		}
		/* check response size */
		if (rsize != sizeof mir) {
			printf("%s: container info response wrong size "
			    "(%d should be %d)",
			    sc->sc_dev.dv_xname, rsize, sizeof mir);
			continue;
		}

		/* 
		 * Check container volume type for validity.  Note
		 * that many of the possible types * may never show
		 * up.
		 */
		if (mir.Status == ST_OK &&
		    mir.MntTable[0].VolType != CT_NONE) {
			AAC_DPRINTF(AAC_D_MISC,
			    ("%d: id %x  name '%.16s'  size %u  type %d", i,
			    mir.MntTable[0].ObjectId,
			    mir.MntTable[0].FileSystemName,
			    mir.MntTable[0].Capacity,
			    mir.MntTable[0].VolType));

			sc->sc_hdr[i].hd_present = 1;
			sc->sc_hdr[i].hd_size = mir.MntTable[0].Capacity;

			/*
			 * Evaluate mapping (sectors per head, heads per cyl)
			 */
			sc->sc_hdr[i].hd_size &= ~AAC_SECS32;
			aac_eval_mapping(sc->sc_hdr[i].hd_size, &drv_cyls,
			    &drv_hds, &drv_secs);
			sc->sc_hdr[i].hd_heads = drv_hds;
			sc->sc_hdr[i].hd_secs = drv_secs;
			/* Round the size */
			sc->sc_hdr[i].hd_size = drv_cyls * drv_hds * drv_secs;

			sc->sc_hdr[i].hd_devtype = mir.MntTable[0].VolType;

			/* XXX Save the name too for use in IDENTIFY later */
		}
	}

	/* mark the controller up */
	sc->sc_state &= ~AAC_STATE_SUSPEND;

	/* enable interrupts now */
	AAC_UNMASK_INTERRUPTS(sc);
}

void
aac_eval_mapping(size, cyls, heads, secs)
	u_int32_t size;
	int *cyls, *heads, *secs;
{
	*cyls = size / AAC_HEADS / AAC_SECS;
	if (*cyls < AAC_MAXCYLS) {
		*heads = AAC_HEADS;
		*secs = AAC_SECS;
	} else {
		/* Too high for 64 * 32 */
		*cyls = size / AAC_MEDHEADS / AAC_MEDSECS;
		if (*cyls < AAC_MAXCYLS) {
			*heads = AAC_MEDHEADS;
			*secs = AAC_MEDSECS;
		} else {
			/* Too high for 127 * 63 */
			*cyls = size / AAC_BIGHEADS / AAC_BIGSECS;
			*heads = AAC_BIGHEADS;
			*secs = AAC_BIGSECS;
		}
	}
}

int
aac_raw_scsi_cmd(xs)
	struct scsi_xfer *xs;
{
	AAC_DPRINTF(AAC_D_CMD, ("aac_raw_scsi_cmd "));

	/* XXX Not yet implemented */
	xs->error = XS_DRIVER_STUFFUP;
	return (COMPLETE);
}

int
aac_scsi_cmd(xs)
	struct scsi_xfer *xs;
{
	struct scsi_link *link = xs->sc_link;
	struct aac_softc *sc = link->adapter_softc;
	u_int8_t target = link->target;
	struct aac_ccb *ccb;
	u_int32_t blockno, blockcnt;
	struct scsi_rw *rw;
	struct scsi_rw_big *rwb;
	aac_lock_t lock;
	int retval = SUCCESSFULLY_QUEUED;

	AAC_DPRINTF(AAC_D_CMD, ("aac_scsi_cmd "));

	xs->error = XS_NOERROR;

	if (target >= AAC_MAX_CONTAINERS || !sc->sc_hdr[target].hd_present ||
	    link->lun != 0) {
		/*
		 * XXX Should be XS_SENSE but that would require setting up a
		 * faked sense too.
		 */
		xs->error = XS_DRIVER_STUFFUP;
		xs->flags |= ITSDONE;
		scsi_done(xs);
		return (COMPLETE);
	}

	lock = AAC_LOCK(sc);

	/* Don't double enqueue if we came from aac_chain. */
	if (xs != LIST_FIRST(&sc->sc_queue))
		aac_enqueue(sc, xs, 0);

	while ((xs = aac_dequeue(sc))) {
		xs->error = XS_NOERROR;
		ccb = NULL;
		link = xs->sc_link;
		target = link->target;

		switch (xs->cmd->opcode) {
		case TEST_UNIT_READY:
		case REQUEST_SENSE:
		case INQUIRY:
		case MODE_SENSE:
		case START_STOP:
		case READ_CAPACITY:
#if 0
		case VERIFY:
#endif
			if (!aac_internal_cache_cmd(xs)) {
				AAC_UNLOCK(sc, lock);
				return (TRY_AGAIN_LATER);
			}
			xs->flags |= ITSDONE;
			scsi_done(xs);
			goto ready;

		case PREVENT_ALLOW:
			AAC_DPRINTF(AAC_D_CMD, ("PREVENT/ALLOW "));
			/* XXX Not yet implemented */
			xs->error = XS_NOERROR;
			xs->flags |= ITSDONE;
			scsi_done(xs);
			goto ready;

		case SYNCHRONIZE_CACHE:
			AAC_DPRINTF(AAC_D_CMD, ("SYNCHRONIZE_CACHE "));
			/* XXX Not yet implemented */
			xs->error = XS_NOERROR;
			xs->flags |= ITSDONE;
			scsi_done(xs);
			goto ready;

		default:
			AAC_DPRINTF(AAC_D_CMD,
			    ("unknown opc %d ", xs->cmd->opcode));
			/* XXX Not yet implemented */
			xs->error = XS_DRIVER_STUFFUP;
			xs->flags |= ITSDONE;
			scsi_done(xs);
			goto ready;

		case READ_COMMAND:
		case READ_BIG:
		case WRITE_COMMAND:
		case WRITE_BIG:
			AAC_DPRINTF(AAC_D_CMD,
			    ("rw opc %d ", xs->cmd->opcode));

			if (xs->cmd->opcode != SYNCHRONIZE_CACHE) {
				/* A read or write operation. */
				if (xs->cmdlen == 6) {
					rw = (struct scsi_rw *)xs->cmd;
					blockno = _3btol(rw->addr) &
					    (SRW_TOPADDR << 16 | 0xffff);
					blockcnt =
					    rw->length ? rw->length : 0x100;
				} else {
					rwb = (struct scsi_rw_big *)xs->cmd;
					blockno = _4btol(rwb->addr);
					blockcnt = _2btol(rwb->length);
				}
				if (blockno >= sc->sc_hdr[target].hd_size ||
				    blockno + blockcnt >
				    sc->sc_hdr[target].hd_size) {
					printf(
					    "%s: out of bounds %u-%u >= %u\n",
					    sc->sc_dev.dv_xname, blockno,
					    blockcnt,
					    sc->sc_hdr[target].hd_size);
					/*
					 * XXX Should be XS_SENSE but that
					 * would require setting up a faked
					 * sense too.
					 */
					xs->error = XS_DRIVER_STUFFUP;
					xs->flags |= ITSDONE;
					scsi_done(xs);
					goto ready;
				}
			}

			ccb = aac_get_ccb(sc, xs->flags);

			/*
			 * We are out of commands, try again in a little while.
			 */
			if (ccb == NULL) {
				xs->error = XS_DRIVER_STUFFUP;
				AAC_UNLOCK(sc, lock);
				return (TRY_AGAIN_LATER);
			}

			ccb->ac_blockno = blockno;
			ccb->ac_blockcnt = blockcnt;
			ccb->ac_xs = xs;
			ccb->ac_timeout = xs->timeout;

			if (xs->cmd->opcode != SYNCHRONIZE_CACHE &&
			    aac_map_command(ccb)) {
				aac_free_ccb(sc, ccb);
				xs->error = XS_DRIVER_STUFFUP;
				xs->flags |= ITSDONE;
				scsi_done(xs);
				goto ready;
			}

			aac_enqueue_ccb(sc, ccb);
			/* XXX what if enqueue did not start a transfer? */
			if (xs->flags & SCSI_POLL) {
#if 0
				if (!aac_wait(sc, ccb, ccb->ac_timeout)) {
					AAC_UNLOCK(sc, lock);
					printf("%s: command timed out\n",
					    sc->sc_dev.dv_xname);
					xs->error = XS_TIMEOUT;
					return (TRY_AGAIN_LATER);
				}
				xs->flags |= ITSDONE;
				scsi_done(xs);
#endif
			}
		}

	ready:
		/*
		 * Don't process the queue if we are polling.
		 */
		if (xs->flags & SCSI_POLL) {
			retval = COMPLETE;
			break;
		}
	}

	AAC_UNLOCK(sc, lock);
	return (retval);
}

void
aac_copy_internal_data(xs, data, size)
	struct scsi_xfer *xs;
	u_int8_t *data;
	size_t size;
{
	size_t copy_cnt;

	AAC_DPRINTF(AAC_D_MISC, ("aac_copy_internal_data "));

	if (!xs->datalen)
		printf("uio move not yet supported\n");
	else {
		copy_cnt = MIN(size, xs->datalen);
		bcopy(data, xs->data, copy_cnt);
	}
}

/* Emulated SCSI operation on cache device */
int
aac_internal_cache_cmd(xs)
	struct scsi_xfer *xs;
{
	struct scsi_link *link = xs->sc_link;
	struct aac_softc *sc = link->adapter_softc;
	struct scsi_inquiry_data inq;
	struct scsi_sense_data sd;
	struct {
		struct scsi_mode_header hd;
		struct scsi_blk_desc bd;
		union scsi_disk_pages dp;
	} mpd;
	struct scsi_read_cap_data rcd;
	u_int8_t target = link->target;

	AAC_DPRINTF(AAC_D_CMD, ("aac_internal_cache_cmd "));

	switch (xs->cmd->opcode) {
	case TEST_UNIT_READY:
	case START_STOP:
#if 0
	case VERIFY:
#endif
		AAC_DPRINTF(AAC_D_CMD, ("opc %d tgt %d ", xs->cmd->opcode,
		    target));
		break;

	case REQUEST_SENSE:
		AAC_DPRINTF(AAC_D_CMD, ("REQUEST SENSE tgt %d ", target));
		bzero(&sd, sizeof sd);
		sd.error_code = 0x70;
		sd.segment = 0;
		sd.flags = SKEY_NO_SENSE;
		aac_enc32(sd.info, 0);
		sd.extra_len = 0;
		aac_copy_internal_data(xs, (u_int8_t *)&sd, sizeof sd);
		break;

	case INQUIRY:
		AAC_DPRINTF(AAC_D_CMD, ("INQUIRY tgt %d devtype %x ", target,
		    sc->sc_hdr[target].hd_devtype));
		bzero(&inq, sizeof inq);
		/* XXX How do we detect removable/CD-ROM devices?  */
		inq.device = T_DIRECT;
		inq.dev_qual2 = 0;
		inq.version = 2;
		inq.response_format = 2;
		inq.additional_length = 32;
		strcpy(inq.vendor, "Adaptec");
		sprintf(inq.product, "Container #%02d", target);
		strcpy(inq.revision, "   ");
		aac_copy_internal_data(xs, (u_int8_t *)&inq, sizeof inq);
		break;

	case MODE_SENSE:
		AAC_DPRINTF(AAC_D_CMD, ("MODE SENSE tgt %d ", target));

		bzero(&mpd, sizeof mpd);
		switch (((struct scsi_mode_sense *)xs->cmd)->page) {
		case 4:
			/* scsi_disk.h says this should be 0x16 */
			mpd.dp.rigid_geometry.pg_length = 0x16;
			mpd.hd.data_length = sizeof mpd.hd + sizeof mpd.bd +
			    mpd.dp.rigid_geometry.pg_length;
			mpd.hd.blk_desc_len = sizeof mpd.bd;

			/* XXX */
			mpd.hd.dev_spec = 0;
			_lto3b(AAC_BLOCK_SIZE, mpd.bd.blklen);
			mpd.dp.rigid_geometry.pg_code = 4;
			_lto3b(sc->sc_hdr[target].hd_size /
			    sc->sc_hdr[target].hd_heads /
			    sc->sc_hdr[target].hd_secs,
			    mpd.dp.rigid_geometry.ncyl);
			mpd.dp.rigid_geometry.nheads =
			    sc->sc_hdr[target].hd_heads;
			aac_copy_internal_data(xs, (u_int8_t *)&mpd,
			    sizeof mpd);
			break;

		default:
			printf("%s: mode sense page %d not simulated\n",
			    sc->sc_dev.dv_xname,
			    ((struct scsi_mode_sense *)xs->cmd)->page);
			xs->error = XS_DRIVER_STUFFUP;
			return (0);
		}
		break;

	case READ_CAPACITY:
		AAC_DPRINTF(AAC_D_CMD, ("READ CAPACITY tgt %d ", target));
		bzero(&rcd, sizeof rcd);
		_lto4b(sc->sc_hdr[target].hd_size - 1, rcd.addr);
		_lto4b(AAC_BLOCK_SIZE, rcd.length);
		aac_copy_internal_data(xs, (u_int8_t *)&rcd, sizeof rcd);
		break;

	default:
		printf("aac_internal_cache_cmd got bad opcode: %d\n",
		    xs->cmd->opcode);
		xs->error = XS_DRIVER_STUFFUP;
		return (0);
	}

	xs->error = XS_NOERROR;
	return (1);
}

/*
 * Take an interrupt.
 */
int
aac_intr(arg)
	void *arg;
{
	struct aac_softc *sc = arg;
	u_int16_t reason;
	int claimed = 0;

	AAC_DPRINTF(AAC_D_INTR, ("aac_intr(%p) ", sc));

	reason = AAC_GET_ISTATUS(sc);
	AAC_DPRINTF(AAC_D_INTR, ("istatus 0x%04x ", reason));

	/* controller wants to talk to the log?  XXX should we defer this? */
	if (reason & AAC_DB_PRINTF) {
		if (sc->sc_common->ac_printf[0]) {
			printf("%s: ** %.*s", sc->sc_dev.dv_xname,
			    AAC_PRINTF_BUFSIZE, sc->sc_common->ac_printf);
			sc->sc_common->ac_printf[0] = 0;
		}
		AAC_CLEAR_ISTATUS(sc, AAC_DB_PRINTF);
		AAC_QNOTIFY(sc, AAC_DB_PRINTF);
		claimed = 1;
	}

	/* Controller has a message for us? */
	if (reason & AAC_DB_COMMAND_READY) {
		aac_host_command(sc);
		AAC_CLEAR_ISTATUS(sc, AAC_DB_COMMAND_READY);
		claimed = 1;
	}
    
	/* Controller has a response for us? */
	if (reason & AAC_DB_RESPONSE_READY) {
		aac_host_response(sc);
		AAC_CLEAR_ISTATUS(sc, AAC_DB_RESPONSE_READY);
		claimed = 1;
	}

	/*
	 * Spurious interrupts that we don't use - reset the mask and clear
	 * the interrupts.
	 */
	if (reason & (AAC_DB_SYNC_COMMAND | AAC_DB_COMMAND_NOT_FULL |
            AAC_DB_RESPONSE_NOT_FULL)) {
		AAC_UNMASK_INTERRUPTS(sc);
		AAC_CLEAR_ISTATUS(sc, AAC_DB_SYNC_COMMAND |
		    AAC_DB_COMMAND_NOT_FULL | AAC_DB_RESPONSE_NOT_FULL);
		claimed = 1;
	}

	return (claimed);
}

/*
 * Handle notification of one or more FIBs coming from the controller.
 */
void
aac_host_command(struct aac_softc *sc)
{
	struct aac_fib *fib;
	u_int32_t fib_size;

	for (;;) {
		if (aac_dequeue_fib(sc, AAC_HOST_NORM_CMD_QUEUE, &fib_size,
		    &fib))
			break;	/* nothing to do */

		switch(fib->Header.Command) {
		case AifRequest:
#if 0
			aac_handle_aif(sc,
			    (struct aac_aif_command *)&fib->data[0]);
#endif

			break;
		default:
			printf("%s: unknown command from controller\n",
			    sc->sc_dev.dv_xname);
			AAC_PRINT_FIB(sc, fib);
			break;
		}

		/* XXX reply to FIBs requesting responses ?? */
		/* XXX how do we return these FIBs to the controller? */
	}
}

/*
 * Handle notification of one or more FIBs completed by the controller
 */
void
aac_host_response(struct aac_softc *sc)
{
	struct aac_ccb *ccb;
	struct aac_fib *fib;
	u_int32_t fib_size;

	for (;;) {
		/* look for completed FIBs on our queue */
		if (aac_dequeue_fib(sc, AAC_HOST_NORM_RESP_QUEUE, &fib_size,
		    &fib))
			break;	/* nothing to do */
	
		/* get the command, unmap and queue for later processing */
		ccb = (struct aac_ccb *)fib->Header.SenderData;
		if (ccb == NULL) {
			AAC_PRINT_FIB(sc, fib);
		} else {
			timeout_del(&ccb->ac_xs->stimeout);
			aac_unmap_command(ccb);		/* XXX defer? */
			aac_enqueue_completed(ccb);
		}
	}

	/* handle completion processing */
	aac_complete(sc, 0);
}

/*
 * Process completed commands.
 */
void
aac_complete(void *context, int pending)
{
	struct aac_softc *sc = (struct aac_softc *)context;
	struct aac_ccb *ccb;

	/* pull completed commands off the queue */
	for (;;) {
		ccb = aac_dequeue_completed(sc);
		if (ccb == NULL)
			return;
		ccb->ac_flags |= AAC_ACF_COMPLETED;

#if 0
		/* is there a completion handler? */
		if (ccb->ac_complete != NULL) {
			ccb->ac_complete(ccb);
		} else {
			/* assume that someone is sleeping on this command */
			wakeup(ccb);
		}
#else
		aac_bio_complete(ccb);
#endif
	}
}

/*
 * Handle a bio-instigated command that has been completed.
 */
void
aac_bio_complete(struct aac_ccb *ccb)
{
	struct scsi_xfer *xs = ccb->ac_xs;
	struct aac_softc *sc = xs->sc_link->adapter_softc;
	struct buf *bp = xs->bp;
	struct aac_blockread_response *brr;
	struct aac_blockwrite_response *bwr;
	AAC_FSAStatus status;

	/* fetch relevant status and then release the command */
	if (bp->b_flags & B_READ) {
		brr = (struct aac_blockread_response *)&ccb->ac_fib->data[0];
		status = brr->Status;
	} else {
		bwr = (struct aac_blockwrite_response *)&ccb->ac_fib->data[0];
		status = bwr->Status;
	}
	aac_free_ccb(sc, ccb);

	/* fix up the bio based on status */
	if (status == ST_OK) {
		bp->b_resid = 0;
	} else {
		bp->b_error = EIO;
		bp->b_flags |= B_ERROR;
	
		/* XXX be more verbose? */
		printf("%s: I/O error %d (%s)\n", sc->sc_dev.dv_xname,
		    status, AAC_COMMAND_STATUS(status));
	}
	scsi_done(xs);
}

/*
 * Send a synchronous command to the controller and wait for a result.
 */
int
aac_sync_command(sc, command, arg0, arg1, arg2, arg3, sp)
	struct aac_softc *sc;
	u_int32_t command;
	u_int32_t arg0;
	u_int32_t arg1;
	u_int32_t arg2;
	u_int32_t arg3;
	u_int32_t *sp;
{
	int i;
	u_int32_t status;
	aac_lock_t lock = AAC_LOCK(sc);

	/* populate the mailbox */
	AAC_SET_MAILBOX(sc, command, arg0, arg1, arg2, arg3);

	/* ensure the sync command doorbell flag is cleared */
	AAC_CLEAR_ISTATUS(sc, AAC_DB_SYNC_COMMAND);

	/* then set it to signal the adapter */
	AAC_QNOTIFY(sc, AAC_DB_SYNC_COMMAND);
	DELAY(AAC_SYNC_DELAY);

	/* spin waiting for the command to complete */
	for (i = 0; i < AAC_IMMEDIATE_TIMEOUT * 1000; i++) {
		if (AAC_GET_ISTATUS(sc) & AAC_DB_SYNC_COMMAND);
			break;
		DELAY(1000);
	}
	if (i == AAC_IMMEDIATE_TIMEOUT * 1000) {
		AAC_UNLOCK(sc, lock);
		return (EIO);
	}

	/* clear the completion flag */
	AAC_CLEAR_ISTATUS(sc, AAC_DB_SYNC_COMMAND);

	/* get the command status */
	status = AAC_GET_MAILBOXSTATUS(sc);
	AAC_UNLOCK(sc, lock);
	if (sp != NULL)
		*sp = status;
	return (0);	/* check command return status? */
}

/*
 * Send a synchronous FIB to the controller and wait for a result.
 */
int
aac_sync_fib(sc, command, xferstate, data, datasize, result, resultsize)
	struct aac_softc *sc;
	u_int32_t command;
	u_int32_t xferstate;
	void *data;
	u_int16_t datasize;
	void *result;
	u_int16_t *resultsize;
{
	struct aac_fib *fib = &sc->sc_common->ac_sync_fib;

	if (datasize > AAC_FIB_DATASIZE)
		return (EINVAL);

	/*
	 * Set up the sync FIB
	 */
	fib->Header.XferState = AAC_FIBSTATE_HOSTOWNED |
	    AAC_FIBSTATE_INITIALISED | AAC_FIBSTATE_EMPTY;
	fib->Header.XferState |= xferstate;
	fib->Header.Command = command;
	fib->Header.StructType = AAC_FIBTYPE_TFIB;
	fib->Header.Size = sizeof fib + datasize;
	fib->Header.SenderSize = sizeof *fib;
	fib->Header.SenderFibAddress = (u_int32_t)fib;
	fib->Header.ReceiverFibAddress =
	    sc->sc_common_busaddr + offsetof(struct aac_common, ac_sync_fib);

	/*
	 * Copy in data.
	 */
	if (data != NULL) {
		bcopy(data, fib->data, datasize);
		fib->Header.XferState |=
		    AAC_FIBSTATE_FROMHOST | AAC_FIBSTATE_NORM;
	}

	/*
	 * Give the FIB to the controller, wait for a response.
	 */
	if (aac_sync_command(sc, AAC_MONKER_SYNCFIB,
	    fib->Header.ReceiverFibAddress, 0, 0, 0, NULL)) {
		return (EIO);
	}

	/* 
	 * Copy out the result
	 */
	if (result != NULL) {
		*resultsize = fib->Header.Size - sizeof fib->Header;
		bcopy(fib->data, result, *resultsize);
	}
	return (0);
}

void
aacminphys(bp)
	struct buf *bp;
{
#if 0
	u_int8_t *buf = bp->b_data;
	paddr_t pa;
	long off;
#endif

	AAC_DPRINTF(AAC_D_MISC, ("aacminphys(0x%x) ", bp));

#if 1
#if 0	/* As this is way more than MAXPHYS it's really not necessary. */
	if (bp->b_bcount > ((AAC_MAXOFFSETS - 1) * PAGE_SIZE))
		bp->b_bcount = ((AAC_MAXOFFSETS - 1) * PAGE_SIZE);
#endif
#else
	for (off = PAGE_SIZE, pa = vtophys(buf); off < bp->b_bcount;
	    off += PAGE_SIZE)
		if (pa + off != vtophys(buf + off)) {
			bp->b_bcount = off;
			break;
		}
#endif
	minphys(bp);
}

/*
 * Read the current firmware status word.
 */
int
aac_sa_get_fwstatus(sc)
	struct aac_softc *sc;
{
	return (AAC_GETREG4(sc, AAC_SA_FWSTATUS));
}

int
aac_rx_get_fwstatus(sc)
	struct aac_softc *sc;
{
	return (AAC_GETREG4(sc, AAC_RX_FWSTATUS));
}

/*
 * Notify the controller of a change in a given queue
 */

void
aac_sa_qnotify(sc, qbit)
	struct aac_softc *sc;
	int qbit;
{
	AAC_SETREG2(sc, AAC_SA_DOORBELL1_SET, qbit);
}

void
aac_rx_qnotify(sc, qbit)
	struct aac_softc *sc;
	int qbit;
{
	AAC_SETREG4(sc, AAC_RX_IDBR, qbit);
}

/*
 * Get the interrupt reason bits
 */
int
aac_sa_get_istatus(sc)
	struct aac_softc *sc;
{
	return (AAC_GETREG2(sc, AAC_SA_DOORBELL0));
}

int
aac_rx_get_istatus(sc)
	struct aac_softc *sc;
{
	return (AAC_GETREG4(sc, AAC_RX_ODBR));
}

/*
 * Clear some interrupt reason bits
 */
void
aac_sa_clear_istatus(sc, mask)
	struct aac_softc *sc;
	int mask;
{
	AAC_SETREG2(sc, AAC_SA_DOORBELL0_CLEAR, mask);
}

void
aac_rx_clear_istatus(sc, mask)
	struct aac_softc *sc;
	int mask;
{
	AAC_SETREG4(sc, AAC_RX_ODBR, mask);
}

/*
 * Populate the mailbox and set the command word
 */
void
aac_sa_set_mailbox(sc, command, arg0, arg1, arg2, arg3)
	struct aac_softc *sc;
	u_int32_t command;
	u_int32_t arg0;
	u_int32_t arg1;
	u_int32_t arg2;
	u_int32_t arg3;
{
	AAC_SETREG4(sc, AAC_SA_MAILBOX, command);
	AAC_SETREG4(sc, AAC_SA_MAILBOX + 4, arg0);
	AAC_SETREG4(sc, AAC_SA_MAILBOX + 8, arg1);
	AAC_SETREG4(sc, AAC_SA_MAILBOX + 12, arg2);
	AAC_SETREG4(sc, AAC_SA_MAILBOX + 16, arg3);
}

void
aac_rx_set_mailbox(sc, command, arg0, arg1, arg2, arg3)
	struct aac_softc *sc;
	u_int32_t command;
	u_int32_t arg0;
	u_int32_t arg1;
	u_int32_t arg2;
	u_int32_t arg3;
{
	AAC_SETREG4(sc, AAC_RX_MAILBOX, command);
	AAC_SETREG4(sc, AAC_RX_MAILBOX + 4, arg0);
	AAC_SETREG4(sc, AAC_RX_MAILBOX + 8, arg1);
	AAC_SETREG4(sc, AAC_RX_MAILBOX + 12, arg2);
	AAC_SETREG4(sc, AAC_RX_MAILBOX + 16, arg3);
}

/*
 * Fetch the immediate command status word
 */
int
aac_sa_get_mailboxstatus(sc)
	struct aac_softc *sc;
{
	return (AAC_GETREG4(sc, AAC_SA_MAILBOX));
}

int
aac_rx_get_mailboxstatus(sc)
	struct aac_softc *sc;
{
	return (AAC_GETREG4(sc, AAC_RX_MAILBOX));
}

/*
 * Set/clear interrupt masks
 */
void
aac_sa_set_interrupts(sc, enable)
	struct aac_softc *sc;
	int enable;
{
	if (enable)
		AAC_SETREG2((sc), AAC_SA_MASK0_CLEAR, AAC_DB_INTERRUPTS);
	else
		AAC_SETREG2((sc), AAC_SA_MASK0_SET, ~0);
}

void
aac_rx_set_interrupts(sc, enable)
	struct aac_softc *sc;
	int enable;
{
	if (enable)
		AAC_SETREG4(sc, AAC_RX_OIMR, ~AAC_DB_INTERRUPTS);
	else
		AAC_SETREG4(sc, AAC_RX_OIMR, ~0);
}

struct aac_ccb *
aac_get_ccb(sc, flags)
	struct aac_softc *sc;
	int flags;
{
	struct aac_ccb *ccb;
	aac_lock_t lock;

	AAC_DPRINTF(AAC_D_QUEUE, ("aac_get_ccb(%p, 0x%x) ", sc, flags));

	lock = AAC_LOCK(sc);

	for (;;) {
		ccb = TAILQ_FIRST(&sc->sc_free_ccb);
		if (ccb != NULL)
			break;
		if (flags & SCSI_NOSLEEP)
			goto bail_out;
		tsleep(&sc->sc_free_ccb, PRIBIO, "aac_ccb", 0);
	}

	TAILQ_REMOVE(&sc->sc_free_ccb, ccb, ac_chain);

	/* initialise the command/FIB */
	ccb->ac_sgtable = NULL;
	ccb->ac_flags = 0;
	ccb->ac_fib->Header.XferState = AAC_FIBSTATE_EMPTY;
	ccb->ac_fib->Header.StructType = AAC_FIBTYPE_TFIB;
	ccb->ac_fib->Header.Flags = 0;
	ccb->ac_fib->Header.SenderSize = sizeof(struct aac_fib);

	/* 
	 * These are duplicated in aac_start to cover the case where an
	 * intermediate stage may have destroyed them.  They're left
	 * initialised here for debugging purposes only.
	 */
	ccb->ac_fib->Header.SenderFibAddress = (u_int32_t)ccb->ac_fib;
	ccb->ac_fib->Header.ReceiverFibAddress = ccb->ac_fibphys;

 bail_out:
	AAC_UNLOCK(sc, lock);
	return (ccb);
}

void
aac_free_ccb(sc, ccb)
	struct aac_softc *sc;
	struct aac_ccb *ccb;
{
	aac_lock_t lock;

	AAC_DPRINTF(AAC_D_QUEUE, ("aac_free_ccb(%p, %p) ", sc, ccb));

	lock = AAC_LOCK(sc);

	TAILQ_INSERT_HEAD(&sc->sc_free_ccb, ccb, ac_chain);

	/* If the free list was empty, wake up potential waiters. */
	if (TAILQ_NEXT(ccb, ac_chain) == NULL)
		wakeup(&sc->sc_free_ccb);

	AAC_UNLOCK(sc, lock);
}

void
aac_enqueue_ccb(sc, ccb)
	struct aac_softc *sc;
	struct aac_ccb *ccb;
{
	AAC_DPRINTF(AAC_D_QUEUE, ("aac_enqueue_ccb(%p, %p) ", sc, ccb));

	timeout_set(&ccb->ac_xs->stimeout, aac_timeout, ccb);
	TAILQ_INSERT_TAIL(&sc->sc_ccbq, ccb, ac_chain);
	aac_start_ccbs(sc);
}

void
aac_start_ccbs(sc)
	struct aac_softc *sc;
{
	struct aac_ccb *ccb;
	struct scsi_xfer *xs;

	AAC_DPRINTF(AAC_D_QUEUE, ("aac_start_ccbs(%p) ", sc));

	while ((ccb = TAILQ_FIRST(&sc->sc_ccbq)) != NULL) {

		xs = ccb->ac_xs;
		if (ccb->ac_flags & AAC_ACF_WATCHDOG)
			timeout_del(&xs->stimeout);

		if (aac_exec_ccb(ccb) == 0) {
			ccb->ac_flags |= AAC_ACF_WATCHDOG;
			timeout_set(&ccb->ac_xs->stimeout, aac_watchdog, ccb);
			timeout_add(&xs->stimeout,
			    (AAC_WATCH_TIMEOUT * hz) / 1000);
			break;
		}
		TAILQ_REMOVE(&sc->sc_ccbq, ccb, ac_chain);

		if ((xs->flags & SCSI_POLL) == 0) {
			timeout_set(&ccb->ac_xs->stimeout, aac_timeout, ccb);
			timeout_add(&xs->stimeout,
			    (ccb->ac_timeout * hz) / 1000);
		}
	}
}

int
aac_exec_ccb(ccb)
	struct aac_ccb *ccb;
{
	struct scsi_xfer *xs = ccb->ac_xs;
	struct scsi_link *link = xs->sc_link;
	u_int8_t target = link->target;
	int i;
	struct aac_fib *fib;
	struct aac_blockread *br;
	struct aac_blockwrite *bw;
	bus_dmamap_t xfer;

	AAC_DPRINTF(AAC_D_CMD, ("aac_exec_ccb(%p, %p) ", xs, ccb));

	/* build the FIB */
	fib = ccb->ac_fib;
	fib->Header.XferState = AAC_FIBSTATE_HOSTOWNED |
	    AAC_FIBSTATE_INITIALISED | AAC_FIBSTATE_FROMHOST |
	    AAC_FIBSTATE_REXPECTED | AAC_FIBSTATE_NORM;
	fib->Header.Command = ContainerCommand;
	fib->Header.Size = sizeof(struct aac_fib_header);

	switch (xs->cmd->opcode) {
	case PREVENT_ALLOW:
	case SYNCHRONIZE_CACHE:
		if (xs->cmd->opcode == PREVENT_ALLOW) {
			/* XXX PREVENT_ALLOW support goes here */
		} else {
			AAC_DPRINTF(AAC_D_CMD,
			    ("SYNCHRONIZE CACHE tgt %d ", target));
		}
		break;

	case WRITE_COMMAND:
	case WRITE_BIG:
		bw = (struct aac_blockwrite *)&fib->data[0];
		bw->Command = VM_CtBlockWrite;
		bw->ContainerId = target;
		bw->BlockNumber = ccb->ac_blockno;
		bw->ByteCount = ccb->ac_blockcnt * DEV_BSIZE;
		bw->Stable = CUNSTABLE;	/* XXX what's appropriate here? */
		fib->Header.Size += sizeof(struct aac_blockwrite);
		ccb->ac_sgtable = &bw->SgMap;
		break;

	case READ_COMMAND:
	case READ_BIG:
		br = (struct aac_blockread *)&fib->data[0];
		br->Command = VM_CtBlockRead;
		br->ContainerId = target;
		br->BlockNumber = ccb->ac_blockno;
		br->ByteCount = ccb->ac_blockcnt * DEV_BSIZE;
		fib->Header.Size += sizeof(struct aac_blockread);
		ccb->ac_sgtable = &br->SgMap;
		break;
	}

	if (xs->cmd->opcode != PREVENT_ALLOW &&
	    xs->cmd->opcode != SYNCHRONIZE_CACHE) {
		xfer = ccb->ac_dmamap_xfer;
		ccb->ac_sgtable->SgCount = xfer->dm_nsegs;
		for (i = 0; i < xfer->dm_nsegs; i++) {
			ccb->ac_sgtable->SgEntry[i].SgAddress =
			    xfer->dm_segs[i].ds_addr;
			ccb->ac_sgtable->SgEntry[i].SgByteCount =
			    xfer->dm_segs[i].ds_len;
			AAC_DPRINTF(AAC_D_IO,
			    ("#%d va %p pa %p len %x\n", i, buf,
			    xfer->dm_segs[i].ds_addr,
			    xfer->dm_segs[i].ds_len));
		}

		/* update the FIB size for the s/g count */
		fib->Header.Size += xfer->dm_nsegs *
		    sizeof(struct aac_sg_entry);
	}

	aac_start(ccb);

	xs->error = XS_NOERROR;
	xs->resid = 0;
	return (1);
}

/********************************************************************************
 * Deliver a command to the controller; allocate controller resources at the
 * last moment when possible.
 */
int
aac_start(struct aac_ccb *ccb)
{
	struct aac_softc *sc = ccb->ac_xs->sc_link->adapter_softc;

#if 0
	/* get the command mapped */
	aac_map_command(ccb);
#endif

	/* fix up the address values */
	ccb->ac_fib->Header.SenderFibAddress = (u_int32_t)ccb->ac_fib;
	ccb->ac_fib->Header.ReceiverFibAddress = ccb->ac_fibphys;

	/* save a pointer to the command for speedy reverse-lookup */
	ccb->ac_fib->Header.SenderData = (u_int32_t)ccb; /* XXX ack, sizing */

	/* put the FIB on the outbound queue */
	if (aac_enqueue_fib(sc, AAC_ADAP_NORM_CMD_QUEUE, ccb))
		return (EBUSY);

	return (0);
}

/*
 * Map a command into controller-visible space.
 */
int
aac_map_command(struct aac_ccb *ccb)
{
	struct scsi_xfer *xs = ccb->ac_xs;
	struct aac_softc *sc = xs->sc_link->adapter_softc;
	int error;

#if 0
	/* don't map more than once */
	if (ccb->ac_flags & AAC_CMD_MAPPED)
		return;
#endif

	if (xs->datalen != 0) {
		error = bus_dmamap_load(sc->sc_dmat, ccb->ac_dmamap_xfer,
		    xs->data, xs->datalen, NULL,
		    (xs->flags & SCSI_NOSLEEP) ? BUS_DMA_NOWAIT :
		    BUS_DMA_WAITOK);
		if (error) {
			printf("%s: aac_scsi_cmd: ", sc->sc_dev.dv_xname);
			if (error == EFBIG)
				printf("more than %d dma segs\n",
				    AAC_MAXSGENTRIES);
			else
				printf("error %d loading dma map\n", error);
			return (error);
		}

		bus_dmamap_sync(sc->sc_dmat, ccb->ac_dmamap_xfer, 0,
		    ccb->ac_dmamap_xfer->dm_mapsize,
		    (xs->flags & SCSI_DATA_IN) ? BUS_DMASYNC_PREREAD :
		    BUS_DMASYNC_PREWRITE);
	}

#if 0
	ccb->ac_flags |= AAC_CMD_MAPPED;
#endif
	return (0);
}

/*
 * Unmap a command from controller-visible space.
 */
void
aac_unmap_command(struct aac_ccb *ccb)
{
	struct scsi_xfer *xs = ccb->ac_xs;
	struct aac_softc *sc = xs->sc_link->adapter_softc;

#if 0
	if (!(ccb->ac_flags & AAC_CMD_MAPPED))
		return;
#endif

	if (xs->datalen != 0) {
		bus_dmamap_sync(sc->sc_dmat, ccb->ac_dmamap_xfer, 0,
		    ccb->ac_dmamap_xfer->dm_mapsize,
		    (xs->flags & SCSI_DATA_IN) ? BUS_DMASYNC_POSTREAD :
		    BUS_DMASYNC_POSTWRITE);

		bus_dmamap_unload(sc->sc_dmat, ccb->ac_dmamap_xfer);
	}
#if 0
	ccb->ac_flags &= ~AAC_CMD_MAPPED;
#endif
}

void
aac_timeout(arg)
	void *arg;
{
	struct aac_ccb *ccb = arg;
	struct scsi_link *link = ccb->ac_xs->sc_link;
	struct aac_softc *sc = link->adapter_softc;
	aac_lock_t lock;

	sc_print_addr(link);
	printf("timed out\n");

	/* XXX Test for multiple timeouts */

	ccb->ac_xs->error = XS_TIMEOUT;
	lock = AAC_LOCK(sc);
	aac_enqueue_ccb(sc, ccb);
	AAC_UNLOCK(sc, lock);
}

void
aac_watchdog(arg)
	void *arg;
{
	struct aac_ccb *ccb = arg;
	struct scsi_link *link = ccb->ac_xs->sc_link;
	struct aac_softc *sc = link->adapter_softc;
	aac_lock_t lock;

	lock = AAC_LOCK(sc);
	ccb->ac_flags &= ~AAC_ACF_WATCHDOG;
	aac_start_ccbs(sc);
	AAC_UNLOCK(sc, lock);
}
/*
 * Insert a command into the driver queue, either at the front or at the tail.
 * It's ok to overload the freelist link as these structures are never on
 * the freelist at this time.
 */
void
aac_enqueue(sc, xs, infront)
	struct aac_softc *sc;
	struct scsi_xfer *xs;
	int infront;
{
	if (infront || LIST_FIRST(&sc->sc_queue) == NULL) {
		if (LIST_FIRST(&sc->sc_queue) == NULL)
			sc->sc_queuelast = xs;
		LIST_INSERT_HEAD(&sc->sc_queue, xs, free_list);
		return;
	}
	LIST_INSERT_AFTER(sc->sc_queuelast, xs, free_list);
	sc->sc_queuelast = xs;
}

/*
 * Pull a command off the front of the driver queue.
 */
struct scsi_xfer *
aac_dequeue(sc)
	struct aac_softc *sc;
{
	struct scsi_xfer *xs;

	xs = LIST_FIRST(&sc->sc_queue);
	if (xs == NULL)
		return (NULL);
	LIST_REMOVE(xs, free_list);

	if (LIST_FIRST(&sc->sc_queue) == NULL)
		sc->sc_queuelast = NULL;

	return (xs);
}

/********************************************************************************
 * Adapter-space FIB queue manipulation
 *
 * Note that the queue implementation here is a little funky; neither the PI or
 * CI will ever be zero.  This behaviour is a controller feature.
 */
static struct {
	int size;
	int notify;
} aac_qinfo[] = {
	{ AAC_HOST_NORM_CMD_ENTRIES, AAC_DB_COMMAND_NOT_FULL },
	{ AAC_HOST_HIGH_CMD_ENTRIES, 0 },
	{ AAC_ADAP_NORM_CMD_ENTRIES, AAC_DB_COMMAND_READY },
	{ AAC_ADAP_HIGH_CMD_ENTRIES, 0 },
	{ AAC_HOST_NORM_RESP_ENTRIES, AAC_DB_RESPONSE_NOT_FULL },
	{ AAC_HOST_HIGH_RESP_ENTRIES, 0 },
	{ AAC_ADAP_NORM_RESP_ENTRIES, AAC_DB_RESPONSE_READY },
	{ AAC_ADAP_HIGH_RESP_ENTRIES, 0 }
};

/*
 * Atomically insert an entry into the nominated queue, returns 0 on success
 * or EBUSY if the queue is full.
 *
 * XXX Note that it would be more efficient to defer notifying the controller
 * in the case where we may be inserting several entries in rapid succession,
 * but implementing this usefully is difficult.
 */
int
aac_enqueue_fib(struct aac_softc *sc, int queue, struct aac_ccb *ccb)
{
	u_int32_t pi, ci;
	int error;
	aac_lock_t lock;
	u_int32_t fib_size;
	u_int32_t fib_addr;

	fib_size = ccb->ac_fib->Header.Size;
	fib_addr = ccb->ac_fib->Header.ReceiverFibAddress;

	lock = AAC_LOCK(sc);

	/* get the producer/consumer indices */
	pi = sc->sc_queues->qt_qindex[queue][AAC_PRODUCER_INDEX];
	ci = sc->sc_queues->qt_qindex[queue][AAC_CONSUMER_INDEX];

	/* wrap the queue? */
	if (pi >= aac_qinfo[queue].size)
		pi = 0;

	/* check for queue full */
	if ((pi + 1) == ci) {
		error = EBUSY;
		goto out;
	}

	/* populate queue entry */
	(sc->sc_qentries[queue] + pi)->aq_fib_size = fib_size;
	(sc->sc_qentries[queue] + pi)->aq_fib_addr = fib_addr;

	/* update producer index */
	sc->sc_queues->qt_qindex[queue][AAC_PRODUCER_INDEX] = pi + 1;

	/* notify the adapter if we know how */
	if (aac_qinfo[queue].notify != 0)
		AAC_QNOTIFY(sc, aac_qinfo[queue].notify);

	error = 0;

out:
	AAC_UNLOCK(sc, lock);
	return (error);
}

/*
 * Atomically remove one entry from the nominated queue, returns 0 on success
 * or ENOENT if the queue is empty.
 */
int
aac_dequeue_fib(struct aac_softc *sc, int queue, u_int32_t *fib_size,
    struct aac_fib **fib_addr)
{
	u_int32_t pi, ci;
	int notify;
	int error;
	aac_lock_t lock;

	lock = AAC_LOCK(sc);

	/* get the producer/consumer indices */
	pi = sc->sc_queues->qt_qindex[queue][AAC_PRODUCER_INDEX];
	ci = sc->sc_queues->qt_qindex[queue][AAC_CONSUMER_INDEX];

	/* check for queue empty */
	if (ci == pi) {
		error = ENOENT;
		goto out;
	}

	notify = 0;
	if (ci == pi + 1)
		notify++;

	/* wrap the queue? */
	if (ci >= aac_qinfo[queue].size)
		ci = 0;

	/* fetch the entry */
	*fib_size = (sc->sc_qentries[queue] + ci)->aq_fib_size;
	*fib_addr =
	    (struct aac_fib *)(sc->sc_qentries[queue] + ci)->aq_fib_addr;

	/* update consumer index */
	sc->sc_queues->qt_qindex[queue][AAC_CONSUMER_INDEX] = ci + 1;

	/* if we have made the queue un-full, notify the adapter */
	if (notify && (aac_qinfo[queue].notify != 0))
		AAC_QNOTIFY(sc, aac_qinfo[queue].notify);
	error = 0;

out:
	AAC_UNLOCK(sc, lock);
	return (error);
}

#ifdef AAC_DEBUG
/*
 * Print a FIB
 */
void
aac_print_fib(struct aac_softc *sc, struct aac_fib *fib, char *caller)
{
	printf("%s: FIB @ %p\n", caller, fib);
	printf("  XferState %b\n", fib->Header.XferState, "\20"
	    "\1HOSTOWNED"
	    "\2ADAPTEROWNED"
	    "\3INITIALISED"
	    "\4EMPTY"
	    "\5FROMPOOL"
	    "\6FROMHOST"
	    "\7FROMADAP"
	    "\10REXPECTED"
	    "\11RNOTEXPECTED"
	    "\12DONEADAP"
	    "\13DONEHOST"
	    "\14HIGH"
	    "\15NORM"
	    "\16ASYNC"
	    "\17PAGEFILEIO"
	    "\20SHUTDOWN"
	    "\21LAZYWRITE"
	    "\22ADAPMICROFIB"
	    "\23BIOSFIB"
	    "\24FAST_RESPONSE"
	    "\25APIFIB\n");
	printf("  Command         %d\n", fib->Header.Command);
	printf("  StructType      %d\n", fib->Header.StructType);
	printf("  Flags           0x%x\n", fib->Header.Flags);
	printf("  Size            %d\n", fib->Header.Size);
	printf("  SenderSize      %d\n", fib->Header.SenderSize);
	printf("  SenderAddress   0x%x\n", fib->Header.SenderFibAddress);
	printf("  ReceiverAddress 0x%x\n", fib->Header.ReceiverFibAddress);
	printf("  SenderData      0x%x\n", fib->Header.SenderData);
	switch(fib->Header.Command) {
	case ContainerCommand: {
		struct aac_blockread *br = (struct aac_blockread *)fib->data;
		struct aac_blockwrite *bw = (struct aac_blockwrite *)fib->data;
		struct aac_sg_table *sg = NULL;
		int i;

		if (br->Command == VM_CtBlockRead) {
			printf("  BlockRead: container %d  0x%x/%d\n", 
			    br->ContainerId, br->BlockNumber, br->ByteCount);
			    sg = &br->SgMap;
		}
		if (bw->Command == VM_CtBlockWrite) {
			printf("  BlockWrite: container %d  0x%x/%d (%s)\n", 
			    bw->ContainerId, bw->BlockNumber, bw->ByteCount,
			    bw->Stable == CSTABLE ? "stable" : "unstable");
			sg = &bw->SgMap;
		}
		if (sg != NULL) {
			printf("  %d s/g entries\n", sg->SgCount);
			for (i = 0; i < sg->SgCount; i++)
				printf("  0x%08x/%d\n",
				       sg->SgEntry[i].SgAddress,
				       sg->SgEntry[i].SgByteCount);
		}
		break;
	}
	default:
		printf("   %16D\n", fib->data, " ");
		printf("   %16D\n", fib->data + 16, " ");
	break;
	}
}
#endif