summaryrefslogtreecommitdiff
path: root/usr/src/uts/common/io/scsi/adapters/smrt/smrt_ciss.c
blob: 8da9ac903820eaa2ee769b7d479e0ad30d8bfe72 (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
/*
 * This file and its contents are supplied under the terms of the
 * Common Development and Distribution License ("CDDL"), version 1.0.
 * You may only use this file in accordance with the terms of version
 * 1.0 of the CDDL.
 *
 * A full copy of the text of the CDDL should have accompanied this
 * source.  A copy of the CDDL is also available via the Internet at
 * http://www.illumos.org/license/CDDL.
 */

/*
 * Copyright (c) 2017, Joyent, Inc.
 */

#include <sys/scsi/adapters/smrt/smrt.h>

/*
 * Discovery, Resets, Periodics, and Events
 * ----------------------------------------
 *
 * Discovery is the act of figuring out what logical and physical volumes exist
 * under the controller.  Discovery happens in response to the following events:
 *
 *   o iports for virtual and physical devices being attached
 *   o Controller event notifications indicating potential topology changes
 *   o After a reset of the controller, before we can perform I/O again
 *
 * Because we have to perform discovery after a reset, which can happen during
 * panic(), that also means that discovery may be run in panic context.  We
 * also need to emphasize the need for discovery to happen after a controller
 * reset.  Once a reset is initiated, we cannot be certain about the addresses
 * of any of the existing targets until the reset has completed.  The driver
 * performs I/Os to addresses that the controller provides.  The controller
 * specification says that these addresses may change after a controller reset.
 *
 * Unfortunately, all of this combined means that making sure we can correctly
 * run discovery is somewhat complicated.  In non-panic contexts, discovery is
 * always run from a taskq.  We'll kick off the discovery in the taskq if
 * nothing is pending at that time.  The state is managed by bits in the
 * smrt_status member of the smrt_t.  There are four bits at this time:
 *
 *	SMRT_CTLR_DISCOVERY_REQUESTED	This flag indicates that something has
 *					requested that a discovery be performed.
 *					If no flags are set when this is set,
 *					then we will kick off discovery.  All
 *					discovery requests are initiated via the
 *					smrt_discover_request() function.
 *
 *	SMRT_CTLR_DISCOVERY_RUNNING	This flag is set at the start of us
 *					running a discovery.  It is removed when
 *					discovery finishes.
 *
 *	SMRT_CTLR_DISCOVERY_PERIODIC	This flag is set in a number of
 *					circumstances, which will be described
 *					in a subsequent section.  This indicates
 *					that the periodic must kick off the
 *					discovery process.
 *
 *	SMRT_CTLR_DISCOVERY_REQUIRED	This flag indicates that at some point a
 *					controller reset occurred and we need to
 *					have a successful discovery to finish
 *					the act of resetting and allowing I/O to
 *					continue.
 *
 * In general, a request to discover kicks off the taskq to discover entries, if
 * it hasn't already been requested or started.  This also allows us to coalesce
 * multiple requests, if needed.  Note that if a request comes in when a
 * discovery is ongoing, we do not kick off discovery again.  Instead, we set
 * the SMRT_CTLR_DISCOVERY_REQUESTED flag which will rerun discovery after the
 * initial pass has completed.
 *
 * When a discovery starts, the first thing it does is clear the
 * SMRT_CTLR_DISCOVERY_REQUESTED flag.  This is important, because any
 * additional requests for discovery that come in after this has started likely
 * indicate that we've missed something.  As such, when the discovery process
 * finishes, if it sees the REQUESTED flag, then it will need to set the
 * PERIODIC flag.  The PERIODIC flag is used to indicate that we should run
 * discovery again, but not kick if off immediately.  Instead, it should be
 * driven by the normal periodic behavior.
 *
 * If for some reason the act of discovery fails, or we fail to dispatch
 * discovery due to a transient error, then we will flag PERIODIC so that the
 * periodic tick will try and run things again.
 *
 * Now, we need to talk about SMRT_CTLR_DISCOVERY_REQUIRED.  This flag is set
 * after a reset occurs.  The reset thread will be blocked on this.
 * Importantly, none of the code in the discovery path can ask for a controller
 * reset at this time.  If at the end of a discovery, this flag is set, then we
 * will signal the reset thread that it should check on its status by
 * broadcasting on the smrt_cv_finishq.  At that point, the reset thread will
 * continue.
 *
 * Panic Context
 * -------------
 *
 * All of this talk of threads and taskqs is well and good, but as an HBA
 * driver, we have a serious responsibility to try and deal with panic sanely.
 * In panic context, we will directly call the discovery functions and not poll
 * for them to occur.
 *
 * However, because our discovery relies on the target maps, which aren't safe
 * for panic context at this time, we have to take a different approach.  We
 * leverage the fact that we have a generation number stored with every
 * discovery.  If we try to do an I/O to a device where the generation doesn't
 * match, then we know that it disappeared and should not be used.  We also
 * sanity check the model, serial numbers, and WWNs to make sure that these are
 * the same devices.  If they are, then we'll end up updating the address
 * structures.
 *
 * Now, it is possible that when we were panicking, we had a thread that was in
 * the process of running a discovery or even resetting the system.  Once we're
 * in panic, those threads aren't running, so if they didn't end up producing a
 * new view of the world that the SCSI framework is using, then it shouldn't
 * really matter, as we won't have updated the list of devices.  Importantly,
 * once we're in that context, we're not going to be attaching or detaching
 * targets.  If we get a request for one of these targets which has disappeared,
 * we're going to have to end up giving up.
 *
 * Request Attributes
 * ------------------
 *
 * The CISS specification allows for three different kinds of attributes that
 * describe how requests are queued to the controller.  These are:
 *
 *	HEAD OF QUEUE		The request should go to the head of the
 *				controller queue.  This is used for resets and
 *				aborts to ensure that they're not blocked behind
 *				additional I/O.
 *
 *	SIMPLE			This queues the request for normal processing.
 *				Commands queued this way are not special with
 *				respect to one another.  We use this for all I/O
 *				and discovery commands.
 *
 *	ORDERED			This attribute is used to indicate that commands
 *				should be submitted and processed in some order.
 *				This is used primarily for the event
 *				notification bits so we can ensure that at the
 *				return of a cancellation of the event
 *				notification, that any outstanding request has
 *				been honored.
 */

static int smrt_ctlr_versions(smrt_t *, uint16_t, smrt_versions_t *);
static void smrt_discover(void *);

/*
 * The maximum number of seconds to wait for the controller to come online.
 */
unsigned smrt_ciss_init_time = 90;

/*
 * A tunable that determines the number of events per tick that we'll process
 * via asynchronous event notification.  If this rate is very high, then we will
 * not submit the event and it will be picked up at the next tick of the
 * periodic.
 */
uint_t smrt_event_intervention_threshold = 1000;

/*
 * Converts a LUN Address to a BMIC Identifier.  The BMIC Identifier is used
 * when performing various physical commands and generally should stay the same
 * for a given device across inserts and removals; however, not across
 * controller resets.  These are calculated based on what the CISS specification
 * calls the 'Level 2' target and bus, which don't have a real meaning in the
 * SAS world otherwise.
 */
uint16_t
smrt_lun_addr_to_bmic(PhysDevAddr_t *paddr)
{
	uint16_t id;

	id = (paddr->Target[1].PeripDev.Bus - 1) << 8;
	id += paddr->Target[1].PeripDev.Dev;

	return (id);
}

void
smrt_write_lun_addr_phys(LUNAddr_t *lun, boolean_t masked, unsigned bus,
    unsigned target)
{
	lun->PhysDev.Mode = masked ? MASK_PERIPHERIAL_DEV_ADDR :
	    PERIPHERIAL_DEV_ADDR;

	lun->PhysDev.TargetId = target;
	lun->PhysDev.Bus = bus;

	bzero(&lun->PhysDev.Target, sizeof (lun->PhysDev.Target));
}

/*
 * According to the CISS Specification, the controller is always addressed in
 * Mask Perhiperhal mode with a bus and target ID of zero.  This is used by
 * commands that need to write to the controller itself, which is generally
 * discovery and other commands.
 */
void
smrt_write_controller_lun_addr(LUNAddr_t *lun)
{
	smrt_write_lun_addr_phys(lun, B_TRUE, 0, 0);
}

void
smrt_write_message_common(smrt_command_t *smcm, uint8_t type, int timeout_secs)
{
	switch (type) {
	case CISS_MSG_ABORT:
	case CISS_MSG_RESET:
	case CISS_MSG_NOP:
		break;

	default:
		panic("unknown message type");
	}

	smcm->smcm_va_cmd->Request.Type.Type = CISS_TYPE_MSG;
	smcm->smcm_va_cmd->Request.Type.Attribute = CISS_ATTR_HEADOFQUEUE;
	smcm->smcm_va_cmd->Request.Type.Direction = CISS_XFER_NONE;
	smcm->smcm_va_cmd->Request.Timeout = LE_16(timeout_secs);
	smcm->smcm_va_cmd->Request.CDBLen = CISS_CDBLEN;
	smcm->smcm_va_cmd->Request.CDB[0] = type;
}

void
smrt_write_message_abort_one(smrt_command_t *smcm, uint32_t tag)
{
	smrt_tag_t cisstag;

	/*
	 * When aborting a particular command, the request is addressed
	 * to the controller.
	 */
	smrt_write_lun_addr_phys(&smcm->smcm_va_cmd->Header.LUN,
	    B_TRUE, 0, 0);

	smrt_write_message_common(smcm, CISS_MSG_ABORT, 0);

	/*
	 * Abort a single command.
	 */
	smcm->smcm_va_cmd->Request.CDB[1] = CISS_ABORT_TASK;

	/*
	 * The CISS Specification says that the tag value for a task-level
	 * abort should be in the CDB in bytes 4-11.
	 */
	bzero(&cisstag, sizeof (cisstag));
	cisstag.tag_value = tag;
	bcopy(&cisstag, &smcm->smcm_va_cmd->Request.CDB[4],
	    sizeof (cisstag));
}

void
smrt_write_message_abort_all(smrt_command_t *smcm, LUNAddr_t *addr)
{
	/*
	 * When aborting all tasks for a particular Logical Volume,
	 * the command is addressed not to the controller but to
	 * the Volume itself.
	 */
	smcm->smcm_va_cmd->Header.LUN = *addr;

	smrt_write_message_common(smcm, CISS_MSG_ABORT, 0);

	/*
	 * Abort all commands for a particular Logical Volume.
	 */
	smcm->smcm_va_cmd->Request.CDB[1] = CISS_ABORT_TASKSET;
}

void
smrt_write_message_event_notify(smrt_command_t *smcm)
{
	smrt_event_notify_req_t senr;

	smrt_write_controller_lun_addr(&smcm->smcm_va_cmd->Header.LUN);

	smcm->smcm_va_cmd->Request.Type.Type = CISS_TYPE_CMD;
	smcm->smcm_va_cmd->Request.Type.Attribute = CISS_ATTR_ORDERED;
	smcm->smcm_va_cmd->Request.Type.Direction = CISS_XFER_READ;
	smcm->smcm_va_cmd->Request.Timeout = 0;
	smcm->smcm_va_cmd->Request.CDBLen = sizeof (senr);

	bzero(&senr, sizeof (senr));
	senr.senr_opcode = CISS_SCMD_READ;
	senr.senr_subcode = CISS_BMIC_NOTIFY_ON_EVENT;
	senr.senr_flags = BE_32(0);
	senr.senr_size = BE_32(SMRT_EVENT_NOTIFY_BUFLEN);

	bcopy(&senr, &smcm->smcm_va_cmd->Request.CDB[0],
	    MIN(CISS_CDBLEN, sizeof (senr)));
}

void
smrt_write_message_cancel_event_notify(smrt_command_t *smcm)
{
	smrt_event_notify_req_t senr;

	smrt_write_controller_lun_addr(&smcm->smcm_va_cmd->Header.LUN);

	smcm->smcm_va_cmd->Request.Type.Type = CISS_TYPE_CMD;
	smcm->smcm_va_cmd->Request.Type.Attribute = CISS_ATTR_ORDERED;
	smcm->smcm_va_cmd->Request.Type.Direction = CISS_XFER_WRITE;
	smcm->smcm_va_cmd->Request.Timeout = LE_16(SMRT_ASYNC_CANCEL_TIMEOUT);
	smcm->smcm_va_cmd->Request.CDBLen = sizeof (senr);

	bzero(&senr, sizeof (senr));
	senr.senr_opcode = CISS_SCMD_WRITE;
	senr.senr_subcode = CISS_BMIC_NOTIFY_ON_EVENT_CANCEL;
	senr.senr_size = BE_32(SMRT_EVENT_NOTIFY_BUFLEN);

	bcopy(&senr, &smcm->smcm_va_cmd->Request.CDB[0],
	    MIN(CISS_CDBLEN, sizeof (senr)));
}

void
smrt_write_message_reset_ctlr(smrt_command_t *smcm)
{
	smrt_write_lun_addr_phys(&smcm->smcm_va_cmd->Header.LUN,
	    B_TRUE, 0, 0);

	smrt_write_message_common(smcm, CISS_MSG_RESET, 0);

	smcm->smcm_va_cmd->Request.CDB[1] = CISS_RESET_CTLR;
}

void
smrt_write_message_nop(smrt_command_t *smcm, int timeout_secs)
{
	/*
	 * No-op messages are always sent to the controller.
	 */
	smrt_write_lun_addr_phys(&smcm->smcm_va_cmd->Header.LUN,
	    B_TRUE, 0, 0);

	smrt_write_message_common(smcm, CISS_MSG_NOP, timeout_secs);
}

/*
 * This routine is executed regularly by ddi_periodic_add(9F).  It checks the
 * health of the controller and looks for submitted commands that have timed
 * out.
 */
void
smrt_periodic(void *arg)
{
	smrt_t *smrt = arg;

	mutex_enter(&smrt->smrt_mutex);

	/*
	 * Before we even check if the controller is running to process
	 * everything else, we must first check if we had a request to kick off
	 * discovery.  We do this before the check if the controller is running,
	 * as this may be required to finish a discovery.
	 */
	if ((smrt->smrt_status & SMRT_CTLR_DISCOVERY_PERIODIC) != 0 &&
	    (smrt->smrt_status & SMRT_CTLR_DISCOVERY_RUNNING) == 0 &&
	    (smrt->smrt_status & SMRT_CTLR_STATUS_RESETTING) == 0) {
		if (ddi_taskq_dispatch(smrt->smrt_discover_taskq,
		    smrt_discover, smrt, DDI_NOSLEEP) != DDI_SUCCESS) {
			smrt->smrt_stats.smrts_discovery_tq_errors++;
		} else {
			smrt->smrt_status &= ~SMRT_CTLR_DISCOVERY_PERIODIC;
		}
	}

	if (!(smrt->smrt_status & SMRT_CTLR_STATUS_RUNNING)) {
		/*
		 * The device is currently not active, e.g. due to an
		 * in-progress controller reset.
		 */
		mutex_exit(&smrt->smrt_mutex);
		return;
	}

	/*
	 * Check on the health of the controller firmware.  Note that if the
	 * controller has locked up, this routine will panic the system.
	 */
	smrt_lockup_check(smrt);

	/*
	 * Reset the event notification threshold counter.
	 */
	smrt->smrt_event_count = 0;

	/*
	 * Check inflight commands to see if they have timed out.
	 */
	for (smrt_command_t *smcm = avl_first(&smrt->smrt_inflight);
	    smcm != NULL; smcm = AVL_NEXT(&smrt->smrt_inflight, smcm)) {
		if (smcm->smcm_status & SMRT_CMD_STATUS_POLLED) {
			/*
			 * Polled commands are timed out by the polling
			 * routine.
			 */
			continue;
		}

		if (smcm->smcm_status & SMRT_CMD_STATUS_ABORT_SENT) {
			/*
			 * This command has been aborted; either it will
			 * complete or the controller will be reset.
			 */
			continue;
		}

		if (list_link_active(&smcm->smcm_link_abort)) {
			/*
			 * Already on the abort queue.
			 */
			continue;
		}

		if (smcm->smcm_expiry == 0) {
			/*
			 * This command has no expiry time.
			 */
			continue;
		}

		if (gethrtime() > smcm->smcm_expiry) {
			list_insert_tail(&smrt->smrt_abortq, smcm);
			smcm->smcm_status |= SMRT_CMD_STATUS_TIMEOUT;
		}
	}

	/*
	 * Process the abort queue.
	 */
	(void) smrt_process_abortq(smrt);

	/*
	 * Check if we have an outstanding event intervention request.  Note,
	 * the command in question should always be in a state such that it is
	 * usable by the system here.  The command is always prepared again by
	 * the normal event notification path, even if a reset has occurred.
	 * The reset will be processed before we'd ever consider running an
	 * event again.  Note, if we fail to submit this, then we leave this for
	 * the next occurrence of the periodic.
	 */
	if (smrt->smrt_status & SMRT_CTLR_ASYNC_INTERVENTION) {
		smrt->smrt_stats.smrts_events_intervened++;

		if (smrt_submit(smrt, smrt->smrt_event_cmd) == 0) {
			smrt->smrt_status &= ~SMRT_CTLR_ASYNC_INTERVENTION;
		}
	}

	mutex_exit(&smrt->smrt_mutex);
}

int
smrt_retrieve(smrt_t *smrt)
{
	VERIFY(MUTEX_HELD(&smrt->smrt_mutex));

	switch (smrt->smrt_ctlr_mode) {
	case SMRT_CTLR_MODE_SIMPLE:
		smrt_retrieve_simple(smrt);
		return (DDI_SUCCESS);

	case SMRT_CTLR_MODE_UNKNOWN:
		break;
	}

	panic("unknown controller mode");
	/* LINTED: E_FUNC_NO_RET_VAL */
}

/*
 * Grab a new tag number for this command.  We aim to avoid reusing tag numbers
 * as much as possible, so as to avoid spurious double completion from the
 * controller.
 */
static void
smrt_set_new_tag(smrt_t *smrt, smrt_command_t *smcm)
{
	VERIFY(MUTEX_HELD(&smrt->smrt_mutex));

	/*
	 * Loop until we find a tag that is not in use.  The tag space is
	 * very large (~30 bits) and the maximum number of inflight commands
	 * is comparatively small (~1024 in current controllers).
	 */
	for (;;) {
		uint32_t new_tag = smrt->smrt_next_tag;

		if (++smrt->smrt_next_tag > SMRT_MAX_TAG_NUMBER) {
			smrt->smrt_next_tag = SMRT_MIN_TAG_NUMBER;
		}

		if (smrt_lookup_inflight(smrt, new_tag) != NULL) {
			/*
			 * This tag is already used on an inflight command.
			 * Choose another.
			 */
			continue;
		}

		/*
		 * Set the tag for the command and also write it into the
		 * appropriate part of the request block.
		 */
		smcm->smcm_tag = new_tag;
		smcm->smcm_va_cmd->Header.Tag.tag_value = new_tag;
		return;
	}
}

/*
 * Submit a command to the controller.
 */
int
smrt_submit(smrt_t *smrt, smrt_command_t *smcm)
{
	VERIFY(MUTEX_HELD(&smrt->smrt_mutex));
	VERIFY(smcm->smcm_type != SMRT_CMDTYPE_PREINIT);

	/*
	 * Anything that asks us to ignore the running state of the controller
	 * must be wired up to poll for completion.
	 */
	if (smcm->smcm_status & SMRT_CMD_IGNORE_RUNNING) {
		VERIFY(smcm->smcm_status & SMRT_CMD_STATUS_POLLED);
	}

	/*
	 * If the controller is currently being reset, do not allow command
	 * submission.  However, if this is one of the commands needed to finish
	 * reset, as indicated on the command structure, allow it.
	 */
	if (!(smrt->smrt_status & SMRT_CTLR_STATUS_RUNNING) &&
	    !(smcm->smcm_status & SMRT_CMD_IGNORE_RUNNING)) {
		return (EIO);
	}

	/*
	 * Do not allow submission of more concurrent commands than the
	 * controller supports.
	 */
	if (avl_numnodes(&smrt->smrt_inflight) >= smrt->smrt_maxcmds) {
		return (EAGAIN);
	}

	/*
	 * Synchronise the Command Block DMA resources to ensure that the
	 * device has a consistent view before we pass it the command.
	 */
	if (ddi_dma_sync(smcm->smcm_contig.smdma_dma_handle, 0, 0,
	    DDI_DMA_SYNC_FORDEV) != DDI_SUCCESS) {
		dev_err(smrt->smrt_dip, CE_PANIC, "DMA sync failure");
		return (EIO);
	}

	/*
	 * Ensure that this command is not re-used without issuing a new
	 * tag number and performing any appropriate cleanup.
	 */
	VERIFY(!(smcm->smcm_status & SMRT_CMD_STATUS_USED));
	smcm->smcm_status |= SMRT_CMD_STATUS_USED;

	/*
	 * Assign a tag that is not currently in use
	 */
	smrt_set_new_tag(smrt, smcm);

	/*
	 * Insert this command into the inflight AVL.
	 */
	avl_index_t where;
	if (avl_find(&smrt->smrt_inflight, smcm, &where) != NULL) {
		dev_err(smrt->smrt_dip, CE_PANIC, "duplicate submit tag %x",
		    smcm->smcm_tag);
	}
	avl_insert(&smrt->smrt_inflight, smcm, where);
	if (smrt->smrt_stats.smrts_max_inflight <
	    avl_numnodes(&smrt->smrt_inflight)) {
		smrt->smrt_stats.smrts_max_inflight =
		    avl_numnodes(&smrt->smrt_inflight);
	}

	VERIFY(!(smcm->smcm_status & SMRT_CMD_STATUS_INFLIGHT));
	smcm->smcm_status |= SMRT_CMD_STATUS_INFLIGHT;

	smcm->smcm_time_submit = gethrtime();

	switch (smrt->smrt_ctlr_mode) {
	case SMRT_CTLR_MODE_SIMPLE:
		smrt_submit_simple(smrt, smcm);
		return (0);

	case SMRT_CTLR_MODE_UNKNOWN:
		break;
	}
	panic("unknown controller mode");
	/* LINTED: E_FUNC_NO_RET_VAL */
}

static void
smrt_process_finishq_sync(smrt_command_t *smcm)
{
	smrt_t *smrt = smcm->smcm_ctlr;

	if (ddi_dma_sync(smcm->smcm_contig.smdma_dma_handle, 0, 0,
	    DDI_DMA_SYNC_FORCPU) != DDI_SUCCESS) {
		dev_err(smrt->smrt_dip, CE_PANIC, "finishq DMA sync failure");
	}
}

static void
smrt_process_finishq_one(smrt_command_t *smcm)
{
	smrt_t *smrt = smcm->smcm_ctlr;

	VERIFY(!(smcm->smcm_status & SMRT_CMD_STATUS_COMPLETE));
	smcm->smcm_status |= SMRT_CMD_STATUS_COMPLETE;

	switch (smcm->smcm_type) {
	case SMRT_CMDTYPE_INTERNAL:
		cv_broadcast(&smcm->smcm_ctlr->smrt_cv_finishq);
		return;

	case SMRT_CMDTYPE_SCSA:
		smrt_hba_complete(smcm);
		return;

	case SMRT_CMDTYPE_EVENT:
		smrt_event_complete(smcm);
		return;

	case SMRT_CMDTYPE_ABORTQ:
		/*
		 * Abort messages sent as part of abort queue processing
		 * do not require any completion activity.
		 */
		mutex_exit(&smrt->smrt_mutex);
		smrt_command_free(smcm);
		mutex_enter(&smrt->smrt_mutex);
		return;

	case SMRT_CMDTYPE_PREINIT:
		dev_err(smrt->smrt_dip, CE_PANIC, "preinit command "
		    "completed after initialisation");
		return;
	}

	panic("unknown command type");
}

/*
 * Process commands in the completion queue.
 */
void
smrt_process_finishq(smrt_t *smrt)
{
	smrt_command_t *smcm;

	VERIFY(MUTEX_HELD(&smrt->smrt_mutex));

	while ((smcm = list_remove_head(&smrt->smrt_finishq)) != NULL) {
		/*
		 * Synchronise the Command Block before we read from it or
		 * free it, to ensure that any writes from the controller are
		 * visible.
		 */
		smrt_process_finishq_sync(smcm);

		/*
		 * Check if this command was in line to be aborted.
		 */
		if (list_link_active(&smcm->smcm_link_abort)) {
			/*
			 * This command was in line, but the controller
			 * subsequently completed the command before we
			 * were able to do so.
			 */
			list_remove(&smrt->smrt_abortq, smcm);
			smcm->smcm_status &= ~SMRT_CMD_STATUS_TIMEOUT;
		}

		/*
		 * Check if this command has been abandoned by the original
		 * submitter.  If it has, free it now to avoid a leak.
		 */
		if (smcm->smcm_status & SMRT_CMD_STATUS_ABANDONED) {
			mutex_exit(&smrt->smrt_mutex);
			smrt_command_free(smcm);
			mutex_enter(&smrt->smrt_mutex);
			continue;
		}

		if (smcm->smcm_status & SMRT_CMD_STATUS_POLLED) {
			/*
			 * This command will be picked up and processed
			 * by "smrt_poll_for()" once the CV is triggered
			 * at the end of processing.
			 */
			smcm->smcm_status |= SMRT_CMD_STATUS_POLL_COMPLETE;
			continue;
		}

		smrt_process_finishq_one(smcm);
	}

	cv_broadcast(&smrt->smrt_cv_finishq);
}

/*
 * Process commands in the abort queue.
 */
void
smrt_process_abortq(smrt_t *smrt)
{
	smrt_command_t *smcm;
	smrt_command_t *abort_smcm = NULL;

	VERIFY(MUTEX_HELD(&smrt->smrt_mutex));

	if (list_is_empty(&smrt->smrt_abortq)) {
		goto out;
	}

another:
	mutex_exit(&smrt->smrt_mutex);
	if ((abort_smcm = smrt_command_alloc(smrt, SMRT_CMDTYPE_ABORTQ,
	    KM_NOSLEEP)) == NULL) {
		/*
		 * No resources available to send abort messages.  We will
		 * try again the next time around.
		 */
		mutex_enter(&smrt->smrt_mutex);
		goto out;
	}
	mutex_enter(&smrt->smrt_mutex);

	while ((smcm = list_remove_head(&smrt->smrt_abortq)) != NULL) {
		if (!(smcm->smcm_status & SMRT_CMD_STATUS_INFLIGHT)) {
			/*
			 * This message is not currently inflight, so
			 * no abort is needed.
			 */
			continue;
		}

		if (smcm->smcm_status & SMRT_CMD_STATUS_ABORT_SENT) {
			/*
			 * An abort message has already been sent for
			 * this command.
			 */
			continue;
		}

		/*
		 * Send an abort message for the command.
		 */
		smrt_write_message_abort_one(abort_smcm, smcm->smcm_tag);
		if (smrt_submit(smrt, abort_smcm) != 0) {
			/*
			 * The command could not be submitted to the
			 * controller.  Put it back in the abort queue
			 * and give up for now.
			 */
			list_insert_head(&smrt->smrt_abortq, smcm);
			goto out;
		}
		smcm->smcm_status |= SMRT_CMD_STATUS_ABORT_SENT;

		/*
		 * Record some debugging information about the abort we
		 * sent:
		 */
		smcm->smcm_abort_time = gethrtime();
		smcm->smcm_abort_tag = abort_smcm->smcm_tag;

		/*
		 * The abort message was sent.  Release it and
		 * allocate another command.
		 */
		abort_smcm = NULL;
		goto another;
	}

out:
	cv_broadcast(&smrt->smrt_cv_finishq);
	if (abort_smcm != NULL) {
		mutex_exit(&smrt->smrt_mutex);
		smrt_command_free(abort_smcm);
		mutex_enter(&smrt->smrt_mutex);
	}
}

int
smrt_poll_for(smrt_t *smrt, smrt_command_t *smcm)
{
	VERIFY(MUTEX_HELD(&smrt->smrt_mutex));
	VERIFY(smcm->smcm_status & SMRT_CMD_STATUS_POLLED);

	while (!(smcm->smcm_status & SMRT_CMD_STATUS_POLL_COMPLETE)) {
		if (smcm->smcm_expiry != 0) {
			/*
			 * This command has an expiry time.  Check to see
			 * if it has already passed:
			 */
			if (smcm->smcm_expiry < gethrtime()) {
				return (ETIMEDOUT);
			}
		}

		if (ddi_in_panic()) {
			/*
			 * When the system is panicking, there are no
			 * interrupts or other threads.  Drive the polling loop
			 * on our own, but with a small delay to avoid
			 * aggrevating the controller while we're trying to
			 * dump.
			 */
			(void) smrt_retrieve(smrt);
			smrt_process_finishq(smrt);
			drv_usecwait(100);
			continue;
		}

		/*
		 * Wait for command completion to return through the regular
		 * interrupt handling path.
		 */
		if (smcm->smcm_expiry == 0) {
			cv_wait(&smrt->smrt_cv_finishq, &smrt->smrt_mutex);
		} else {
			/*
			 * Wait only until the expiry time for this command.
			 */
			(void) cv_timedwait_sig_hrtime(&smrt->smrt_cv_finishq,
			    &smrt->smrt_mutex, smcm->smcm_expiry);
		}
	}

	/*
	 * Fire the completion callback for this command.  The callback
	 * is responsible for freeing the command, so it may not be
	 * referenced again once this call returns.
	 */
	smrt_process_finishq_one(smcm);

	return (0);
}

void
smrt_intr_set(smrt_t *smrt, boolean_t enabled)
{
	/*
	 * Read the Interrupt Mask Register.
	 */
	uint32_t imr = smrt_get32(smrt, CISS_I2O_INTERRUPT_MASK);

	switch (smrt->smrt_ctlr_mode) {
	case SMRT_CTLR_MODE_SIMPLE:
		if (enabled) {
			imr &= ~CISS_IMR_BIT_SIMPLE_INTR_DISABLE;
		} else {
			imr |= CISS_IMR_BIT_SIMPLE_INTR_DISABLE;
		}
		smrt_put32(smrt, CISS_I2O_INTERRUPT_MASK, imr);
		return;

	case SMRT_CTLR_MODE_UNKNOWN:
		break;
	}
	panic("unknown controller mode");
}

/*
 * Signal to the controller that we have updated the Configuration Table by
 * writing to the Inbound Doorbell Register.  The controller will, after some
 * number of seconds, acknowledge this by clearing the bit.
 *
 * If successful, return DDI_SUCCESS.  If the controller takes too long to
 * acknowledge, return DDI_FAILURE.
 */
int
smrt_cfgtbl_flush(smrt_t *smrt)
{
	/*
	 * Read the current value of the Inbound Doorbell Register.
	 */
	uint32_t idr = smrt_get32(smrt, CISS_I2O_INBOUND_DOORBELL);

	/*
	 * Signal the Configuration Table change to the controller.
	 */
	idr |= CISS_IDR_BIT_CFGTBL_CHANGE;
	smrt_put32(smrt, CISS_I2O_INBOUND_DOORBELL, idr);

	/*
	 * Wait for the controller to acknowledge the change.
	 */
	for (unsigned i = 0; i < smrt_ciss_init_time; i++) {
		idr = smrt_get32(smrt, CISS_I2O_INBOUND_DOORBELL);

		if ((idr & CISS_IDR_BIT_CFGTBL_CHANGE) == 0) {
			return (DDI_SUCCESS);
		}

		/*
		 * Wait for one second before trying again.
		 */
		delay(drv_usectohz(1000000));
	}

	dev_err(smrt->smrt_dip, CE_WARN, "time out expired before controller "
	    "configuration completed");
	return (DDI_FAILURE);
}

int
smrt_cfgtbl_transport_has_support(smrt_t *smrt, int xport)
{
	VERIFY(xport == CISS_CFGTBL_XPORT_SIMPLE);

	/*
	 * Read the current value of the "Supported Transport Methods" field in
	 * the Configuration Table.
	 */
	uint32_t xport_active = ddi_get32(smrt->smrt_ct_handle,
	    &smrt->smrt_ct->TransportSupport);

	/*
	 * Check that the desired transport method is supported by the
	 * controller:
	 */
	if ((xport_active & xport) == 0) {
		dev_err(smrt->smrt_dip, CE_WARN, "controller does not support "
		    "method \"%s\"", xport == CISS_CFGTBL_XPORT_SIMPLE ?
		    "simple" : "performant");
		return (DDI_FAILURE);
	}

	return (DDI_SUCCESS);
}

void
smrt_cfgtbl_transport_set(smrt_t *smrt, int xport)
{
	VERIFY(xport == CISS_CFGTBL_XPORT_SIMPLE);

	ddi_put32(smrt->smrt_ct_handle, &smrt->smrt_ct->TransportRequest,
	    xport);
}

int
smrt_cfgtbl_transport_confirm(smrt_t *smrt, int xport)
{
	VERIFY(xport == CISS_CFGTBL_XPORT_SIMPLE);

	/*
	 * Read the current value of the TransportActive field in the
	 * Configuration Table.
	 */
	uint32_t xport_active = ddi_get32(smrt->smrt_ct_handle,
	    &smrt->smrt_ct->TransportActive);

	/*
	 * Check that the desired transport method is now active:
	 */
	if ((xport_active & xport) == 0) {
		dev_err(smrt->smrt_dip, CE_WARN, "failed to enable transport "
		    "method \"%s\"", xport == CISS_CFGTBL_XPORT_SIMPLE ?
		    "simple" : "performant");
		return (DDI_FAILURE);
	}

	/*
	 * Ensure that the controller is now ready to accept commands.
	 */
	if ((xport_active & CISS_CFGTBL_READY_FOR_COMMANDS) == 0) {
		dev_err(smrt->smrt_dip, CE_WARN, "controller not ready to "
		    "accept commands");
		return (DDI_FAILURE);
	}

	return (DDI_SUCCESS);
}

uint32_t
smrt_ctlr_get_maxsgelements(smrt_t *smrt)
{
	return (ddi_get32(smrt->smrt_ct_handle, &smrt->smrt_ct->MaxSGElements));
}

uint32_t
smrt_ctlr_get_cmdsoutmax(smrt_t *smrt)
{
	return (ddi_get32(smrt->smrt_ct_handle, &smrt->smrt_ct->CmdsOutMax));
}

static uint32_t
smrt_ctlr_get_hostdrvsup(smrt_t *smrt)
{
	return (ddi_get32(smrt->smrt_ct_handle,
	    &smrt->smrt_ct->HostDrvrSupport));
}

int
smrt_ctlr_init(smrt_t *smrt)
{
	uint8_t signature[4] = { 'C', 'I', 'S', 'S' };
	int e;

	if ((e = smrt_ctlr_wait_for_state(smrt,
	    SMRT_WAIT_STATE_READY)) != DDI_SUCCESS) {
		return (e);
	}

	/*
	 * The configuration table contains an ASCII signature ("CISS") which
	 * should be checked as we initialise the controller.
	 * See: "9.1 Configuration Table" in CISS Specification.
	 */
	for (unsigned i = 0; i < 4; i++) {
		if (ddi_get8(smrt->smrt_ct_handle,
		    &smrt->smrt_ct->Signature[i]) != signature[i]) {
			dev_err(smrt->smrt_dip, CE_WARN, "invalid signature "
			    "detected");
			return (DDI_FAILURE);
		}
	}

	/*
	 * Initialise an appropriate Transport Method.  For now, this driver
	 * only supports the "Simple" method.
	 */
	if ((e = smrt_ctlr_init_simple(smrt)) != DDI_SUCCESS) {
		return (e);
	}

	/*
	 * Save some common feature support bitfields.
	 */
	smrt->smrt_host_support = smrt_ctlr_get_hostdrvsup(smrt);
	smrt->smrt_bus_support = ddi_get32(smrt->smrt_ct_handle,
	    &smrt->smrt_ct->BusTypes);

	/*
	 * Read initial controller heartbeat value and mark the current
	 * reading time.
	 */
	smrt->smrt_last_heartbeat = ddi_get32(smrt->smrt_ct_handle,
	    &smrt->smrt_ct->HeartBeat);
	smrt->smrt_last_heartbeat_time = gethrtime();

	/*
	 * Determine the firmware version of the controller so that we can
	 * select which type of interrupts to use.
	 */
	if ((e = smrt_ctlr_versions(smrt, SMRT_DISCOVER_TIMEOUT,
	    &smrt->smrt_versions)) != 0) {
		dev_err(smrt->smrt_dip, CE_WARN, "could not identify "
		    "controller (%d)", e);
		return (DDI_FAILURE);
	}

	dev_err(smrt->smrt_dip, CE_NOTE, "!firmware rev %s",
	    smrt->smrt_versions.smrtv_firmware_rev);

	return (DDI_SUCCESS);
}

void
smrt_ctlr_teardown(smrt_t *smrt)
{
	smrt->smrt_status &= ~SMRT_CTLR_STATUS_RUNNING;

	switch (smrt->smrt_ctlr_mode) {
	case SMRT_CTLR_MODE_SIMPLE:
		smrt_ctlr_teardown_simple(smrt);
		return;

	case SMRT_CTLR_MODE_UNKNOWN:
		return;
	}

	panic("unknown controller mode");
}

int
smrt_ctlr_wait_for_state(smrt_t *smrt, smrt_wait_state_t state)
{
	unsigned wait_usec = 100 * 1000;
	unsigned wait_count = SMRT_WAIT_DELAY_SECONDS * 1000000 / wait_usec;

	VERIFY(state == SMRT_WAIT_STATE_READY ||
	    state == SMRT_WAIT_STATE_UNREADY);

	/*
	 * Read from the Scratchpad Register until the expected ready signature
	 * is detected.  This behaviour is not described in the CISS
	 * specification.
	 *
	 * If the device is not in the desired state immediately, sleep for a
	 * second and try again.  If the device has not become ready in 300
	 * seconds, give up.
	 */
	for (unsigned i = 0; i < wait_count; i++) {
		uint32_t spr = smrt_get32(smrt, CISS_I2O_SCRATCHPAD);

		switch (state) {
		case SMRT_WAIT_STATE_READY:
			if (spr == CISS_SCRATCHPAD_INITIALISED) {
				return (DDI_SUCCESS);
			}
			break;

		case SMRT_WAIT_STATE_UNREADY:
			if (spr != CISS_SCRATCHPAD_INITIALISED) {
				return (DDI_SUCCESS);
			}
			break;
		}

		if (ddi_in_panic()) {
			/*
			 * There is no sleep for the panicking, so we
			 * must spin wait:
			 */
			drv_usecwait(wait_usec);
		} else {
			/*
			 * Wait for a quarter second and try again.
			 */
			delay(drv_usectohz(wait_usec));
		}
	}

	dev_err(smrt->smrt_dip, CE_WARN, "time out waiting for controller "
	    "to enter state \"%s\"", state == SMRT_WAIT_STATE_READY ?
	    "ready": "unready");
	return (DDI_FAILURE);
}

void
smrt_lockup_check(smrt_t *smrt)
{
	/*
	 * Read the current controller heartbeat value.
	 */
	uint32_t heartbeat = ddi_get32(smrt->smrt_ct_handle,
	    &smrt->smrt_ct->HeartBeat);

	VERIFY(MUTEX_HELD(&smrt->smrt_mutex));

	/*
	 * Check to see if the value is the same as last time we looked:
	 */
	if (heartbeat != smrt->smrt_last_heartbeat) {
		/*
		 * The heartbeat value has changed, which suggests that the
		 * firmware in the controller has not yet come to a complete
		 * stop.  Record the new value, as well as the current time.
		 */
		smrt->smrt_last_heartbeat = heartbeat;
		smrt->smrt_last_heartbeat_time = gethrtime();
		return;
	}

	/*
	 * The controller _might_ have been able to signal to us that is
	 * has locked up.  This is a truly unfathomable state of affairs:
	 * If the firmware can tell it has flown off the rails, why not
	 * simply reset the controller?
	 */
	uint32_t odr = smrt_get32(smrt, CISS_I2O_OUTBOUND_DOORBELL_STATUS);
	uint32_t spr = smrt_get32(smrt, CISS_I2O_SCRATCHPAD);
	if ((odr & CISS_ODR_BIT_LOCKUP) != 0) {
		dev_err(smrt->smrt_dip, CE_PANIC, "HP SmartArray firmware has "
		    "reported a critical fault (odr %08x spr %08x)",
		    odr, spr);
	}

	if (gethrtime() > smrt->smrt_last_heartbeat_time + 60 * NANOSEC) {
		dev_err(smrt->smrt_dip, CE_PANIC, "HP SmartArray firmware has "
		    "stopped responding (odr %08x spr %08x)",
		    odr, spr);
	}
}

/*
 * Probe the controller with the IDENTIFY CONTROLLER request.  This is a BMIC
 * command, so it must be submitted to the controller and we must poll for its
 * completion.  This functionality is only presently used during controller
 * initialisation, so it uses the special pre-initialisation path for command
 * allocation and submission.
 */
static int
smrt_ctlr_identify(smrt_t *smrt, uint16_t timeout,
    smrt_identify_controller_t *resp)
{
	smrt_command_t *smcm;
	smrt_identify_controller_req_t smicr;
	int r;
	size_t sz;

	/*
	 * Allocate a command with a data buffer; the controller will fill it
	 * with identification information.  There is some suggestion in the
	 * firmware-level specification that the buffer length should be a
	 * multiple of 512 bytes for some controllers, so we round up.
	 */
	sz = P2ROUNDUP_TYPED(sizeof (*resp), 512, size_t);
	if ((smcm = smrt_command_alloc_preinit(smrt, sz, KM_SLEEP)) == NULL) {
		return (ENOMEM);
	}

	smrt_write_controller_lun_addr(&smcm->smcm_va_cmd->Header.LUN);

	smcm->smcm_va_cmd->Request.CDBLen = sizeof (smicr);
	smcm->smcm_va_cmd->Request.Timeout = timeout;
	smcm->smcm_va_cmd->Request.Type.Type = CISS_TYPE_CMD;
	smcm->smcm_va_cmd->Request.Type.Attribute = CISS_ATTR_SIMPLE;
	smcm->smcm_va_cmd->Request.Type.Direction = CISS_XFER_READ;

	/*
	 * Construct the IDENTIFY CONTROLLER request CDB.  Note that any
	 * reserved fields in the request must be filled with zeroes.
	 */
	bzero(&smicr, sizeof (smicr));
	smicr.smicr_opcode = CISS_SCMD_BMIC_READ;
	smicr.smicr_lun = 0;
	smicr.smicr_command = CISS_BMIC_IDENTIFY_CONTROLLER;
	bcopy(&smicr, &smcm->smcm_va_cmd->Request.CDB[0],
	    MIN(CISS_CDBLEN, sizeof (smicr)));

	/*
	 * Send the command to the device and poll for its completion.
	 */
	smcm->smcm_status |= SMRT_CMD_STATUS_POLLED;
	smcm->smcm_expiry = gethrtime() + timeout * NANOSEC;
	if ((r = smrt_preinit_command_simple(smrt, smcm)) != 0) {
		VERIFY3S(r, ==, ETIMEDOUT);
		VERIFY0(smcm->smcm_status & SMRT_CMD_STATUS_POLL_COMPLETE);

		/*
		 * This command timed out, but the driver is not presently
		 * initialised to the point where we can try to abort it.
		 * The command was created with the PREINIT type, so it
		 * does not appear in the global command tracking list.
		 * In order to avoid problems with DMA from the controller,
		 * we have to leak the command allocation.
		 */
		smcm = NULL;
		goto out;
	}

	if (smcm->smcm_status & SMRT_CMD_STATUS_RESET_SENT) {
		/*
		 * The controller was reset while we were trying to identify
		 * it.  Report failure.
		 */
		r = EIO;
		goto out;
	}

	if (smcm->smcm_status & SMRT_CMD_STATUS_ERROR) {
		ErrorInfo_t *ei = smcm->smcm_va_err;

		if (ei->CommandStatus != CISS_CMD_DATA_UNDERRUN) {
			dev_err(smrt->smrt_dip, CE_WARN, "identify "
			    "controller error: status 0x%x",
			    ei->CommandStatus);
			r = EIO;
			goto out;
		}
	}

	if (resp != NULL) {
		/*
		 * Copy the identify response out for the caller.
		 */
		bcopy(smcm->smcm_internal->smcmi_va, resp, sizeof (*resp));
	}

	r = 0;

out:
	if (smcm != NULL) {
		smrt_command_free(smcm);
	}
	return (r);
}

/*
 * The firmware versions in an IDENTIFY CONTROLLER response generally take
 * the form of a four byte ASCII string containing a dotted decimal version
 * number; e.g., "8.00".
 *
 * This function sanitises the firmware version, replacing unexpected
 * values with a question mark.
 */
static void
smrt_copy_firmware_version(uint8_t *src, char *dst)
{
	for (unsigned i = 0; i < 4; i++) {
		/*
		 * Make sure that this is a 7-bit clean ASCII value.
		 */
		char c = src[i] <= 0x7f ? (char)(src[i] & 0x7f) : '?';

		if (isalnum(c) || c == '.' || c == ' ') {
			dst[i] = c;
		} else {
			dst[i] = '?';
		}
	}
	dst[4] = '\0';
}

/*
 * Using an IDENTIFY CONTROLLER request, determine firmware and controller
 * version details.  See the comments for "smrt_ctlr_identify()" for more
 * details about calling context.
 */
static int
smrt_ctlr_versions(smrt_t *smrt, uint16_t timeout, smrt_versions_t *smrtv)
{
	smrt_identify_controller_t smic;
	int r;

	if ((r = smrt_ctlr_identify(smrt, timeout, &smic)) != 0) {
		return (r);
	}

	smrtv->smrtv_hardware_version = smic.smic_hardware_version;
	smrt_copy_firmware_version(smic.smic_firmware_rev,
	    smrtv->smrtv_firmware_rev);
	smrt_copy_firmware_version(smic.smic_recovery_rev,
	    smrtv->smrtv_recovery_rev);
	smrt_copy_firmware_version(smic.smic_bootblock_rev,
	    smrtv->smrtv_bootblock_rev);

	return (0);
}

int
smrt_ctlr_reset(smrt_t *smrt)
{
	smrt_command_t *smcm, *smcm_nop;
	int r;

	VERIFY(MUTEX_HELD(&smrt->smrt_mutex));

	if (ddi_in_panic()) {
		goto skip_check;
	}

	if (smrt->smrt_status & SMRT_CTLR_STATUS_RESETTING) {
		/*
		 * Don't pile on.  One reset is enough.  Wait until
		 * it's complete, and then return success.
		 */
		while (smrt->smrt_status & SMRT_CTLR_STATUS_RESETTING) {
			cv_wait(&smrt->smrt_cv_finishq, &smrt->smrt_mutex);
		}
		return (0);
	}
	smrt->smrt_status |= SMRT_CTLR_STATUS_RESETTING;
	smrt->smrt_last_reset_start = gethrtime();
	smrt->smrt_stats.smrts_ctlr_resets++;

skip_check:
	/*
	 * Allocate two commands: one for the soft reset message, which we
	 * cannot free until the controller has reset; and one for the ping we
	 * will use to determine when it is once again functional.
	 */
	mutex_exit(&smrt->smrt_mutex);
	if ((smcm = smrt_command_alloc(smrt, SMRT_CMDTYPE_INTERNAL,
	    KM_NOSLEEP)) == NULL) {
		mutex_enter(&smrt->smrt_mutex);
		return (ENOMEM);
	}
	if ((smcm_nop = smrt_command_alloc(smrt, SMRT_CMDTYPE_INTERNAL,
	    KM_NOSLEEP)) == NULL) {
		smrt_command_free(smcm);
		mutex_enter(&smrt->smrt_mutex);
		return (ENOMEM);
	}
	mutex_enter(&smrt->smrt_mutex);

	/*
	 * Send a soft reset command to the controller.  If this command
	 * succeeds, there will likely be no completion notification.  Instead,
	 * the device should become unavailable for some period of time and
	 * then become available again.  Once available again, we know the soft
	 * reset has completed and should abort all in-flight commands.
	 */
	smrt_write_message_reset_ctlr(smcm);

	/*
	 * Disable interrupts now.
	 */
	smrt_intr_set(smrt, B_FALSE);

	dev_err(smrt->smrt_dip, CE_WARN, "attempting controller soft reset");
	smcm->smcm_status |= SMRT_CMD_STATUS_POLLED;
	if ((r = smrt_submit(smrt, smcm)) != 0) {
		dev_err(smrt->smrt_dip, CE_PANIC, "soft reset failed: "
		    "submit failed (%d)", r);
	}

	/*
	 * Mark every currently inflight command as being reset, including the
	 * soft reset command we just sent.  Once we confirm the reset works,
	 * we can safely report that these commands have failed.
	 */
	for (smrt_command_t *t = avl_first(&smrt->smrt_inflight);
	    t != NULL; t = AVL_NEXT(&smrt->smrt_inflight, t)) {
		t->smcm_status |= SMRT_CMD_STATUS_RESET_SENT;
	}

	/*
	 * Now that we have submitted our soft reset command, prevent
	 * the rest of the driver from interacting with the controller.
	 */
	smrt->smrt_status &= ~SMRT_CTLR_STATUS_RUNNING;

	/*
	 * We do not expect a completion from the controller for our soft
	 * reset command, but we also cannot remove it from the inflight
	 * list until we know the controller has actually reset.  To do
	 * otherwise would potentially allow the controller to scribble
	 * on the memory we were using.
	 */
	smcm->smcm_status |= SMRT_CMD_STATUS_ABANDONED;

	if (smrt_ctlr_wait_for_state(smrt, SMRT_WAIT_STATE_UNREADY) !=
	    DDI_SUCCESS) {
		dev_err(smrt->smrt_dip, CE_PANIC, "soft reset failed: "
		    "controller did not become unready");
	}
	dev_err(smrt->smrt_dip, CE_NOTE, "soft reset: controller unready");

	if (smrt_ctlr_wait_for_state(smrt, SMRT_WAIT_STATE_READY) !=
	    DDI_SUCCESS) {
		dev_err(smrt->smrt_dip, CE_PANIC, "soft reset failed: "
		    "controller did not come become ready");
	}
	dev_err(smrt->smrt_dip, CE_NOTE, "soft reset: controller ready");

	/*
	 * In at least the Smart Array P420i, the controller can take 30-45
	 * seconds after the scratchpad register shows it as being available
	 * before it is ready to receive commands.  In order to avoid hitting
	 * it too early with our post-reset ping, we will sleep for 10 seconds
	 * here.
	 */
	if (ddi_in_panic()) {
		drv_usecwait(10 * MICROSEC);
	} else {
		delay(drv_usectohz(10 * MICROSEC));
	}

	smrt_ctlr_teardown(smrt);
	if (smrt_ctlr_init(smrt) != DDI_SUCCESS) {
		dev_err(smrt->smrt_dip, CE_PANIC, "soft reset failed: "
		    "controller transport could not be configured");
	}
	dev_err(smrt->smrt_dip, CE_NOTE, "soft reset: controller configured");

	smrt_write_message_nop(smcm_nop, 0);
	smcm_nop->smcm_status |= SMRT_CMD_STATUS_POLLED |
	    SMRT_CMD_IGNORE_RUNNING;
	if ((r = smrt_submit(smrt, smcm_nop)) != 0) {
		dev_err(smrt->smrt_dip, CE_PANIC, "soft reset failed: "
		    "ping could not be submitted (%d)", r);
	}

	/*
	 * Interrupts are still masked at this stage.  Poll manually in
	 * a way that will not trigger regular finish queue processing:
	 */
	VERIFY(smcm_nop->smcm_status & SMRT_CMD_STATUS_INFLIGHT);
	for (unsigned i = 0; i < 600; i++) {
		smrt_retrieve_simple(smrt);

		if (!(smcm_nop->smcm_status & SMRT_CMD_STATUS_INFLIGHT)) {
			/*
			 * Remove the ping command from the finish queue and
			 * process it manually.  This processing must mirror
			 * what would have been done in smrt_process_finishq().
			 */
			VERIFY(list_link_active(&smcm_nop->smcm_link_finish));
			list_remove(&smrt->smrt_finishq, smcm_nop);
			smrt_process_finishq_sync(smcm_nop);
			smcm_nop->smcm_status |= SMRT_CMD_STATUS_POLL_COMPLETE;
			smrt_process_finishq_one(smcm_nop);
			break;
		}

		if (ddi_in_panic()) {
			drv_usecwait(100 * 1000);
		} else {
			delay(drv_usectohz(100 * 1000));
		}
	}

	if (!(smcm_nop->smcm_status & SMRT_CMD_STATUS_COMPLETE)) {
		dev_err(smrt->smrt_dip, CE_PANIC, "soft reset failed: "
		    "ping did not complete");
	} else if (smcm_nop->smcm_status & SMRT_CMD_STATUS_ERROR) {
		dev_err(smrt->smrt_dip, CE_WARN, "soft reset: ping completed "
		    "in error (status %u)",
		    (unsigned)smcm_nop->smcm_va_err->CommandStatus);
	} else {
		dev_err(smrt->smrt_dip, CE_NOTE, "soft reset: ping completed");
	}

	/*
	 * Now that the controller is working again, we can abort any
	 * commands that were inflight during the reset.
	 */
	smrt_command_t *nt;
	for (smrt_command_t *t = avl_first(&smrt->smrt_inflight);
	    t != NULL; t = nt) {
		nt = AVL_NEXT(&smrt->smrt_inflight, t);

		if (t->smcm_status & SMRT_CMD_STATUS_RESET_SENT) {
			avl_remove(&smrt->smrt_inflight, t);
			t->smcm_status &= ~SMRT_CMD_STATUS_INFLIGHT;

			list_insert_tail(&smrt->smrt_finishq, t);
		}
	}

	/*
	 * Quiesce our discovery thread.  Note, because
	 * SMRT_CTLR_STATUS_RESTARTING is set, nothing can cause it to be
	 * enabled again.
	 */
	if (!ddi_in_panic()) {
		mutex_exit(&smrt->smrt_mutex);
		ddi_taskq_wait(smrt->smrt_discover_taskq);
		mutex_enter(&smrt->smrt_mutex);
	}

	/*
	 * Re-enable interrupts.  Now, we must kick off a discovery to make sure
	 * that the system is in a sane state and that we can perform I/O.
	 */
	smrt_intr_set(smrt, B_TRUE);
	smrt->smrt_status &= ~SMRT_CTLR_STATUS_RESETTING;
	smrt->smrt_status |= SMRT_CTLR_DISCOVERY_REQUIRED;

	/*
	 * Attempt a discovery to make sure that the drivers sees a realistic
	 * view of the world.  If we're not in panic context, spin for the
	 * asynchronous process to complete, otherwise we're in panic context
	 * and this is going to happen regardless if we want it to or not.
	 * Before we kick off the request to run discovery, we reset the
	 * discovery request flags as we know that nothing else can consider
	 * running discovery and we don't want to delay until the next smrt
	 * periodic tick if we can avoid it.  In panic context, if this failed,
	 * then we won't make it back.
	 */
	VERIFY0(smrt->smrt_status & SMRT_CTLR_DISCOVERY_RUNNING);
	smrt->smrt_status &= ~(SMRT_CTLR_DISCOVERY_MASK);
	smrt_discover(smrt);
	if (!ddi_in_panic()) {
		while (smrt->smrt_status & SMRT_CTLR_DISCOVERY_REQUIRED) {
			cv_wait(&smrt->smrt_cv_finishq, &smrt->smrt_mutex);
		}
	}

	smrt->smrt_status |= SMRT_CTLR_STATUS_RUNNING;
	smrt->smrt_last_reset_finish = gethrtime();

	/*
	 * Wake anybody that was waiting for the reset to complete.
	 */
	cv_broadcast(&smrt->smrt_cv_finishq);

	/*
	 * Process the completion queue one last time before we let go
	 * of the mutex.
	 */
	smrt_process_finishq(smrt);

	mutex_exit(&smrt->smrt_mutex);
	smrt_command_free(smcm_nop);
	mutex_enter(&smrt->smrt_mutex);
	return (0);
}

int
smrt_event_init(smrt_t *smrt)
{
	int ret;
	smrt_command_t *event, *cancel;

	event = smrt_command_alloc(smrt, SMRT_CMDTYPE_EVENT, KM_NOSLEEP);
	if (event == NULL)
		return (ENOMEM);
	if (smrt_command_attach_internal(smrt, event, SMRT_EVENT_NOTIFY_BUFLEN,
	    KM_NOSLEEP) != 0) {
		smrt_command_free(event);
		return (ENOMEM);
	}
	smrt_write_message_event_notify(event);

	cancel = smrt_command_alloc(smrt, SMRT_CMDTYPE_INTERNAL, KM_NOSLEEP);
	if (cancel == NULL) {
		smrt_command_free(event);
		return (ENOMEM);
	}
	if (smrt_command_attach_internal(smrt, cancel, SMRT_EVENT_NOTIFY_BUFLEN,
	    KM_NOSLEEP) != 0) {
		smrt_command_free(event);
		smrt_command_free(cancel);
		return (ENOMEM);
	}
	smrt_write_message_cancel_event_notify(cancel);

	cv_init(&smrt->smrt_event_queue, NULL, CV_DRIVER, NULL);

	mutex_enter(&smrt->smrt_mutex);
	if ((ret = smrt_submit(smrt, event)) != 0) {
		mutex_exit(&smrt->smrt_mutex);
		smrt_command_free(event);
		smrt_command_free(cancel);
		return (ret);
	}

	smrt->smrt_event_cmd = event;
	smrt->smrt_event_cancel_cmd = cancel;
	mutex_exit(&smrt->smrt_mutex);

	return (0);
}

void
smrt_event_complete(smrt_command_t *smcm)
{
	smrt_event_notify_t *sen;
	boolean_t log, rescan;

	boolean_t intervene = B_FALSE;
	smrt_t *smrt = smcm->smcm_ctlr;

	VERIFY(MUTEX_HELD(&smrt->smrt_mutex));
	VERIFY3P(smcm, ==, smrt->smrt_event_cmd);
	VERIFY0(smrt->smrt_status & SMRT_CTLR_ASYNC_INTERVENTION);

	smrt->smrt_stats.smrts_events_received++;

	if (smrt->smrt_status & SMRT_CTLR_STATUS_DETACHING) {
		cv_signal(&smrt->smrt_event_queue);
		return;
	}

	if (smrt->smrt_status & SMRT_CTLR_STATUS_RESETTING) {
		intervene = B_TRUE;
		goto clean;
	}

	/*
	 * The event notification command failed for some reason.  Attempt to
	 * drive on and try again at the next intervention period.  Because this
	 * may represent a programmer error (though it's hard to know), we wait
	 * until the next intervention period and don't panic.
	 */
	if (smcm->smcm_status & SMRT_CMD_STATUS_ERROR) {
		ErrorInfo_t *ei = smcm->smcm_va_err;
		intervene = B_TRUE;

		smrt->smrt_stats.smrts_events_errors++;
		dev_err(smrt->smrt_dip, CE_WARN, "!event notification request "
		    "error: status 0x%x", ei->CommandStatus);
		goto clean;
	}

	sen = smcm->smcm_internal->smcmi_va;
	log = rescan = B_FALSE;
	switch (sen->sen_class) {
	case SMRT_EVENT_CLASS_PROTOCOL:
		/*
		 * Most of the event protocol class events aren't really
		 * actionable.  However, subclass 1 indicates errors.  Today,
		 * the only error is an event overflow.  If there's an event
		 * overflow, then we must assume that we need to rescan.
		 */
		if (sen->sen_subclass == SMRT_EVENT_PROTOCOL_SUBCLASS_ERROR) {
			rescan = B_TRUE;
		}
		break;
	case SMRT_EVENT_CLASS_HOTPLUG:
		/*
		 * We want to log all hotplug events.  However we only need to
		 * scan these if the subclass indicates the event is for a disk.
		 */
		log = B_TRUE;
		if (sen->sen_subclass == SMRT_EVENT_HOTPLUG_SUBCLASS_DRIVE) {
			rescan = B_TRUE;
		}
		break;
	case SMRT_EVENT_CLASS_HWERROR:
	case SMRT_EVENT_CLASS_ENVIRONMENT:
		log = B_TRUE;
		break;
	case SMRT_EVENT_CLASS_PHYS:
		log = B_TRUE;
		/*
		 * This subclass indicates some change for physical drives.  As
		 * such, this should trigger a rescan.
		 */
		if (sen->sen_subclass == SMRT_EVENT_PHYS_SUBCLASS_STATE) {
			rescan = B_TRUE;
		}
		break;
	case SMRT_EVENT_CLASS_LOGVOL:
		rescan = B_TRUE;
		log = B_TRUE;
		break;
	default:
		/*
		 * While there are other classes of events, it's hard to say how
		 * actionable they are for the moment.  If we revamp this such
		 * that it becomes an ireport based system, then we should just
		 * always log these.  We opt not to at the moment to try and be
		 * kind to the system log.
		 */
		break;
	}

	/*
	 * Ideally, this would be an ireport that we could pass onto
	 * administrators; however, since we don't have any way to generate
	 * that, we provide a subset of the event information.
	 */
	if (log) {
		const char *rmsg;
		if (rescan == B_TRUE) {
			rmsg = "rescanning";
		} else {
			rmsg = "not rescanning";
		}
		if (sen->sen_message[0] != '\0') {
			sen->sen_message[sizeof (sen->sen_message) - 1] = '\0';
			dev_err(smrt->smrt_dip, CE_NOTE, "!controller event "
			    "class/sub-class/detail %x, %x, %x: %s; %s devices",
			    sen->sen_class, sen->sen_subclass, sen->sen_detail,
			    sen->sen_message, rmsg);
		} else {
			dev_err(smrt->smrt_dip, CE_NOTE, "!controller event "
			    "class/sub-class/detail %x, %x, %x; %s devices",
			    sen->sen_class, sen->sen_subclass, sen->sen_detail,
			    rmsg);
		}
	}

	if (rescan)
		smrt_discover_request(smrt);

clean:
	mutex_exit(&smrt->smrt_mutex);
	smrt_command_reuse(smcm);
	bzero(smcm->smcm_internal->smcmi_va, SMRT_EVENT_NOTIFY_BUFLEN);
	mutex_enter(&smrt->smrt_mutex);

	/*
	 * Make sure we're not _now_ detaching or resetting.
	 */
	if (smrt->smrt_status & SMRT_CTLR_STATUS_DETACHING) {
		cv_signal(&smrt->smrt_event_queue);
		return;
	}

	if ((smrt->smrt_status & SMRT_CTLR_STATUS_RESETTING) != 0 ||
	    intervene == B_TRUE) {
		smrt->smrt_status |= SMRT_CTLR_ASYNC_INTERVENTION;
		return;
	}

	/*
	 * Check out command count per tick.  If it's too high, leave it for
	 * intervention to solve.  Likely there is some serious driver or
	 * firmware error going on.
	 */
	smrt->smrt_event_count++;
	if (smrt->smrt_event_count > smrt_event_intervention_threshold) {
		smrt->smrt_status |= SMRT_CTLR_ASYNC_INTERVENTION;
		return;
	}

	if (smrt_submit(smrt, smcm) != 0) {
		smrt->smrt_status |= SMRT_CTLR_ASYNC_INTERVENTION;
	}
}

void
smrt_event_fini(smrt_t *smrt)
{
	int ret;
	smrt_command_t *event, *cancel;
	mutex_enter(&smrt->smrt_mutex);

	/*
	 * If intervention has been requested, there is nothing for us to do. We
	 * clear the flag so nothing else accidentally sees this and takes
	 * action.  We also don't need to bother sending a cancellation request,
	 * as there is no outstanding event.
	 */
	if (smrt->smrt_status & SMRT_CTLR_ASYNC_INTERVENTION) {
		smrt->smrt_status &= ~SMRT_CTLR_ASYNC_INTERVENTION;
		goto free;
	}

	/*
	 * Submit a cancel request for the event notification queue.  Because we
	 * submit both the cancel event and the regular notification event as an
	 * ordered command, we know that by the time this completes, that the
	 * existing one will have completed.
	 */
	smrt->smrt_event_cancel_cmd->smcm_status |= SMRT_CMD_STATUS_POLLED;
	if ((ret = smrt_submit(smrt, smrt->smrt_event_cancel_cmd)) != 0) {
		/*
		 * This is unfortunate.  We've failed to submit the command.  At
		 * this point all we can do is reset the device.  If the reset
		 * succeeds, we're done and we can clear all the memory.  If it
		 * fails, then all we can do is just leak the command and scream
		 * to the system, sorry.
		 */
		if (smrt_ctlr_reset(smrt) != 0) {
			dev_err(smrt->smrt_dip, CE_WARN, "failed to reset "
			    "device after failure to submit cancellation "
			    "(%d), abandoning smrt_command_t at address %p",
			    ret, smrt->smrt_event_cmd);
			smrt->smrt_event_cmd = NULL;
			goto free;
		}
	}

	smrt->smrt_event_cancel_cmd->smcm_expiry = gethrtime() +
	    SMRT_ASYNC_CANCEL_TIMEOUT * NANOSEC;
	if ((ret = smrt_poll_for(smrt, smrt->smrt_event_cancel_cmd)) != 0) {
		VERIFY3S(ret, ==, ETIMEDOUT);
		VERIFY0(smrt->smrt_event_cancel_cmd->smcm_status &
		    SMRT_CMD_STATUS_POLL_COMPLETE);

		/*
		 * The command timed out.  All we can do is hope a reset will
		 * work.
		 */
		if (smrt_ctlr_reset(smrt) != 0) {
			dev_err(smrt->smrt_dip, CE_WARN, "failed to reset "
			    "device after failure to poll for async "
			    "cancellation command abandoning smrt_command_t "
			    "event command at address %p and cancellation "
			    "command at %p", smrt->smrt_event_cmd,
			    smrt->smrt_event_cancel_cmd);
			smrt->smrt_event_cmd = NULL;
			smrt->smrt_event_cancel_cmd = NULL;
			goto free;
		}

	}

	/*
	 * Well, in the end, it's results that count.
	 */
	if (smrt->smrt_event_cancel_cmd->smcm_status &
	    SMRT_CMD_STATUS_RESET_SENT) {
		goto free;
	}

	if (smrt->smrt_event_cancel_cmd->smcm_status & SMRT_CMD_STATUS_ERROR) {
		ErrorInfo_t *ei = smrt->smrt_event_cancel_cmd->smcm_va_err;

		/*
		 * This can return a CISS_CMD_TARGET_STATUS entry when the
		 * controller doesn't think a command is outstanding.  It is
		 * possible we raced, so don't think too much about that case.
		 * Anything else leaves us between a rock and a hard place, the
		 * only way out is a reset.
		 */
		if (ei->CommandStatus != CISS_CMD_TARGET_STATUS &&
		    smrt_ctlr_reset(smrt) != 0) {
			dev_err(smrt->smrt_dip, CE_WARN, "failed to reset  "
			    "device after receiving an error on the async "
			    "cancellation command (%d); abandoning "
			    "smrt_command_t event command at address %p and "
			    "cancellation command at %p", ei->CommandStatus,
			    smrt->smrt_event_cmd, smrt->smrt_event_cancel_cmd);
			smrt->smrt_event_cmd = NULL;
			smrt->smrt_event_cancel_cmd = NULL;
			goto free;
		}
	}

free:
	event = smrt->smrt_event_cmd;
	smrt->smrt_event_cmd = NULL;
	cancel = smrt->smrt_event_cancel_cmd;
	smrt->smrt_event_cancel_cmd = NULL;
	mutex_exit(&smrt->smrt_mutex);
	if (event != NULL)
		smrt_command_free(event);
	if (cancel != NULL)
		smrt_command_free(cancel);
	cv_destroy(&smrt->smrt_event_queue);
}

/*
 * We've been asked to do a discovery in panic context.  This would have
 * occurred because there was a device reset.  Because we can't rely on the
 * target maps, all we can do at the moment is go over all the active targets
 * and note which ones no longer exist.  If this target was required to dump,
 * then the dump code will encounter a fatal error.  If not, then we should
 * count ourselves surprisingly lucky.
 */
static void
smrt_discover_panic_check(smrt_t *smrt)
{
	smrt_target_t *smtg;

	ASSERT(MUTEX_HELD(&smrt->smrt_mutex));
	for (smtg = list_head(&smrt->smrt_targets); smtg != NULL;
	    smtg = list_next(&smrt->smrt_targets, smtg)) {
		uint64_t gen;

		if (smtg->smtg_physical) {
			smrt_physical_t *smpt = smtg->smtg_lun.smtg_phys;
			/*
			 * Don't worry about drives that aren't visible.
			 */
			if (!smpt->smpt_visible)
				continue;
			gen = smpt->smpt_gen;
		} else {
			smrt_volume_t *smlv = smtg->smtg_lun.smtg_vol;
			gen = smlv->smlv_gen;
		}

		if (gen != smrt->smrt_discover_gen) {
			dev_err(smrt->smrt_dip, CE_WARN, "target %s "
			    "disappeared during post-panic discovery",
			    scsi_device_unit_address(smtg->smtg_scsi_dev));
			smtg->smtg_gone = B_TRUE;
		}
	}
}

static void
smrt_discover(void *arg)
{
	int log = 0, phys = 0;
	smrt_t *smrt = arg;
	uint64_t gen;
	boolean_t runphys, runvirt;

	mutex_enter(&smrt->smrt_mutex);
	smrt->smrt_status |= SMRT_CTLR_DISCOVERY_RUNNING;
	smrt->smrt_status &= ~SMRT_CTLR_DISCOVERY_REQUESTED;

	smrt->smrt_discover_gen++;
	gen = smrt->smrt_discover_gen;
	runphys = smrt->smrt_phys_tgtmap != NULL;
	runvirt = smrt->smrt_virt_tgtmap != NULL;
	mutex_exit(&smrt->smrt_mutex);
	if (runphys)
		phys = smrt_phys_discover(smrt, SMRT_DISCOVER_TIMEOUT, gen);
	if (runvirt)
		log = smrt_logvol_discover(smrt, SMRT_DISCOVER_TIMEOUT, gen);
	mutex_enter(&smrt->smrt_mutex);

	if (phys != 0 || log != 0) {
		if (!ddi_in_panic()) {
			smrt->smrt_status |= SMRT_CTLR_DISCOVERY_PERIODIC;
		} else {
			panic("smrt_t %p failed to perform discovery after "
			    "a reset in panic context, unable to continue. "
			    "logvol: %d, phys: %d", smrt, log, phys);
		}
	} else {
		if (!ddi_in_panic() &&
		    smrt->smrt_status & SMRT_CTLR_DISCOVERY_REQUIRED) {
			smrt->smrt_status &= ~SMRT_CTLR_DISCOVERY_REQUIRED;
			cv_broadcast(&smrt->smrt_cv_finishq);
		}

		if (ddi_in_panic()) {
			smrt_discover_panic_check(smrt);
		}
	}
	smrt->smrt_status &= ~SMRT_CTLR_DISCOVERY_RUNNING;
	if (smrt->smrt_status & SMRT_CTLR_DISCOVERY_REQUESTED)
		smrt->smrt_status |= SMRT_CTLR_DISCOVERY_PERIODIC;
	mutex_exit(&smrt->smrt_mutex);
}

/*
 * Request discovery, which is always run via a taskq.
 */
void
smrt_discover_request(smrt_t *smrt)
{
	boolean_t run;
	ASSERT(MUTEX_HELD(&smrt->smrt_mutex));

	if (ddi_in_panic()) {
		smrt_discover(smrt);
		return;
	}

	run = (smrt->smrt_status & SMRT_CTLR_DISCOVERY_MASK) == 0;
	smrt->smrt_status |= SMRT_CTLR_DISCOVERY_REQUESTED;
	if (run && ddi_taskq_dispatch(smrt->smrt_discover_taskq,
	    smrt_discover, smrt, DDI_NOSLEEP) != DDI_SUCCESS) {
		smrt->smrt_status |= SMRT_CTLR_DISCOVERY_PERIODIC;
		smrt->smrt_stats.smrts_discovery_tq_errors++;
	}
}