summaryrefslogtreecommitdiff
path: root/sys/dev/ic/aac.c
blob: 3ae5e4731871e18bda96fe1636a555c71e508a6d (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
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
/*	$OpenBSD: aac.c,v 1.26 2005/12/03 16:53:15 krw Exp $	*/

/*-
 * Copyright (c) 2000 Michael Smith
 * Copyright (c) 2001 Scott Long
 * Copyright (c) 2000 BSDi
 * Copyright (c) 2001 Adaptec, Inc.
 * Copyright (c) 2000 Niklas Hallqvist
 * Copyright (c) 2004 Nathan Binkert
 * 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/kthread.h>
#include <sys/malloc.h>
#include <sys/rwlock.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 */

struct scsi_xfer;

void	aac_copy_internal_data(struct scsi_xfer *, u_int8_t *, size_t);
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);
int	aac_enqueue_fib(struct aac_softc *, int, struct aac_command *);
int	aac_dequeue_fib(struct aac_softc *, int, u_int32_t *,
			struct aac_fib **);
int	aac_enqueue_response(struct aac_softc *sc, int queue,
			     struct aac_fib *fib);

void	aac_eval_mapping(u_int32_t, int *, int *, int *);
void	aac_print_printf(struct aac_softc *);
void	aac_host_command(struct aac_softc *);
void	aac_host_response(struct aac_softc *);
int	aac_init(struct aac_softc *);
int	aac_check_firmware(struct aac_softc *);
int	aac_internal_cache_cmd(struct scsi_xfer *);

/* Command Processing */
void	aac_timeout(struct aac_softc *);
void	aac_command_timeout(struct aac_command *);
int	aac_map_command(struct aac_command *);
void	aac_complete(void *);
int	aac_bio_command(struct aac_softc *, struct aac_command **);
void	aac_bio_complete(struct aac_command *);
int	aac_wait_command(struct aac_command *, int);
void	aac_create_thread(void *);
void	aac_command_thread(void *);

/* Command Buffer Management */
void	aac_map_command_sg(void *, bus_dma_segment_t *, int, int);
int	aac_alloc_commands(struct aac_softc *);
void	aac_free_commands(struct aac_softc *);
void	aac_unmap_command(struct aac_command *);

int	aac_raw_scsi_cmd(struct scsi_xfer *);
int	aac_scsi_cmd(struct scsi_xfer *);
void	aac_startio(struct aac_softc *);
void	aac_startup(struct aac_softc *);
void	aac_add_container(struct aac_softc *, struct aac_mntinforesp *, int);
void	aac_shutdown(void *);
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 *);
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
};

/* Falcon/PPC interface */
int	aac_fa_get_fwstatus(struct aac_softc *);
void	aac_fa_qnotify(struct aac_softc *, int);
int	aac_fa_get_istatus(struct aac_softc *);
void	aac_fa_clear_istatus(struct aac_softc *, int);
void	aac_fa_set_mailbox(struct aac_softc *, u_int32_t, u_int32_t, u_int32_t,
			   u_int32_t, u_int32_t);
int	aac_fa_get_mailbox(struct aac_softc *, int);
void	aac_fa_set_interrupts(struct aac_softc *, int);

struct aac_interface aac_fa_interface = {
	aac_fa_get_fwstatus,
	aac_fa_qnotify,
	aac_fa_get_istatus,
	aac_fa_clear_istatus,
	aac_fa_set_mailbox,
	aac_fa_get_mailbox,
	aac_fa_set_interrupts
};

/* 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_mailbox(struct aac_softc *, int);
void	aac_sa_set_interrupts(struct aac_softc *, int);

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_mailbox,
	aac_sa_set_interrupts
};

/* 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_mailbox(struct aac_softc *, int);
void	aac_rx_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_mailbox,
	aac_rx_set_interrupts
};

#ifdef AAC_DEBUG
int	aac_debug = AAC_DEBUG;
#endif

int
aac_attach(struct aac_softc *sc)
{
	int error;

	/*
	 * Initialise per-controller queues.
	 */
	aac_initq_free(sc);
	aac_initq_ready(sc);
	aac_initq_busy(sc);
	aac_initq_bio(sc);

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

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

	/*
	 * Check that the firmware on the card is supported.
	 */
	error = aac_check_firmware(sc);
	if (error)
		return (error);

	/*
	 * Initialize locks
	 */
	AAC_LOCK_INIT(&sc->aac_sync_lock, "AAC sync FIB lock");
	AAC_LOCK_INIT(&sc->aac_aifq_lock, "AAC AIF lock");
	AAC_LOCK_INIT(&sc->aac_io_lock, "AAC I/O lock");
	AAC_LOCK_INIT(&sc->aac_container_lock, "AAC container lock");
	TAILQ_INIT(&sc->aac_container_tqh);

	/* Initialize the local AIF queue pointers */
	sc->aac_aifq_head = sc->aac_aifq_tail = AAC_AIFQ_LENGTH;

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

	/* Fill in the prototype scsi_link. */
	sc->aac_link.adapter_softc = sc;
	sc->aac_link.adapter = &aac_switch;
	sc->aac_link.device = &aac_dev;
	sc->aac_link.openings = (sc->total_fibs - 8) / 
	    (sc->aac_container_count ? sc->aac_container_count : 1);
	sc->aac_link.adapter_buswidth = AAC_MAX_CONTAINERS;
	sc->aac_link.adapter_target = AAC_MAX_CONTAINERS;

	config_found(&sc->aac_dev, &sc->aac_link, scsiprint);

	/* Create the AIF thread */
	sc->aifthread = 0;
	sc->aifflags = 0;
	kthread_create_deferred(aac_create_thread, sc);

#if 0
	/* Register the shutdown method to only be called post-dump */
	sc->aac_sdh = shutdownhook_establish(aac_shutdown, (void *)sc);
#endif

	return (0);
}

void
aac_create_thread(void *arg)
{
	struct aac_softc *sc = arg;

	if (kthread_create(aac_command_thread, sc, &sc->aifthread, "%s",
	    sc->aac_dev.dv_xname)) {
		/* TODO disable aac */
		printf("%s: failed to create kernel thread, disabled",
		sc->aac_dev.dv_xname);
	}
	AAC_DPRINTF(AAC_D_MISC, ("%s: aac_create_thread\n",
	    sc->aac_dev.dv_xname));

}

/*
 * Probe for containers, create disks.
 */
void
aac_startup(struct aac_softc *sc)
{
	struct aac_fib *fib;
	struct aac_mntinfo *mi;
	struct aac_mntinforesp *mir = NULL;
	int count = 0, i = 0;


	aac_alloc_sync_fib(sc, &fib, 0);
	mi = (struct aac_mntinfo *)&fib->data[0];

	AAC_DPRINTF(AAC_D_MISC, ("%s: aac startup\n", sc->aac_dev.dv_xname));

	sc->aac_container_count = 0;
	/* loop over possible containers */
	do {
		/* request information on this container */
		bzero(mi, sizeof(struct aac_mntinfo));
		mi->Command = VM_NameServe;
		mi->MntType = FT_FILESYS;
		mi->MntCount = i;
		if (aac_sync_fib(sc, ContainerCommand, 0, fib,
				 sizeof(struct aac_mntinfo))) {
			printf("%s: error probing container %d\n",
			       sc->aac_dev.dv_xname, i);
			continue;
		}

		mir = (struct aac_mntinforesp *)&fib->data[0];
		/* XXX Need to check if count changed */
		count = mir->MntRespCount;

#if 0
		aac_add_container(sc, mir, 0);
#else
		/* 
		 * 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) {
			int drv_cyls, drv_hds, drv_secs;

			AAC_DPRINTF(AAC_D_MISC,
			    ("%s: %d: id %x  name '%.16s'  size %u  type %d\n",
			     sc->aac_dev.dv_xname, i,
			     mir->MntTable[0].ObjectId,
			     mir->MntTable[0].FileSystemName,
			     mir->MntTable[0].Capacity,
			     mir->MntTable[0].VolType));

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

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

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

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

		i++;
	} while ((i < count) && (i < AAC_MAX_CONTAINERS));

	aac_release_sync_fib(sc);

#if 0
	/* poke the bus to actually attach the child devices */
	if (bus_generic_attach(sc->aac_dev))
		printf("%s: bus_generic_attach failed\n",
		       sc->aac_dev.dv_xname);
#endif


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

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

#if 0
/*
 * Create a device to respresent a new container
 */
void
aac_add_container(struct aac_softc *sc, struct aac_mntinforesp *mir, int f)
{
	struct aac_container *co;
	device_t child;

	/* 
	 * 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)) {
		co = (struct aac_container *)malloc(sizeof *co, M_DEVBUF,
		       M_NOWAIT);
		if (co == NULL)
			panic("Out of memory?!\n");
		bzero(co, sizeof *co);
		AAC_DPRINTF(AAC_D_MISC,
			    ("%s: id %x  name '%.16s'  size %u  type %d\n", 
			     sc->aac_dev.dv_xname,
			     mir->MntTable[0].ObjectId,
			     mir->MntTable[0].FileSystemName,
			     mir->MntTable[0].Capacity,
			     mir->MntTable[0].VolType);
	
		if ((child = device_add_child(sc->aac_dev, "aacd", -1)) == NULL)
			printf("%s: device_add_child failed\n",
			       sc->aac_dev.dv_xname);
		else
			device_set_ivars(child, co);
		device_set_desc(child, aac_describe_code(aac_container_types,
				mir->MntTable[0].VolType));
		co->co_disk = child;
		co->co_found = f;
		bcopy(&mir->MntTable[0], &co->co_mntobj,
		      sizeof(struct aac_mntobj));
		AAC_LOCK_ACQUIRE(&sc->aac_container_lock);
		TAILQ_INSERT_TAIL(&sc->aac_container_tqh, co, co_link);
		AAC_LOCK_RELEASE(&sc->aac_container_lock);
	}
}
#endif

#if 0
/*
 * Free all of the resources associated with (sc)
 *
 * Should not be called if the controller is active.
 */
void
aac_free(struct aac_softc *sc)
{

	debug_called(1);

	/* remove the control device */
	if (sc->aac_dev_t != NULL)
		destroy_dev(sc->aac_dev_t);

	/* throw away any FIB buffers, discard the FIB DMA tag */
	aac_free_commands(sc);
	if (sc->aac_fib_dmat)
		bus_dma_tag_destroy(sc->aac_fib_dmat);

	free(sc->aac_commands, M_AACBUF);

	/* destroy the common area */
	if (sc->aac_common) {
		bus_dmamap_unload(sc->aac_common_dmat, sc->aac_common_dmamap);
		bus_dmamem_free(sc->aac_common_dmat, sc->aac_common,
				sc->aac_common_dmamap);
	}
	if (sc->aac_common_dmat)
		bus_dma_tag_destroy(sc->aac_common_dmat);

	/* disconnect the interrupt handler */
	if (sc->aac_intr)
		bus_teardown_intr(sc->aac_dev, sc->aac_irq, sc->aac_intr);
	if (sc->aac_irq != NULL)
		bus_release_resource(sc->aac_dev, SYS_RES_IRQ, sc->aac_irq_rid,
				     sc->aac_irq);

	/* destroy data-transfer DMA tag */
	if (sc->aac_buffer_dmat)
		bus_dma_tag_destroy(sc->aac_buffer_dmat);

	/* destroy the parent DMA tag */
	if (sc->aac_parent_dmat)
		bus_dma_tag_destroy(sc->aac_parent_dmat);

	/* release the register window mapping */
	if (sc->aac_regs_resource != NULL)
		bus_release_resource(sc->aac_dev, SYS_RES_MEMORY,
				     sc->aac_regs_rid, sc->aac_regs_resource);
}

/*
 * Disconnect from the controller completely, in preparation for unload.
 */
int
aac_detach(device_t dev)
{
	struct aac_softc *sc;
	struct aac_container *co;
	struct aac_sim	*sim;
	int error;

	debug_called(1);

	sc = device_get_softc(dev);

	if (sc->aac_state & AAC_STATE_OPEN)
		return(EBUSY);

	/* Remove the child containers */
	while ((co = TAILQ_FIRST(&sc->aac_container_tqh)) != NULL) {
		error = device_delete_child(dev, co->co_disk);
		if (error)
			return (error);
		TAILQ_REMOVE(&sc->aac_container_tqh, co, co_link);
		free(co, M_AACBUF);
	}

	/* Remove the CAM SIMs */
	while ((sim = TAILQ_FIRST(&sc->aac_sim_tqh)) != NULL) {
		TAILQ_REMOVE(&sc->aac_sim_tqh, sim, sim_link);
		error = device_delete_child(dev, sim->sim_dev);
		if (error)
			return (error);
		free(sim, M_AACBUF);
	}

	if (sc->aifflags & AAC_AIFFLAGS_RUNNING) {
		sc->aifflags |= AAC_AIFFLAGS_EXIT;
		wakeup(sc->aifthread);
		tsleep(sc->aac_dev, PUSER | PCATCH, "aacdch", 30 * hz);
	}

	if (sc->aifflags & AAC_AIFFLAGS_RUNNING)
		panic("Cannot shutdown AIF thread\n");

	if ((error = aac_shutdown(dev)))
		return(error);

	EVENTHANDLER_DEREGISTER(shutdown_final, sc->eh);

	aac_free(sc);

	return(0);
}

/*
 * Bring the controller down to a dormant state and detach all child devices.
 *
 * This function is called before detach or system shutdown.
 *
 * Note that we can assume that the bioq on the controller is empty, as we won't
 * allow shutdown if any device is open.
 */
int
aac_shutdown(device_t dev)
{
	struct aac_softc *sc;
	struct aac_fib *fib;
	struct aac_close_command *cc;

	debug_called(1);

	sc = device_get_softc(dev);

	sc->aac_state |= AAC_STATE_SUSPEND;

	/* 
	 * Send a Container shutdown followed by a HostShutdown FIB to the
	 * controller to convince it that we don't want to talk to it anymore.
	 * We've been closed and all I/O completed already
	 */
	device_printf(sc->aac_dev, "shutting down controller...");

	aac_alloc_sync_fib(sc, &fib, AAC_SYNC_LOCK_FORCE);
	cc = (struct aac_close_command *)&fib->data[0];

	bzero(cc, sizeof(struct aac_close_command));
	cc->Command = VM_CloseAll;
	cc->ContainerId = 0xffffffff;
	if (aac_sync_fib(sc, ContainerCommand, 0, fib,
	    sizeof(struct aac_close_command)))
		printf("FAILED.\n");
	else
		printf("done\n");
	else {
		fib->data[0] = 0;
		/*
		 * XXX Issuing this command to the controller makes it
		 * shut down but also keeps it from coming back up
		 * without a reset of the PCI bus.  This is not
		 * desirable if you are just unloading the driver
		 * module with the intent to reload it later.
		 */
		if (aac_sync_fib(sc, FsaHostShutdown, AAC_FIBSTATE_SHUTDOWN,
		    fib, 1)) {
			printf("FAILED.\n");
		} else {
			printf("done.\n");
		}
	}

	AAC_MASK_INTERRUPTS(sc);

	return(0);
}

/*
 * Bring the controller to a quiescent state, ready for system suspend.
 */
int
aac_suspend(device_t dev)
{
	struct aac_softc *sc;

	debug_called(1);

	sc = device_get_softc(dev);

	sc->aac_state |= AAC_STATE_SUSPEND;
	
	AAC_MASK_INTERRUPTS(sc);
	return(0);
}

/*
 * Bring the controller back to a state ready for operation.
 */
int
aac_resume(device_t dev)
{
	struct aac_softc *sc;

	debug_called(1);

	sc = device_get_softc(dev);

	sc->aac_state &= ~AAC_STATE_SUSPEND;
	AAC_UNMASK_INTERRUPTS(sc);
	return(0);
}
#endif

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


	/*
	 * Read the status register directly.  This is faster than taking the
	 * driver lock and reading the queues directly.  It also saves having
	 * to turn parts of the driver lock into a spin mutex, which would be
	 * ugly.
	 */
	reason = AAC_GET_ISTATUS(sc);
	AAC_CLEAR_ISTATUS(sc, reason);
	(void)AAC_GET_ISTATUS(sc);

	if (reason == 0)
		return (0);

	AAC_DPRINTF(AAC_D_INTR, ("%s: intr: sc=%p: reason=%#x\n",
				 sc->aac_dev.dv_xname, sc, reason));

	/* controller wants to talk to us */
	if (reason & (AAC_DB_PRINTF | AAC_DB_COMMAND_READY |
		      AAC_DB_RESPONSE_READY)) {

		if (reason & AAC_DB_RESPONSE_READY) {
			/* handle completion processing */
			if (sc->aifflags & AAC_AIFFLAGS_RUNNING) {
				sc->aifflags |= AAC_AIFFLAGS_COMPLETE;
			} else {
				AAC_LOCK_ACQUIRE(&sc->aac_io_lock);
				aac_complete(sc);
				AAC_LOCK_RELEASE(&sc->aac_io_lock);
			}
		}


		/*
		 * XXX Make sure that we don't get fooled by strange messages
		 * that start with a NULL.
		 */
		if (reason & AAC_DB_PRINTF)
			if (sc->aac_common->ac_printf[0] == 0)
				sc->aac_common->ac_printf[0] = 32;

		/*
		 * This might miss doing the actual wakeup.  However, the
		 * msleep that this is waking up has a timeout, so it will
		 * wake up eventually.  AIFs and printfs are low enough
		 * priority that they can handle hanging out for a few seconds
		 * if needed.
		 */
		if (sc->aifthread)
			wakeup(sc->aifthread);

	}

	return (1);
}

/*
 * Command Processing
 */

/*
 * Start as much queued I/O as possible on the controller
 */
void
aac_startio(struct aac_softc *sc)
{
	struct aac_command *cm;

	AAC_DPRINTF(AAC_D_CMD, ("%s: start command", sc->aac_dev.dv_xname));

	if (sc->flags & AAC_QUEUE_FRZN) {
		AAC_DPRINTF(AAC_D_CMD, (": queue frozen"));
		return;
	}

	AAC_DPRINTF(AAC_D_CMD, ("\n"));

	for (;;) {
		/*
		 * Try to get a command that's been put off for lack of 
		 * resources
		 */
		cm = aac_dequeue_ready(sc);

		/*
		 * Try to build a command off the bio queue (ignore error 
		 * return)
		 */
		if (cm == NULL) {
			AAC_DPRINTF(AAC_D_CMD, ("\n"));
			aac_bio_command(sc, &cm);
			AAC_DPRINTF(AAC_D_CMD, ("%s: start done bio",
						sc->aac_dev.dv_xname));
		}

		/* nothing to do? */
		if (cm == NULL)
			break;

		/*
		 * Try to give the command to the controller.  Any error is
		 * catastrophic since it means that bus_dmamap_load() failed.
		 */
		if (aac_map_command(cm) != 0)
			panic("aac: error mapping command %p\n", cm);

		AAC_DPRINTF(AAC_D_CMD, ("\n%s: another command",
					sc->aac_dev.dv_xname));
	}

	AAC_DPRINTF(AAC_D_CMD, ("\n"));
}

/*
 * Deliver a command to the controller; allocate controller resources at the
 * last moment when possible.
 */
int
aac_map_command(struct aac_command *cm)
{
	struct aac_softc *sc = cm->cm_sc;
	int error = 0;

	AAC_DPRINTF(AAC_D_CMD, (": map command"));

	/* don't map more than once */
	if (cm->cm_flags & AAC_CMD_MAPPED)
		panic("aac: command %p already mapped", cm);

	if (cm->cm_datalen != 0) {
		error = bus_dmamap_load(sc->aac_dmat, cm->cm_datamap,
					cm->cm_data, cm->cm_datalen, NULL,
					BUS_DMA_NOWAIT);
		if (error)
			return (error);

		aac_map_command_sg(cm, cm->cm_datamap->dm_segs,
				   cm->cm_datamap->dm_nsegs, 0);
	} else {
		aac_map_command_sg(cm, NULL, 0, 0);
	}

	return (error);
}

/*
 * Handle notification of one or more FIBs coming from the controller.
 */
void
aac_command_thread(void *arg)
{
	struct aac_softc *sc = arg;
	struct aac_fib *fib;
	u_int32_t fib_size;
	int size, retval;

	AAC_DPRINTF(AAC_D_THREAD, ("%s: aac_command_thread: starting\n",
	    sc->aac_dev.dv_xname));
	AAC_LOCK_ACQUIRE(&sc->aac_io_lock);
	sc->aifflags = AAC_AIFFLAGS_RUNNING;

	while ((sc->aifflags & AAC_AIFFLAGS_EXIT) == 0) {

		AAC_DPRINTF(AAC_D_THREAD,
		    ("%s: aac_command_thread: aifflags=%#x\n",
		    sc->aac_dev.dv_xname, sc->aifflags));
		retval = 0;

		if ((sc->aifflags & AAC_AIFFLAGS_PENDING) == 0) {
			AAC_DPRINTF(AAC_D_THREAD,
				    ("%s: command thread sleeping\n",
				     sc->aac_dev.dv_xname));
			AAC_LOCK_RELEASE(&sc->aac_io_lock);
			retval = tsleep(sc->aifthread, PRIBIO, "aifthd",
					AAC_PERIODIC_INTERVAL * hz);
			AAC_LOCK_ACQUIRE(&sc->aac_io_lock);
		}

		if ((sc->aifflags & AAC_AIFFLAGS_COMPLETE) != 0) {
			aac_complete(sc);
			sc->aifflags &= ~AAC_AIFFLAGS_COMPLETE;
		}

		/*
		 * While we're here, check to see if any commands are stuck.
		 * This is pretty low-priority, so it's ok if it doesn't
		 * always fire.
		 */
		if (retval == EWOULDBLOCK)
			aac_timeout(sc);

		/* Check the hardware printf message buffer */
		if (sc->aac_common->ac_printf[0] != 0)
			aac_print_printf(sc);

		/* Also check to see if the adapter has a command for us. */
		while (aac_dequeue_fib(sc, AAC_HOST_NORM_CMD_QUEUE,
				       &fib_size, &fib) == 0) {
	
			AAC_PRINT_FIB(sc, fib);
	
			switch (fib->Header.Command) {
			case AifRequest:
				//aac_handle_aif(sc, fib);
				break;
			default:
				printf("%s: unknown command from controller\n",
				       sc->aac_dev.dv_xname);
				break;
			}

			if ((fib->Header.XferState == 0) ||
			    (fib->Header.StructType != AAC_FIBTYPE_TFIB))
				break;

			/* Return the AIF to the controller. */
			if (fib->Header.XferState & AAC_FIBSTATE_FROMADAP) {
				fib->Header.XferState |= AAC_FIBSTATE_DONEHOST;
				*(AAC_FSAStatus*)fib->data = ST_OK;

				/* XXX Compute the Size field? */
				size = fib->Header.Size;
				if (size > sizeof(struct aac_fib)) {
					size = sizeof(struct aac_fib);
					fib->Header.Size = size;
				}
		
				/*
				 * Since we did not generate this command, it
				 * cannot go through the normal
				 * enqueue->startio chain.
				 */
				aac_enqueue_response(sc,
						     AAC_ADAP_NORM_RESP_QUEUE,
						     fib);
			}
		}
	}
	sc->aifflags &= ~AAC_AIFFLAGS_RUNNING;
	AAC_LOCK_RELEASE(&sc->aac_io_lock);

#if 0
	/*
	 * if we ever implement detach, we should have detach tsleep
	 * to wait for this thread to finish
	 */
	wakeup(sc->aac_dev);
#endif

	AAC_DPRINTF(AAC_D_THREAD, ("%s: aac_command_thread: exiting\n",
	    sc->aac_dev.dv_xname));
	kthread_exit(0);
}

/*
 * Process completed commands.
 */
void
aac_complete(void *context)
{
	struct aac_softc *sc = (struct aac_softc *)context;
	struct aac_command *cm;
	struct aac_fib *fib;
	u_int32_t fib_size;

	AAC_DPRINTF(AAC_D_CMD, ("%s: complete", sc->aac_dev.dv_xname));

	/* pull completed commands off the queue */
	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 hand off for processing */
		cm = sc->aac_commands + fib->Header.SenderData;
		if (cm == NULL) {
			AAC_PRINT_FIB(sc, fib);
			break;
		}

		aac_remove_busy(cm);
		aac_unmap_command(cm);
		cm->cm_flags |= AAC_CMD_COMPLETED;

		/* is there a completion handler? */
		if (cm->cm_complete != NULL) {
			cm->cm_complete(cm);
		} else {
			/* assume that someone is sleeping on this command */
			wakeup(cm);
		}
	}

	AAC_DPRINTF(AAC_D_CMD, ("\n"));
	/* see if we can start some more I/O */
	sc->flags &= ~AAC_QUEUE_FRZN;
	aac_startio(sc);
}

/*
 * Get a bio and build a command to go with it.
 */
int
aac_bio_command(struct aac_softc *sc, struct aac_command **cmp)
{
	struct aac_command *cm;
	struct aac_fib *fib;
	struct scsi_xfer *xs;
	u_int8_t opcode = 0;

	AAC_DPRINTF(AAC_D_CMD, ("%s: bio command", sc->aac_dev.dv_xname));

	/* get the resources we will need */
	if ((cm = aac_dequeue_bio(sc)) == NULL)
		goto fail;
	xs = cm->cm_private;

	/* build the FIB */
	fib = cm->cm_fib;
	fib->Header.Size = sizeof(struct aac_fib_header);
	fib->Header.XferState =  
		AAC_FIBSTATE_HOSTOWNED   | 
		AAC_FIBSTATE_INITIALISED | 
		AAC_FIBSTATE_EMPTY	 | 
		AAC_FIBSTATE_FROMHOST	 |
		AAC_FIBSTATE_REXPECTED   |
		AAC_FIBSTATE_NORM	 |
		AAC_FIBSTATE_ASYNC	 |
		AAC_FIBSTATE_FAST_RESPONSE;

	switch(xs->cmd->opcode) {
	case READ_COMMAND:
	case READ_BIG:
		opcode = READ_COMMAND;
		break;
	case WRITE_COMMAND:
	case WRITE_BIG:
		opcode = WRITE_COMMAND;
		break;
	default:
		panic("%s: invalid opcode %#x\n", sc->aac_dev.dv_xname,
		      xs->cmd->opcode);
	}

	/* build the read/write request */
	if ((sc->flags & AAC_FLAGS_SG_64BIT) == 0) {
		fib->Header.Command = ContainerCommand;
		if (opcode == READ_COMMAND) {
			struct aac_blockread *br;
			br = (struct aac_blockread *)&fib->data[0];
			br->Command = VM_CtBlockRead;
			br->ContainerId = xs->sc_link->target;
			br->BlockNumber = cm->cm_blkno;
			br->ByteCount = cm->cm_bcount * AAC_BLOCK_SIZE;
			fib->Header.Size += sizeof(struct aac_blockread);
			cm->cm_sgtable = &br->SgMap;
			cm->cm_flags |= AAC_CMD_DATAIN;
		} else {
			struct aac_blockwrite *bw;
			bw = (struct aac_blockwrite *)&fib->data[0];
			bw->Command = VM_CtBlockWrite;
			bw->ContainerId = xs->sc_link->target;
			bw->BlockNumber = cm->cm_blkno;
			bw->ByteCount = cm->cm_bcount * AAC_BLOCK_SIZE;
			bw->Stable = CUNSTABLE;
			fib->Header.Size += sizeof(struct aac_blockwrite);
			cm->cm_flags |= AAC_CMD_DATAOUT;
			cm->cm_sgtable = &bw->SgMap;
		}
	} else {
		fib->Header.Command = ContainerCommand64;
		if (opcode == READ_COMMAND) {
			struct aac_blockread64 *br;
			br = (struct aac_blockread64 *)&fib->data[0];
			br->Command = VM_CtHostRead64;
			br->ContainerId = xs->sc_link->target;
			br->BlockNumber = cm->cm_blkno;
			br->SectorCount = cm->cm_bcount;
			br->Pad = 0;
			br->Flags = 0;
			fib->Header.Size += sizeof(struct aac_blockread64);
			cm->cm_flags |= AAC_CMD_DATAOUT;
			(struct aac_sg_table64 *)cm->cm_sgtable = &br->SgMap64;
		} else {
			struct aac_blockwrite64 *bw;
			bw = (struct aac_blockwrite64 *)&fib->data[0];
			bw->Command = VM_CtHostWrite64;
			bw->ContainerId = xs->sc_link->target;
			bw->BlockNumber = cm->cm_blkno;
			bw->SectorCount = cm->cm_bcount;
			bw->Pad = 0;
			bw->Flags = 0;
			fib->Header.Size += sizeof(struct aac_blockwrite64);
			cm->cm_flags |= AAC_CMD_DATAIN;
			(struct aac_sg_table64 *)cm->cm_sgtable = &bw->SgMap64;
		}
	}

	*cmp = cm;
	AAC_DPRINTF(AAC_D_CMD, ("\n"));
	return(0);

fail:
	AAC_DPRINTF(AAC_D_CMD, ("\n"));
	return(ENOMEM);
}

/*
 * Handle a bio-instigated command that has been completed.
 */
void
aac_bio_complete(struct aac_command *cm)
{
	struct aac_blockread_response *brr;
	struct aac_blockwrite_response *bwr;
	struct scsi_xfer *xs = (struct scsi_xfer *)cm->cm_private;
	struct buf *bp = xs->bp;
	AAC_FSAStatus status;
	int s;

	AAC_DPRINTF(AAC_D_CMD,
		    ("%s: bio complete\n", cm->cm_sc->aac_dev.dv_xname));

	s = splbio();
	aac_release_command(cm);
	if (bp == NULL)
		goto exit;

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

	/* 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;

		/* pass an error string out to the disk layer */
		aac_describe_code(aac_command_status_table, status);
	}

 exit:
	xs->error = XS_NOERROR;
	xs->resid = 0;
	xs->flags |= ITSDONE;
	scsi_done(xs);
	splx(s);
}

/*
 * Submit a command to the controller, return when it completes.
 * XXX This is very dangerous!  If the card has gone out to lunch, we could
 *     be stuck here forever.  At the same time, signals are not caught
 *     because there is a risk that a signal could wakeup the tsleep before
 *     the card has a chance to complete the command.  The passed in timeout
 *     is ignored for the same reason.  Since there is no way to cancel a
 *     command in progress, we should probably create a 'dead' queue where
 *     commands go that have been interrupted/timed-out/etc, that keeps them
 *     out of the free pool.  That way, if the card is just slow, it won't
 *     spam the memory of a command that has been recycled.
 */
int
aac_wait_command(struct aac_command *cm, int timeout)
{
	struct aac_softc *sc = cm->cm_sc;
	int error = 0;

	AAC_DPRINTF(AAC_D_CMD, (": wait for command"));

	/* Put the command on the ready queue and get things going */
	cm->cm_queue = AAC_ADAP_NORM_CMD_QUEUE;
	aac_enqueue_ready(cm);
	AAC_DPRINTF(AAC_D_CMD, ("\n"));
	aac_startio(sc);
	while (!(cm->cm_flags & AAC_CMD_COMPLETED) && (error != EWOULDBLOCK)) {
		AAC_DPRINTF(AAC_D_MISC, ("%s: sleeping until command done\n",
					 sc->aac_dev.dv_xname));
		AAC_LOCK_RELEASE(&sc->aac_io_lock);
		error = tsleep(cm, PRIBIO, "aacwait", timeout);
		AAC_LOCK_ACQUIRE(&sc->aac_io_lock);
	}
	return (error);
}

/*
 *Command Buffer Management
 */

/*
 * Allocate a command.
 */
int
aac_alloc_command(struct aac_softc *sc, struct aac_command **cmp)
{
	struct aac_command *cm;

	AAC_DPRINTF(AAC_D_CMD, (": allocate command"));
	if ((cm = aac_dequeue_free(sc)) == NULL) {
		AAC_DPRINTF(AAC_D_CMD, (" failed"));
		return (EBUSY);
	}

	*cmp = cm;
	return(0);
}

/*
 * Release a command back to the freelist.
 */
void
aac_release_command(struct aac_command *cm)
{
	AAC_DPRINTF(AAC_D_CMD, (": release command"));

	/* (re)initialise the command/FIB */
	cm->cm_sgtable = NULL;
	cm->cm_flags = 0;
	cm->cm_complete = NULL;
	cm->cm_private = NULL;
	cm->cm_fib->Header.XferState = AAC_FIBSTATE_EMPTY;
	cm->cm_fib->Header.StructType = AAC_FIBTYPE_TFIB;
	cm->cm_fib->Header.Flags = 0;
	cm->cm_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.
	 */
	cm->cm_fib->Header.ReceiverFibAddress = (u_int32_t)cm->cm_fibphys;
	cm->cm_fib->Header.SenderData = 0;

	aac_enqueue_free(cm);
}

/*
 * Allocate and initialise commands/FIBs for this adapter.
 */
int
aac_alloc_commands(struct aac_softc *sc)
{
	struct aac_command *cm;
	struct aac_fibmap *fm;
	int i, error;

	if (sc->total_fibs + AAC_FIB_COUNT > sc->aac_max_fibs)
		return (ENOMEM);

	fm = malloc(sizeof(struct aac_fibmap), M_DEVBUF, M_NOWAIT);
	if (fm == NULL)
		goto exit;
	bzero(fm, sizeof(struct aac_fibmap));

	/* allocate the FIBs in DMAable memory and load them */
	if (bus_dmamem_alloc(sc->aac_dmat, AAC_FIBMAP_SIZE, PAGE_SIZE, 0,
	    &fm->aac_seg, 1, &fm->aac_nsegs, BUS_DMA_NOWAIT)) {
		printf("%s: can't alloc FIBs\n", sc->aac_dev.dv_xname);
		error = ENOBUFS;
		goto exit_alloc;
	}

	if (bus_dmamem_map(sc->aac_dmat, &fm->aac_seg, 1,
	    AAC_FIBMAP_SIZE, (caddr_t *)&fm->aac_fibs, BUS_DMA_NOWAIT)) {
		printf("%s: can't map FIB structure\n", sc->aac_dev.dv_xname);
		error = ENOBUFS;
		goto exit_map;
	}

	if (bus_dmamap_create(sc->aac_dmat, AAC_FIBMAP_SIZE, 1,
	    AAC_FIBMAP_SIZE, 0, BUS_DMA_NOWAIT, &fm->aac_fibmap)) {
		printf("%s: can't create dma map\n", sc->aac_dev.dv_xname);
		error = ENOBUFS;
		goto exit_create;
	}

	if (bus_dmamap_load(sc->aac_dmat, fm->aac_fibmap, fm->aac_fibs, 
	    AAC_FIBMAP_SIZE, NULL, BUS_DMA_NOWAIT)) {
		printf("%s: can't load dma map\n", sc->aac_dev.dv_xname);
		error = ENOBUFS;
		goto exit_load;
	}

	/* initialise constant fields in the command structure */
	AAC_LOCK_ACQUIRE(&sc->aac_io_lock);
	bzero(fm->aac_fibs, AAC_FIB_COUNT * sizeof(struct aac_fib));
	for (i = 0; i < AAC_FIB_COUNT; i++) {
		cm = sc->aac_commands + sc->total_fibs;
		fm->aac_commands = cm;
		cm->cm_sc = sc;
		cm->cm_fib = fm->aac_fibs + i;
		cm->cm_fibphys = fm->aac_fibmap->dm_segs[0].ds_addr +
			(i * sizeof(struct aac_fib));
		cm->cm_index = sc->total_fibs;

		if (bus_dmamap_create(sc->aac_dmat, MAXBSIZE, AAC_MAXSGENTRIES,
		    MAXBSIZE, 0, BUS_DMA_NOWAIT, &cm->cm_datamap)) {
			break;
		}
		aac_release_command(cm);
		sc->total_fibs++;
	}

	if (i > 0) {
		TAILQ_INSERT_TAIL(&sc->aac_fibmap_tqh, fm, fm_link);
		AAC_DPRINTF(AAC_D_MISC, ("%s: total_fibs= %d\n",
					 sc->aac_dev.dv_xname,
					 sc->total_fibs));
		AAC_LOCK_RELEASE(&sc->aac_io_lock);
		return (0);
	} 

 exit_load:
	bus_dmamap_destroy(sc->aac_dmat, fm->aac_fibmap);
 exit_create:
	bus_dmamem_unmap(sc->aac_dmat, (caddr_t)fm->aac_fibs, AAC_FIBMAP_SIZE);
 exit_map:
	bus_dmamem_free(sc->aac_dmat, &fm->aac_seg, fm->aac_nsegs);
 exit_alloc:
	free(fm, M_DEVBUF);
 exit:
	AAC_LOCK_RELEASE(&sc->aac_io_lock);
	return (error);
}

/*
 * Free FIBs owned by this adapter.
 */
void
aac_free_commands(struct aac_softc *sc)
{
	struct aac_fibmap *fm;
	struct aac_command *cm;
	int i;

	while ((fm = TAILQ_FIRST(&sc->aac_fibmap_tqh)) != NULL) {

		TAILQ_REMOVE(&sc->aac_fibmap_tqh, fm, fm_link);

		/*
		 * We check against total_fibs to handle partially
		 * allocated blocks.
		 */
		for (i = 0; i < AAC_FIB_COUNT && sc->total_fibs--; i++) {
			cm = fm->aac_commands + i;
			bus_dmamap_destroy(sc->aac_dmat, cm->cm_datamap);
		}

		bus_dmamap_unload(sc->aac_dmat, fm->aac_fibmap);
		bus_dmamap_destroy(sc->aac_dmat, fm->aac_fibmap);
		bus_dmamem_unmap(sc->aac_dmat, (caddr_t)fm->aac_fibs,
				 AAC_FIBMAP_SIZE);
		bus_dmamem_free(sc->aac_dmat, &fm->aac_seg, fm->aac_nsegs);
		free(fm, M_DEVBUF);
	}
}


/*
 * Command-mapping helper function - populate this command's s/g table.
 */
void
aac_map_command_sg(void *arg, bus_dma_segment_t *segs, int nseg, int error)
{
	struct aac_command *cm = arg;
	struct aac_softc *sc = cm->cm_sc;
	struct aac_fib *fib = cm->cm_fib;
	int i;

	/* copy into the FIB */
	if (cm->cm_sgtable != NULL) {
		if ((cm->cm_sc->flags & AAC_FLAGS_SG_64BIT) == 0) {
			struct aac_sg_table *sg = cm->cm_sgtable;
			sg->SgCount = nseg;
			for (i = 0; i < nseg; i++) {
				sg->SgEntry[i].SgAddress = segs[i].ds_addr;
				sg->SgEntry[i].SgByteCount = segs[i].ds_len;
			}
			/* update the FIB size for the s/g count */
			fib->Header.Size += nseg * sizeof(struct aac_sg_entry);
		} else {
			struct aac_sg_table64 *sg;
			sg = (struct aac_sg_table64 *)cm->cm_sgtable;
			sg->SgCount = nseg;
			for (i = 0; i < nseg; i++) {
				sg->SgEntry64[i].SgAddress = segs[i].ds_addr;
				sg->SgEntry64[i].SgByteCount = segs[i].ds_len;
			}
			/* update the FIB size for the s/g count */
			fib->Header.Size += nseg*sizeof(struct aac_sg_entry64);
		}
	}

	/* Fix up the address values in the FIB.  Use the command array index
	 * instead of a pointer since these fields are only 32 bits.  Shift
	 * the SenderFibAddress over to make room for the fast response bit.
	 */
	cm->cm_fib->Header.SenderFibAddress = (cm->cm_index << 1);
	cm->cm_fib->Header.ReceiverFibAddress = cm->cm_fibphys;

	/* save a pointer to the command for speedy reverse-lookup */
	cm->cm_fib->Header.SenderData = cm->cm_index;

	if (cm->cm_flags & AAC_CMD_DATAIN)
		bus_dmamap_sync(sc->aac_dmat, cm->cm_datamap, 0,
				cm->cm_datamap->dm_mapsize,
				BUS_DMASYNC_PREREAD);
	if (cm->cm_flags & AAC_CMD_DATAOUT)
		bus_dmamap_sync(sc->aac_dmat, cm->cm_datamap, 0,
				cm->cm_datamap->dm_mapsize,
				BUS_DMASYNC_PREWRITE);
	cm->cm_flags |= AAC_CMD_MAPPED;

	/* put the FIB on the outbound queue */
	if (aac_enqueue_fib(sc, cm->cm_queue, cm) == EBUSY) {
		aac_remove_busy(cm);
		aac_unmap_command(cm);
		aac_requeue_ready(cm);
	}
}

/*
 * Unmap a command from controller-visible space.
 */
void
aac_unmap_command(struct aac_command *cm)
{
	struct aac_softc *sc = cm->cm_sc;

	if (!(cm->cm_flags & AAC_CMD_MAPPED))
		return;

	if (cm->cm_datalen != 0) {
		if (cm->cm_flags & AAC_CMD_DATAIN)
			bus_dmamap_sync(sc->aac_dmat, cm->cm_datamap, 0,
					cm->cm_datamap->dm_mapsize,
					BUS_DMASYNC_POSTREAD);
		if (cm->cm_flags & AAC_CMD_DATAOUT)
			bus_dmamap_sync(sc->aac_dmat, cm->cm_datamap, 0,
					cm->cm_datamap->dm_mapsize,
					BUS_DMASYNC_POSTWRITE);

		bus_dmamap_unload(sc->aac_dmat, cm->cm_datamap);
	}
	cm->cm_flags &= ~AAC_CMD_MAPPED;
}

/*
 * Hardware Interface
 */

/*
 * Initialise the adapter.
 */
int
aac_check_firmware(struct aac_softc *sc)
{
	u_int32_t major, minor, options;

	/*
	 * Retrieve the firmware version numbers.  Dell PERC2/QC cards with
	 * firmware version 1.x are not compatible with this driver.
	 */
	if (sc->flags & AAC_FLAGS_PERC2QC) {
		if (aac_sync_command(sc, AAC_MONKER_GETKERNVER, 0, 0, 0, 0,
				     NULL)) {
			printf("%s: Error reading firmware version\n",
			       sc->aac_dev.dv_xname);
			return (EIO);
		}

		/* These numbers are stored as ASCII! */
		major = (AAC_GET_MAILBOX(sc, 1) & 0xff) - 0x30;
		minor = (AAC_GET_MAILBOX(sc, 2) & 0xff) - 0x30;
		if (major == 1) {
			printf("%s: Firmware version %d.%d is not supported\n",
			       sc->aac_dev.dv_xname, major, minor);
			return (EINVAL);
		}
	}

	/*
	 * Retrieve the capabilities/supported options word so we know what
	 * work-arounds to enable.
	 */
	if (aac_sync_command(sc, AAC_MONKER_GETINFO, 0, 0, 0, 0, NULL)) {
		printf("%s: RequestAdapterInfo failed\n",
		       sc->aac_dev.dv_xname);
		return (EIO);
	}
	options = AAC_GET_MAILBOX(sc, 1);
	sc->supported_options = options;

	if ((options & AAC_SUPPORTED_4GB_WINDOW) != 0 &&
	    (sc->flags & AAC_FLAGS_NO4GB) == 0)
		sc->flags |= AAC_FLAGS_4GB_WINDOW;
	if (options & AAC_SUPPORTED_NONDASD)
		sc->flags |= AAC_FLAGS_ENABLE_CAM;
	if ((options & AAC_SUPPORTED_SGMAP_HOST64) != 0
	     && (sizeof(bus_addr_t) > 4)) {
		printf("%s: Enabling 64-bit address support\n",
		       sc->aac_dev.dv_xname);
		sc->flags |= AAC_FLAGS_SG_64BIT;
	}

	/* Check for broken hardware that does a lower number of commands */
	if ((sc->flags & AAC_FLAGS_256FIBS) == 0)
		sc->aac_max_fibs = AAC_MAX_FIBS;
	else
		sc->aac_max_fibs = 256;

	return (0);
}

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

	/*
	 * First wait for the adapter to come ready.
	 */
	then = time_second;
	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->aac_dev.dv_xname);
			return (ENXIO);
		}
		if (code & AAC_KERNEL_PANIC) {
			printf("%s: FATAL: controller kernel panic\n",
			    sc->aac_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->aac_dev.dv_xname, code);
		return (ENXIO);
	}

	/*
	 * Work around a bug in the 2120 and 2200 that cannot DMA commands
	 * below address 8192 in physical memory.
	 * XXX If the padding is not needed, can it be put to use instead
	 * of ignored?
	 */
	if (bus_dmamem_alloc(sc->aac_dmat, AAC_COMMON_ALLOCSIZE, PAGE_SIZE, 0,
			     &seg, 1, &nsegs, BUS_DMA_NOWAIT)) {
		printf("%s: can't allocate common structure\n",
		    sc->aac_dev.dv_xname);
		return (ENOMEM);
	}
	state++;

	if (bus_dmamem_map(sc->aac_dmat, &seg, nsegs, AAC_COMMON_ALLOCSIZE,
			   (caddr_t *)&sc->aac_common, BUS_DMA_NOWAIT)) {
		printf("%s: can't map common structure\n",
		    sc->aac_dev.dv_xname);
		error = ENOMEM;
		goto bail_out;
	}
	state++;

	if (bus_dmamap_create(sc->aac_dmat, AAC_COMMON_ALLOCSIZE, 1,
	    AAC_COMMON_ALLOCSIZE, 0, BUS_DMA_NOWAIT, &sc->aac_common_map)) {
		printf("%s: can't create dma map\n", sc->aac_dev.dv_xname);
		error = ENOBUFS;
		goto bail_out;
	}
	state++;

	if (bus_dmamap_load(sc->aac_dmat, sc->aac_common_map, sc->aac_common, 
	    AAC_COMMON_ALLOCSIZE, NULL, BUS_DMA_NOWAIT)) {
		printf("%s: can't load dma map\n", sc->aac_dev.dv_xname);
		error = ENOBUFS;
		goto bail_out;
	}
	state++;

	sc->aac_common_busaddr = sc->aac_common_map->dm_segs[0].ds_addr;

	if (sc->aac_common_busaddr < 8192) {
		(uint8_t *)sc->aac_common += 8192;
		sc->aac_common_busaddr += 8192;
	}
	bzero(sc->aac_common, sizeof *sc->aac_common);
    
	/* Allocate some FIBs and associated command structs */
	TAILQ_INIT(&sc->aac_fibmap_tqh);
	sc->aac_commands = malloc(AAC_MAX_FIBS * sizeof(struct aac_command),
				  M_DEVBUF, M_WAITOK);
	bzero(sc->aac_commands, AAC_MAX_FIBS * sizeof(struct aac_command));
	while (sc->total_fibs < AAC_MAX_FIBS) {
		if (aac_alloc_commands(sc) != 0)
			break;
	}
	if (sc->total_fibs == 0)
		goto out;
	
	/*
	 * Fill in the init structure.  This tells the adapter about the
	 * physical location of various important shared data structures.
	 */
	ip = &sc->aac_common->ac_init;
	ip->InitStructRevision = AAC_INIT_STRUCT_REVISION;
	ip->MiniPortRevision = AAC_INIT_STRUCT_MINIPORT_REVISION;

	ip->AdapterFibsPhysicalAddress = sc->aac_common_busaddr +
					 offsetof(struct aac_common, ac_fibs);
	ip->AdapterFibsVirtualAddress = 0;
	ip->AdapterFibsSize = AAC_ADAPTER_FIBS * sizeof(struct aac_fib);
	ip->AdapterFibAlign = sizeof(struct aac_fib);

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

	/* 
	 * The adapter assumes that pages are 4K in size, except on some
 	 * broken firmware versions that do the page->byte conversion twice,
	 * therefore 'assuming' that this value is in 16MB units (2^24).
	 * Round up since the granularity is so high.
	 */
	ip->HostPhysMemPages = ctob(physmem) / AAC_PAGE_SIZE;
	if (sc->flags & AAC_FLAGS_BROKEN_MEMMAP) {
		ip->HostPhysMemPages =
		    (ip->HostPhysMemPages + AAC_PAGE_SIZE) / AAC_PAGE_SIZE;
	}
	ip->HostElapsedSeconds = time_second; /* reset later if invalid */

	/*
	 * Initialise FIB queues.  Note that it appears that the layout of the
	 * indexes and the segmentation of the entries may be 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, and theoretically it could 
	 * work out the entire layout of the queue structures from this.  We
	 * take the easy route and just lay this area out like everyone else
	 * does.
	 *
	 * 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.
	 */
	qoffset = offsetof(struct aac_common, ac_qbuf) + AAC_QUEUE_ALIGN;
	qoffset &= ~(AAC_QUEUE_ALIGN - 1);
	sc->aac_queues =
	    (struct aac_queue_table *)((caddr_t)sc->aac_common + qoffset);
	ip->CommHeaderAddress = sc->aac_common_busaddr + qoffset;

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

	/*
	 * Do controller-type-specific initialisation
	 */
	switch (sc->aac_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->aac_common_busaddr +
			     offsetof(struct aac_common, ac_init), 0, 0, 0,
			     NULL)) {
		printf("%s: error establishing init structure\n",
		    sc->aac_dev.dv_xname);
		error = EIO;
		goto bail_out;
	}

	aac_describe_controller(sc);
	aac_startup(sc);

	return (0);

 bail_out:
	if (state > 3)
		bus_dmamap_unload(sc->aac_dmat, sc->aac_common_map);
	if (state > 2)
		bus_dmamap_destroy(sc->aac_dmat, sc->aac_common_map);
	if (state > 1)
		bus_dmamem_unmap(sc->aac_dmat, (caddr_t)sc->aac_common,
		    sizeof *sc->aac_common);
	if (state > 0)
		bus_dmamem_free(sc->aac_dmat, &seg, 1);

 out:
	return (error);
}

/*
 * Send a synchronous command to the controller and wait for a result.
 */
int
aac_sync_command(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)
{
//	time_t then;
	int i;
	u_int32_t status;
	u_int16_t reason;

	/* 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);

#if 0
	/* spin waiting for the command to complete */
	then = time_second;
	do {
		if (time_second > (then + AAC_IMMEDIATE_TIMEOUT)) {
			AAC_DPRINTF(AAC_D_MISC, ("timed out"));
			return(EIO);
		}
	} while (!(AAC_GET_ISTATUS(sc) & AAC_DB_SYNC_COMMAND));
#else
	DELAY(AAC_SYNC_DELAY);

	/* spin waiting for the command to complete */
	for (i = 0; i < AAC_IMMEDIATE_TIMEOUT * 1000; i++) {
		reason = AAC_GET_ISTATUS(sc);
		if (reason & AAC_DB_SYNC_COMMAND)
			break;
		reason = AAC_GET_ISTATUS(sc);
		if (reason & AAC_DB_SYNC_COMMAND)
			break;
		reason = AAC_GET_ISTATUS(sc);
		if (reason & AAC_DB_SYNC_COMMAND)
			break;
		DELAY(1000);
	}
	if (i == AAC_IMMEDIATE_TIMEOUT * 1000) {
		printf("aac_sync_command: failed, reason=%#x\n", reason);
		return (EIO);
	}
#endif

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

	/* get the command status */
	status = AAC_GET_MAILBOX(sc, 0);

	if (sp != NULL)
		*sp = status;

	return(0);
}

/*
 * Grab the sync fib area.
 */
int
aac_alloc_sync_fib(struct aac_softc *sc, struct aac_fib **fib, int flags)
{

	/*
	 * If the force flag is set, the system is shutting down, or in
	 * trouble.  Ignore the mutex.
	 */
	if (!(flags & AAC_SYNC_LOCK_FORCE))
		AAC_LOCK_ACQUIRE(&sc->aac_sync_lock);

	*fib = &sc->aac_common->ac_sync_fib;

	return (1);
}

/*
 * Release the sync fib area.
 */
void
aac_release_sync_fib(struct aac_softc *sc)
{
	AAC_LOCK_RELEASE(&sc->aac_sync_lock);
}

/*
 * Send a synchronous FIB to the controller and wait for a result.
 */
int
aac_sync_fib(struct aac_softc *sc, u_int32_t command, u_int32_t xferstate, 
	     struct aac_fib *fib, u_int16_t datasize)
{

	if (datasize > AAC_FIB_DATASIZE) {
		printf("aac_sync_fib 1: datasize=%d AAC_FIB_DATASIZE\n",
		    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(struct aac_fib) + datasize;
	fib->Header.SenderSize = sizeof(struct aac_fib);
	fib->Header.SenderFibAddress = 0;	/* Not needed */
	fib->Header.ReceiverFibAddress = sc->aac_common_busaddr +
					 offsetof(struct aac_common,
						  ac_sync_fib);

	/*
	 * 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)) {
		AAC_DPRINTF(AAC_D_IO, ("%s: aac_sync_fib: IO error\n",
				       sc->aac_dev.dv_xname));
		printf("aac_sync_fib 2\n");
		return(EIO);
	}

	return (0);
}

/*****************************************************************************
 * 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.
 *
 * Note: 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 may be difficult
 *	 (it would involve a separate queue/notify interface).
 */
int
aac_enqueue_fib(struct aac_softc *sc, int queue, struct aac_command *cm)
{
	u_int32_t pi, ci;
	int error;
	u_int32_t fib_size;
	u_int32_t fib_addr;

	fib_size = cm->cm_fib->Header.Size;
	fib_addr = cm->cm_fib->Header.ReceiverFibAddress;

	/* get the producer/consumer indices */
	pi = sc->aac_queues->qt_qindex[queue][AAC_PRODUCER_INDEX];
	ci = sc->aac_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->aac_qentries[queue] + pi)->aq_fib_size = fib_size;
	(sc->aac_qentries[queue] + pi)->aq_fib_addr = fib_addr;

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

	/*
	 * To avoid a race with its completion interrupt, place this command on
	 * the busy queue prior to advertising it to the controller.
	 */
	aac_enqueue_busy(cm);

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

	error = 0;

out:
	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;
	u_int32_t fib_index;
	int notify;
	int error;

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

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

	/* wrap the pi so the following test works */
	if (pi >= aac_qinfo[queue].size)
		pi = 0;

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

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

	/* fetch the entry */
	*fib_size = (sc->aac_qentries[queue] + ci)->aq_fib_size;

	switch (queue) {
	case AAC_HOST_NORM_CMD_QUEUE:
	case AAC_HOST_HIGH_CMD_QUEUE:
		/*
		 * The aq_fib_addr is only 32 bits wide so it can't be counted
		 * on to hold an address.  For AIF's, the adapter assumes
		 * that it's giving us an address into the array of AIF fibs.
		 * Therefore, we have to convert it to an index.
		 */
		fib_index = (sc->aac_qentries[queue] + ci)->aq_fib_addr /
			sizeof(struct aac_fib);
		*fib_addr = &sc->aac_common->ac_fibs[fib_index];
		break;

	case AAC_HOST_NORM_RESP_QUEUE:
	case AAC_HOST_HIGH_RESP_QUEUE:
	{
		struct aac_command *cm;

		/*
		 * As above, an index is used instead of an actual address.
		 * Gotta shift the index to account for the fast response
		 * bit.  No other correction is needed since this value was
		 * originally provided by the driver via the SenderFibAddress
		 * field.
		 */
		fib_index = (sc->aac_qentries[queue] + ci)->aq_fib_addr;
		cm = sc->aac_commands + (fib_index >> 1);
		*fib_addr = cm->cm_fib;

		/*
		 * Is this a fast response? If it is, update the fib fields in
		 * local memory since the whole fib isn't DMA'd back up.
		 */
		if (fib_index & 0x01) {
			(*fib_addr)->Header.XferState |= AAC_FIBSTATE_DONEADAP;
			*((u_int32_t*)((*fib_addr)->data)) = AAC_ERROR_NORMAL;
		}
		break;
	}
	default:
		panic("Invalid queue in aac_dequeue_fib()");
		break;
	}


	/* update consumer index */
	sc->aac_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:
	return (error);
}

/*
 * Put our response to an Adapter Initialed Fib on the response queue
 */
int
aac_enqueue_response(struct aac_softc *sc, int queue, struct aac_fib *fib)
{
	u_int32_t pi, ci;
	int error;
	u_int32_t fib_size;
	u_int32_t fib_addr;

	/* Tell the adapter where the FIB is */
	fib_size = fib->Header.Size; 
	fib_addr = fib->Header.SenderFibAddress;
	fib->Header.ReceiverFibAddress = fib_addr;

	/* get the producer/consumer indices */
	pi = sc->aac_queues->qt_qindex[queue][AAC_PRODUCER_INDEX];
	ci = sc->aac_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->aac_qentries[queue] + pi)->aq_fib_size = fib_size;
	(sc->aac_qentries[queue] + pi)->aq_fib_addr = fib_addr;

	/* update producer index */
	sc->aac_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:
	return(error);
}

void
aac_command_timeout(struct aac_command *cm)
{
	struct aac_softc *sc = cm->cm_sc;

	printf("%s: COMMAND %p (flags=%#x) TIMEOUT AFTER %d SECONDS\n",
	       sc->aac_dev.dv_xname, cm, cm->cm_flags,
	       (int)(time_second - cm->cm_timestamp));

	if (cm->cm_flags & AAC_CMD_TIMEDOUT)
		return;

	cm->cm_flags |= AAC_CMD_TIMEDOUT;

	AAC_PRINT_FIB(sc, cm->cm_fib);

	if (cm->cm_flags & AAC_ON_AACQ_BIO) {
		struct scsi_xfer *xs = cm->cm_private;
		int s = splbio();
		xs->error = XS_DRIVER_STUFFUP;
		xs->flags |= ITSDONE;
		scsi_done(xs);
		splx(s);

		aac_remove_bio(cm);
		aac_unmap_command(cm);
	}
}

void
aac_timeout(struct aac_softc *sc)
{
	struct aac_command *cm;
	time_t deadline;

	/*
	 * Traverse the busy command list and timeout any commands
	 * that are past their deadline.
	 */
	deadline = time_second - AAC_CMD_TIMEOUT;
	TAILQ_FOREACH(cm, &sc->aac_busy, cm_link) {
		if (cm->cm_timestamp  < deadline)
			aac_command_timeout(cm);
	}
}

/*
 * Interface Function Vectors
 */

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

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

int
aac_fa_get_fwstatus(struct aac_softc *sc)
{
 	return (AAC_GETREG4(sc, AAC_FA_FWSTATUS));
}

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

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

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

void
aac_fa_qnotify(struct aac_softc *sc, int qbit)
{
	AAC_SETREG2(sc, AAC_FA_DOORBELL1, qbit);
	AAC_FA_HACK(sc);
}

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

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

int
aac_fa_get_istatus(struct aac_softc *sc)
{
	return (AAC_GETREG2(sc, AAC_FA_DOORBELL0));
}

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

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

void
aac_fa_clear_istatus(struct aac_softc *sc, int mask)
{
	AAC_SETREG2(sc, AAC_FA_DOORBELL0_CLEAR, mask);
	AAC_FA_HACK(sc);
}

/*
 * Populate the mailbox and set the command word
 */
void
aac_sa_set_mailbox(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(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);
}

void
aac_fa_set_mailbox(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_FA_MAILBOX, command);
	AAC_FA_HACK(sc);
	AAC_SETREG4(sc, AAC_FA_MAILBOX + 4, arg0);
	AAC_FA_HACK(sc);
	AAC_SETREG4(sc, AAC_FA_MAILBOX + 8, arg1);
	AAC_FA_HACK(sc);
	AAC_SETREG4(sc, AAC_FA_MAILBOX + 12, arg2);
	AAC_FA_HACK(sc);
	AAC_SETREG4(sc, AAC_FA_MAILBOX + 16, arg3);
	AAC_FA_HACK(sc);
}

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

int
aac_rx_get_mailbox(struct aac_softc *sc, int mb)
{
	return (AAC_GETREG4(sc, AAC_RX_MAILBOX + (mb * 4)));
}

int
aac_fa_get_mailbox(struct aac_softc *sc, int mb)
{
	return (AAC_GETREG4(sc, AAC_FA_MAILBOX + (mb * 4)));
}

/*
 * Set/clear interrupt masks
 */
void
aac_sa_set_interrupts(struct aac_softc *sc, int enable)
{
	AAC_DPRINTF(AAC_D_INTR, ("%s: %sable interrupts\n",
				 sc->aac_dev.dv_xname, enable ? "en" : "dis"));

	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(struct aac_softc *sc, int enable)
{
	AAC_DPRINTF(AAC_D_INTR, ("%s: %sable interrupts",
				 sc->aac_dev.dv_xname, enable ? "en" : "dis"));

	if (enable)
		AAC_SETREG4(sc, AAC_RX_OIMR, ~AAC_DB_INTERRUPTS);
	else
		AAC_SETREG4(sc, AAC_RX_OIMR, ~0);
}

void
aac_fa_set_interrupts(struct aac_softc *sc, int enable)
{
	AAC_DPRINTF(AAC_D_INTR, ("%s: %sable interrupts",
				 sc->aac_dev.dv_xname, enable ? "en" : "dis"));

	if (enable) {
		AAC_SETREG2((sc), AAC_FA_MASK0_CLEAR, AAC_DB_INTERRUPTS);
		AAC_FA_HACK(sc);
	} else {
		AAC_SETREG2((sc), AAC_FA_MASK0, ~0);
		AAC_FA_HACK(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;
		}
	}
}

void
aac_copy_internal_data(struct scsi_xfer *xs, u_int8_t *data, size_t size)
{
	struct aac_softc *sc = xs->sc_link->adapter_softc;
	size_t copy_cnt;

	AAC_DPRINTF(AAC_D_MISC, ("%s: aac_copy_internal_data\n",
				 sc->aac_dev.dv_xname));

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

/* Emulated SCSI operation on cache device */
int
aac_internal_cache_cmd(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 scsi_read_cap_data rcd;
	u_int8_t target = link->target;

	AAC_DPRINTF(AAC_D_CMD, ("aac_internal_cache_cmd: ",
				sc->aac_dev.dv_xname));

	switch (xs->cmd->opcode) {
	case TEST_UNIT_READY:
	case START_STOP:
#if 0
	case VERIFY:
#endif
		AAC_DPRINTF(AAC_D_CMD, ("opc %#x 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->aac_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;
		strlcpy(inq.vendor, "Adaptec", sizeof inq.vendor);
		snprintf(inq.product, sizeof inq.product, "Container #%02d",
		    target);
		strlcpy(inq.revision, "   ", sizeof inq.revision);
		aac_copy_internal_data(xs, (u_int8_t *)&inq, sizeof inq);
		break;

	case READ_CAPACITY:
		AAC_DPRINTF(AAC_D_CMD, ("READ CAPACITY tgt %d ", target));
		bzero(&rcd, sizeof rcd);
		_lto4b(sc->aac_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:
		AAC_DPRINTF(AAC_D_CMD, ("\n"));
		printf("aac_internal_cache_cmd got bad opcode: %#x\n",
		    xs->cmd->opcode);
		xs->error = XS_DRIVER_STUFFUP;
		return (0);
	}

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

void
aacminphys(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)\n", bp));

#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

#if 0
	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);
}

int
aac_raw_scsi_cmd(struct scsi_xfer *xs)
{
#ifdef AAC_DEBUG
	struct aac_softc *sc = xs->sc_link->adapter_softc;
#endif
	AAC_DPRINTF(AAC_D_CMD, ("%s: aac_raw_scsi_cmd\n",
				sc->aac_dev.dv_xname));

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

int
aac_scsi_cmd(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_command *cm;
	u_int32_t blockno, blockcnt;
	struct scsi_rw *rw;
	struct scsi_rw_big *rwb;
	int retval = SUCCESSFULLY_QUEUED;
	int s = splbio();

	xs->error = XS_NOERROR;

	if (target >= AAC_MAX_CONTAINERS || !sc->aac_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);
		splx(s);
		return (COMPLETE);
	}

	AAC_DPRINTF(AAC_D_CMD, ("%s: aac_scsi_cmd: ", sc->aac_dev.dv_xname));

	xs->error = XS_NOERROR;
	cm = NULL;
	link = xs->sc_link;
	target = link->target;

	switch (xs->cmd->opcode) {
	case TEST_UNIT_READY:
	case REQUEST_SENSE:
	case INQUIRY:
	case START_STOP:
	case READ_CAPACITY:
#if 0
	case VERIFY:
#endif
		if (!aac_internal_cache_cmd(xs)) {
			splx(s);
			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 %#x ", 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 %#x ", xs->cmd->opcode));
			
		/* 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);
		}

		AAC_DPRINTF(AAC_D_CMD, ("blkno=%d bcount=%d ",
					xs->cmd->opcode, blockno, blockcnt));

		if (blockno >= sc->aac_hdr[target].hd_size ||
		    blockno + blockcnt > sc->aac_hdr[target].hd_size) {
			AAC_DPRINTF(AAC_D_CMD, ("\n"));
			printf("%s: out of bounds %u-%u >= %u\n",
			       sc->aac_dev.dv_xname, blockno,
			       blockcnt, sc->aac_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;
		}

		if (aac_alloc_command(sc, &cm)) {
			AAC_DPRINTF(AAC_D_CMD,
				    (": out of commands, try later\n"));
			/*
			 * We are out of commands, try again
			 * in a little while.
			 */
			splx(s);
			return (TRY_AGAIN_LATER);
		}

		/* fill out the command */
		cm->cm_data = (void *)xs->data;
		cm->cm_datalen = xs->datalen;
		cm->cm_complete = aac_bio_complete;
		cm->cm_private = xs;
		cm->cm_timestamp = time_second;
		cm->cm_queue = AAC_ADAP_NORM_CMD_QUEUE;
		cm->cm_blkno = blockno;
		cm->cm_bcount = blockcnt;

		AAC_DPRINTF(AAC_D_CMD, ("\n"));
		aac_enqueue_bio(cm);
		aac_startio(sc);

		/* XXX what if enqueue did not start a transfer? */
		if (xs->flags & SCSI_POLL) {
			if (!aac_wait_command(cm, xs->timeout))
			{
				printf("%s: command timed out\n",
				       sc->aac_dev.dv_xname);
				splx(s);
				return (TRY_AGAIN_LATER);
			}
			xs->flags |= ITSDONE;
			scsi_done(xs);
		}
	}

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

	splx(s);
	AAC_DPRINTF(AAC_D_CMD, ("%s: scsi_cmd complete\n",
				sc->aac_dev.dv_xname));
	return (retval);
}

/*
 * Debugging and Diagnostics
 */

/*
 * Print some information about the controller.
 */
void
aac_describe_controller(struct aac_softc *sc)
{
	struct aac_fib *fib;
	struct aac_adapter_info	*info;

	aac_alloc_sync_fib(sc, &fib, 0);

	fib->data[0] = 0;
	if (aac_sync_fib(sc, RequestAdapterInfo, 0, fib, 1)) {
		printf("%s: RequestAdapterInfo failed 2\n",
		       sc->aac_dev.dv_xname);
		aac_release_sync_fib(sc);
		return;
	}
	info = (struct aac_adapter_info *)&fib->data[0];   

	printf("%s: %s %dMHz, %dMB cache memory, %s\n", sc->aac_dev.dv_xname,
	       aac_describe_code(aac_cpu_variant, info->CpuVariant),
	       info->ClockSpeed, info->BufferMem / (1024 * 1024), 
	       aac_describe_code(aac_battery_platform, info->batteryPlatform));

	/* save the kernel revision structure for later use */
	sc->aac_revision = info->KernelRevision;
	printf("%s: Kernel %d.%d-%d, Build %d, S/N %6X\n",
	       sc->aac_dev.dv_xname,
	       info->KernelRevision.external.comp.major,
	       info->KernelRevision.external.comp.minor,
	       info->KernelRevision.external.comp.dash,
	       info->KernelRevision.buildNumber,
	       (u_int32_t)(info->SerialNumber & 0xffffff));

	aac_release_sync_fib(sc);

#if 0
	if (1 || bootverbose) {
		device_printf(sc->aac_dev, "Supported Options=%b\n",
			      sc->supported_options,
			      "\20"
			      "\1SNAPSHOT"
			      "\2CLUSTERS"
			      "\3WCACHE"
			      "\4DATA64"
			      "\5HOSTTIME"
			      "\6RAID50"
			      "\7WINDOW4GB"
			      "\10SCSIUPGD"
			      "\11SOFTERR"
			      "\12NORECOND"
			      "\13SGMAP64"
			      "\14ALARM"
			      "\15NONDASD");
	}
#endif
}

/*
 * Look up a text description of a numeric error code and return a pointer to
 * same.
 */
char *
aac_describe_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);
}

#ifdef AAC_DEBUG
/*
 * Print a FIB
 */
void
aac_print_fib(struct aac_softc *sc, struct aac_fib *fib, const 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;
	}
}

/*
 * Describe an AIF we have received.
 */
void
aac_print_aif(struct aac_softc *sc, struct aac_aif_command *aif)
{
	printf("%s: print_aif: ", sc->aac_dev.dv_xname);

	switch(aif->command) {
	case AifCmdEventNotify:
		printf("EventNotify(%d)\n", aif->seqNumber);

		switch(aif->data.EN.type) {
		case AifEnGeneric:
			/* Generic notification */
			printf("\t(Generic) %.*s\n", 
			       (int)sizeof(aif->data.EN.data.EG),
			       aif->data.EN.data.EG.text);
			break;
		case AifEnTaskComplete:
			/* Task has completed */
			printf("\t(TaskComplete)\n");
			break;
		case AifEnConfigChange:
			/* Adapter configuration change occurred */
			printf("\t(ConfigChange)\n");
			break;
		case AifEnContainerChange:
			/* Adapter specific container configuration change */
			printf("\t(ContainerChange) container %d,%d\n", 
			       aif->data.EN.data.ECC.container[0], 
			       aif->data.EN.data.ECC.container[1]);
			break;
		case AifEnDeviceFailure:
			/* SCSI device failed */
			printf("\t(DeviceFailure) handle %d\n", 
			       aif->data.EN.data.EDF.deviceHandle);
			break;
		case AifEnMirrorFailover:
			/* Mirror failover started */
			printf("\t(MirrorFailover) container %d failed, "
			       "migrating from slice %d to %d\n",
			       aif->data.EN.data.EMF.container, 
			       aif->data.EN.data.EMF.failedSlice, 
			       aif->data.EN.data.EMF.creatingSlice);
			break;
		case AifEnContainerEvent:
			/* Significant container event */
			printf("\t(ContainerEvent) container %d event %d\n",
			       aif->data.EN.data.ECE.container,
			       aif->data.EN.data.ECE.eventType);	
			break;
		case AifEnFileSystemChange:
			/* File system changed */
			printf("\t(FileSystemChange)\n");
			break;
		case AifEnConfigPause:
			/* Container pause event */
			printf("\t(ConfigPause)\n");
			break;
		case AifEnConfigResume:
			/* Container resume event */
			printf("\t(ConfigResume)\n");
			break;
		case AifEnFailoverChange:
			/* Failover space assignment changed */
			printf("\t(FailoverChange)\n");
			break;
		case AifEnRAID5RebuildDone:
			/* RAID5 rebuild finished */
			printf("\t(RAID5RebuildDone)\n");
			break;
		case AifEnEnclosureManagement:
			/* Enclosure management event */
			printf("\t(EnclosureManagement) EMPID %d unit %d "
			       "event %d\n",
			       aif->data.EN.data.EEE.empID,
			       aif->data.EN.data.EEE.unitID, 
			       aif->data.EN.data.EEE.eventType);
			break;
		case AifEnBatteryEvent:
			/* Significant NV battery event */
			printf("\t(BatteryEvent) %d (state was %d, is %d\n",
			       aif->data.EN.data.EBE.transition_type,
			       aif->data.EN.data.EBE.current_state,
			       aif->data.EN.data.EBE.prior_state);
			break;
		case AifEnAddContainer:
			/* A new container was created. */
			printf("\t(AddContainer)\n");
			break;		
		case AifEnDeleteContainer:
			/* A container was deleted. */
			printf("\t(DeleteContainer)\n");
			break;
		case AifEnBatteryNeedsRecond:
			/* The battery needs reconditioning */
			printf("\t(BatteryNeedsRecond)\n");
			break;
		case AifEnClusterEvent:
			/* Some cluster event */
			printf("\t(ClusterEvent) event %d\n", 
			       aif->data.EN.data.ECLE.eventType);
			break;
		case AifEnDiskSetEvent:
			/* A disk set event occured. */
			printf("(DiskSetEvent) event %d "
			       "diskset %lld creator %lld\n",
			       aif->data.EN.data.EDS.eventType, 
			       aif->data.EN.data.EDS.DsNum, 
			       aif->data.EN.data.EDS.CreatorId);
			break;
		case AifDenMorphComplete:
			/* A morph operation completed */
			printf("\t(MorphComplete)\n");
			break;
		case AifDenVolumeExtendComplete:
			/* A volume expand operation completed */
			printf("\t(VolumeExtendComplete)\n");
			break;
		default:
			printf("\t(%d)\n", aif->data.EN.type);
			break;
		}
		break;
	case AifCmdJobProgress:
	{
		char	*status;
		switch(aif->data.PR[0].status) {
		case AifJobStsSuccess:
			status = "success"; break;
		case AifJobStsFinished:
			status = "finished"; break;
		case AifJobStsAborted:
			status = "aborted"; break;
		case AifJobStsFailed:
			status = "failed"; break;
		case AifJobStsSuspended:
			status = "suspended"; break;
		case AifJobStsRunning:
			status = "running"; break;
		default:
			status = "unknown status"; break;
		}		
	
		printf("JobProgress (%d) - %s (%d, %d)\n",
		       aif->seqNumber, status, 
		       aif->data.PR[0].currentTick,
		       aif->data.PR[0].finalTick);

		switch(aif->data.PR[0].jd.type) {
		case AifJobScsiZero:
			/* SCSI dev clear operation */
			printf("\t(ScsiZero) handle %d\n",
				      aif->data.PR[0].jd.client.scsi_dh);
			break;
		case AifJobScsiVerify:
			/* SCSI device Verify operation NO REPAIR */
			printf("\t(ScsiVerify) handle %d\n",
				      aif->data.PR[0].jd.client.scsi_dh);
			break;
		case AifJobScsiExercise:
			/* SCSI device Exercise operation */
			printf("\t(ScsiExercise) handle %d\n",
			       aif->data.PR[0].jd.client.scsi_dh);
			break;
		case AifJobScsiVerifyRepair:
			/* SCSI device Verify operation WITH repair */
			printf("\t(ScsiVerifyRepair) handle %d\n",
			       aif->data.PR[0].jd.client.scsi_dh);
			break;
		case AifJobCtrZero:
			/* Container clear operation */
			printf("\t(ConatainerZero) container %d\n", 
			       aif->data.PR[0].jd.client.container.src);
			break;
		case AifJobCtrCopy:
			/* Container copy operation */
			printf("\t(ConatainerCopy) container %d to %d\n", 
			       aif->data.PR[0].jd.client.container.src,
			       aif->data.PR[0].jd.client.container.dst);
			break;
		case AifJobCtrCreateMirror:
			/* Container Create Mirror operation */
			printf("\t(ConatainerCreateMirror) container %d\n",
			       aif->data.PR[0].jd.client.container.src);
			/* XXX two containers? */
			break;
		case AifJobCtrMergeMirror:
			/* Container Merge Mirror operation */
			printf("\t(ConatainerMergeMirror) container %d\n",
			       aif->data.PR[0].jd.client.container.src);
			/* XXX two containers? */
			break;
		case AifJobCtrScrubMirror:
			/* Container Scrub Mirror operation */
			printf("\t(ConatainerScrubMirror) container %d\n",
			       aif->data.PR[0].jd.client.container.src);
			break;
		case AifJobCtrRebuildRaid5:
			/* Container Rebuild Raid5 operation */
			printf("\t(ConatainerRebuildRaid5) container %d\n",
			       aif->data.PR[0].jd.client.container.src);
			break;
		case AifJobCtrScrubRaid5:
			/* Container Scrub Raid5 operation */
			printf("\t(ConatainerScrubRaid5) container %d\n", 
			       aif->data.PR[0].jd.client.container.src);
			break;
		case AifJobCtrMorph:
			/* Container morph operation */
			printf("\t(ConatainerMorph) container %d\n",
			       aif->data.PR[0].jd.client.container.src);
			/* XXX two containers? */
			break;
		case AifJobCtrPartCopy:
			/* Container Partition copy operation */
			printf("\t(ConatainerPartCopy) container %d to %d\n",
			       aif->data.PR[0].jd.client.container.src,
			       aif->data.PR[0].jd.client.container.dst);
			break;
		case AifJobCtrRebuildMirror:
			/* Container Rebuild Mirror operation */
			printf("\t(ConatainerRebuildMirror) container %d\n",
			       aif->data.PR[0].jd.client.container.src);
			break;
		case AifJobCtrCrazyCache:
			/* crazy cache */
			printf("\t(ConatainerCrazyCache) container %d\n", 
			       aif->data.PR[0].jd.client.container.src);
			/* XXX two containers? */
			break;
		case AifJobFsCreate:
			/* File System Create operation */
			printf("\t(FsCreate)\n");
			break;
		case AifJobFsVerify:
			/* File System Verify operation */
			printf("\t(FsVerivy)\n");
			break;
		case AifJobFsExtend:
			/* File System Extend operation */
			printf("\t(FsExtend)\n");
			break;
		case AifJobApiFormatNTFS:
			/* Format a drive to NTFS */
			printf("\t(FormatNTFS)\n");
			break;
		case AifJobApiFormatFAT:
			/* Format a drive to FAT */
			printf("\t(FormatFAT)\n");
			break;
		case AifJobApiUpdateSnapshot:
			/* update the read/write half of a snapshot */
			printf("\t(UpdateSnapshot)\n");
			break;
		case AifJobApiFormatFAT32:
			/* Format a drive to FAT32 */
			printf("\t(FormatFAT32)\n");
			break;
		case AifJobCtlContinuousCtrVerify:
			/* Adapter operation */
			printf("\t(ContinuousCtrVerify)\n");
			break;
		default:
			printf("\t(%d)\n", aif->data.PR[0].jd.type);
			break;
		}
		break;
	}
	case AifCmdAPIReport:
		printf("APIReport (%d)\n", aif->seqNumber);
		break;
	case AifCmdDriverNotify:
		printf("DriverNotify (%d)\n", aif->seqNumber);
		break;
	default:
		printf("AIF %d (%d)\n", aif->command, aif->seqNumber);
		break;
	}
}
#endif