|
root / base / usr / src / uts / common / io / scsi / targets / sgen.c
sgen.c C 2119 lines 54.1 KB
   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
/*
 * CDDL HEADER START
 *
 * The contents of this file are subject to the terms of the
 * Common Development and Distribution License (the "License").
 * You may not use this file except in compliance with the License.
 *
 * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
 * or http://www.opensolaris.org/os/licensing.
 * See the License for the specific language governing permissions
 * and limitations under the License.
 *
 * When distributing Covered Code, include this CDDL HEADER in each
 * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
 * If applicable, add the following below this CDDL HEADER, with the
 * fields enclosed by brackets "[]" replaced with your own identifying
 * information: Portions Copyright [yyyy] [name of copyright owner]
 *
 * CDDL HEADER END
 */

/*
 * Copyright 2008 Sun Microsystems, Inc.  All rights reserved.
 * Use is subject to license terms.
 */

/*
 * Copyright Siemens 1999
 * All rights reserved.
 */


/*
 * sgen - SCSI generic device driver
 *
 * The sgen driver provides user programs access to SCSI devices that
 * are not supported by other drivers by providing the uscsi(4I) interface.
 */

#include <sys/modctl.h>
#include <sys/file.h>
#include <sys/scsi/scsi.h>
#include <sys/scsi/targets/sgendef.h>

/* The name of the driver, established from the module name in _init. */
static	char *sgen_label	= NULL;

#define	DDI_NT_SGEN		"ddi_generic:scsi"

static char *sgen_devtypes[] = {
	"direct",		/* 0x00 -- disks */
	"sequential",		/* 0x01 */
	"printer",		/* 0x02 */
	"processor",		/* 0x03 */
	"worm",			/* 0x04 */
	"rodirect",		/* 0x05 */
	"scanner",		/* 0x06 */
	"optical",		/* 0x07 */
	"changer",		/* 0x08 */
	"comm",			/* 0x09 */
	"prepress1",		/* 0x0a -- reserved for prepress (ASC IT8) */
	"prepress2",		/* 0x0b -- reserved for prepress (ASC IT8) */
	"array_ctrl",		/* 0x0c -- storage array */
	"ses",			/* 0x0d -- enclosure services */
	"rbc",			/* 0x0e -- simplified block */
	"ocrw",			/* 0x0f -- optical card read/write */
	"bridge",		/* 0x10 -- reserved for bridging expanders */
	"type_0x11",		/* 0x11 */
	"type_0x12",		/* 0x12 */
	"type_0x13",		/* 0x13 */
	"type_0x14",		/* 0x14 */
	"type_0x15",		/* 0x15 */
	"type_0x16",		/* 0x16 */
	"type_0x17",		/* 0x17 */
	"type_0x18",		/* 0x18 */
	"type_0x19",		/* 0x19 */
	"type_0x1a",		/* 0x1a */
	"type_0x1b",		/* 0x1b */
	"type_0x1c",		/* 0x1c */
	"type_0x1d",		/* 0x1d */
	"type_0x1e",		/* 0x1e */
	"type_unknown"		/* 0x1f is "no device type" or "unknown" */
};

#define	SGEN_NDEVTYPES ((sizeof (sgen_devtypes) / sizeof (char *)))

#define	SGEN_INQSTRLEN 24
#define	SGEN_VENDID_MAX 8
#define	SGEN_PRODID_MAX 16

#define	FILL_SCSI1_LUN(devp, pkt)					\
	if ((devp)->sd_inq->inq_ansi == 0x1) {				\
		int _lun;						\
		_lun = ddi_prop_get_int(DDI_DEV_T_ANY, (devp)->sd_dev,	\
		    DDI_PROP_DONTPASS, SCSI_ADDR_PROP_LUN, 0);		\
		if (_lun > 0) {						\
			((union scsi_cdb *)(pkt)->pkt_cdbp)->scc_lun =	\
			    _lun;					\
		}							\
	}

#define	SGEN_DO_ERRSTATS(sg_state, x)  \
	if (sg_state->sgen_kstats) { \
		struct sgen_errstats *sp; \
		sp = (struct sgen_errstats *)sg_state->sgen_kstats->ks_data; \
		sp->x.value.ui32++; \
	}

#define	SCBP_C(pkt)	((*(pkt)->pkt_scbp) & STATUS_MASK)

/*
 * Standard entrypoints
 */
static int sgen_attach(dev_info_t *, ddi_attach_cmd_t);
static int sgen_detach(dev_info_t *, ddi_detach_cmd_t);
static int sgen_getinfo(dev_info_t *, ddi_info_cmd_t, void *, void **);
static int sgen_probe(dev_info_t *);
static int sgen_open(dev_t *, int, int, cred_t *);
static int sgen_close(dev_t, int, int, cred_t *);
static int sgen_ioctl(dev_t, int, intptr_t, int, cred_t *, int *);

/*
 * Configuration routines
 */
static int sgen_do_attach(dev_info_t *);
static int sgen_setup_sense(sgen_state_t *);
static void sgen_create_errstats(sgen_state_t *, int);
static int sgen_do_suspend(dev_info_t *);
static int sgen_do_detach(dev_info_t *);
static void sgen_setup_binddb(dev_info_t *);
static void sgen_cleanup_binddb();

/*
 * Packet transport routines
 */
static int  sgen_uscsi_cmd(dev_t, struct uscsi_cmd *, int);
static int sgen_start(struct buf *);
static int sgen_hold_cmdbuf(sgen_state_t *);
static void sgen_rele_cmdbuf(sgen_state_t *);
static int sgen_make_uscsi_cmd(sgen_state_t *, struct buf *);
static void sgen_restart(void *);
static void sgen_callback(struct scsi_pkt *);
static int sgen_handle_autosense(sgen_state_t *, struct scsi_pkt *);
static int sgen_handle_sense(sgen_state_t *);
static int sgen_handle_incomplete(sgen_state_t *, struct scsi_pkt *);
static int sgen_check_error(sgen_state_t *, struct buf *);
static int sgen_initiate_sense(sgen_state_t *, int);
static int sgen_scsi_transport(struct scsi_pkt *);
static int sgen_tur(dev_t);

/*
 * Logging/debugging routines
 */
static void sgen_log(sgen_state_t  *, int,  const char *, ...);
static int sgen_diag_ok(sgen_state_t *, int);
static void sgen_dump_cdb(sgen_state_t *, const char *, union scsi_cdb *, int);
static void sgen_dump_sense(sgen_state_t *, size_t, uchar_t *);

int sgen_diag = 0;
int sgen_sporadic_failures = 0;
int sgen_force_manual_sense = 0;
struct sgen_binddb sgen_binddb;

static struct cb_ops sgen_cb_ops = {
	sgen_open,			/* open */
	sgen_close,			/* close */
	nodev,				/* strategy */
	nodev,				/* print */
	nodev,				/* dump */
	nodev,				/* read */
	nodev,				/* write */
	sgen_ioctl,			/* ioctl */
	nodev,				/* devmap */
	nodev,				/* mmap */
	nodev,				/* segmap */
	nochpoll,			/* poll */
	ddi_prop_op,			/* cb_prop_op */
	0,				/* streamtab  */
	D_MP | D_NEW | D_HOTPLUG	/* Driver compatibility flag */
};

static struct dev_ops sgen_dev_ops = {
	DEVO_REV,		/* devo_rev, */
	0,			/* refcnt  */
	sgen_getinfo,		/* info */
	nodev,			/* identify */
	sgen_probe,		/* probe */
	sgen_attach,		/* attach */
	sgen_detach,		/* detach */
	nodev,			/* reset */
	&sgen_cb_ops,		/* driver operations */
	(struct bus_ops *)0,	/* bus operations */
	NULL,			/* power */
	ddi_quiesce_not_supported,	/* devo_quiesce */
};

static void *sgen_soft_state = NULL;

static struct modldrv modldrv = {
	&mod_driverops, "SCSI generic driver", &sgen_dev_ops
};

static struct modlinkage modlinkage = {
	MODREV_1, &modldrv, NULL
};

int
_init(void)
{
	int err;

	/* establish driver name from module name */
	sgen_label = (char *)mod_modname(&modlinkage);

	sgen_log(NULL, SGEN_DIAG2, "in sgen_init()");
	if ((err = ddi_soft_state_init(&sgen_soft_state,
	    sizeof (sgen_state_t), SGEN_ESTIMATED_NUM_DEVS)) != 0) {
		goto done;
	}

	if ((err = mod_install(&modlinkage)) != 0) {
		ddi_soft_state_fini(&sgen_soft_state);
		goto done;
	}

done:
	sgen_log(NULL, SGEN_DIAG2, "%s sgen_init()", err ? "failed" : "done");
	return (err);
}

int
_fini(void)
{
	int err;
	sgen_log(NULL, SGEN_DIAG2, "in sgen_fini()");

	if ((err = mod_remove(&modlinkage)) != 0) {
		goto done;
	}

	ddi_soft_state_fini(&sgen_soft_state);
	sgen_cleanup_binddb();

done:
	sgen_log(NULL, SGEN_DIAG2, "%s sgen_fini()", err ? "failed" : "done");
	return (err);
}

int
_info(struct modinfo *modinfop)
{
	return (mod_info(&modlinkage, modinfop));
}

/*
 * sgen_typename()
 *	return a device type's name by looking it up in the sgen_devtypes table.
 */
static char *
sgen_typename(uchar_t typeno)
{
	if (typeno >= SGEN_NDEVTYPES)
		return ("type_unknown");
	return (sgen_devtypes[typeno]);
}

/*
 * sgen_typenum()
 *	return a device type's number by looking it up in the sgen_devtypes
 *	table.
 */
static int
sgen_typenum(const char *typename, uchar_t *typenum)
{
	int i;
	for (i = 0; i < SGEN_NDEVTYPES; i++) {
		if (strcasecmp(sgen_devtypes[i], typename) == 0) {
			*typenum = (uchar_t)i;
			return (0);
		}
	}
	return (-1);
}

/*
 * sgen_setup_binddb()
 *	initialize a data structure which stores all of the information about
 *	which devices and device types the driver should bind to.
 */
static void
sgen_setup_binddb(dev_info_t *dip)
{
	char **strs = NULL, *cp, *pcp, *vcp;
	uint_t nelems, pcplen, vcplen, idx;

	ASSERT(sgen_binddb.sdb_init == 0);
	ASSERT(MUTEX_HELD(&sgen_binddb.sdb_lock));

	if (ddi_prop_lookup_string_array(DDI_DEV_T_ANY, dip, DDI_PROP_DONTPASS,
	    "device-type-config-list", &strs, &nelems) == DDI_PROP_SUCCESS) {
		/*
		 * for each device type specifier make a copy and put it into a
		 * node in the binddb.
		 */
		for (idx = 0; idx < nelems; idx++) {
			sgen_type_node_t *nodep;
			uchar_t devtype;
			cp = strs[idx];
			if (sgen_typenum(cp, &devtype) != 0) {
				sgen_log(NULL, CE_WARN,
				    "unknown device type '%s', "
				    "device unit-address @%s",
				    cp, ddi_get_name_addr(dip));
				continue;
			}
			nodep = kmem_zalloc(sizeof (sgen_type_node_t),
			    KM_SLEEP);
			nodep->node_type = devtype;
			nodep->node_next = sgen_binddb.sdb_type_nodes;
			sgen_binddb.sdb_type_nodes = nodep;

			sgen_log(NULL, SGEN_DIAG2, "found device type "
			    "'%s' in device-type-config-list, "
			    "device unit-address @%s",
			    cp, ddi_get_name_addr(dip));
		}
		ddi_prop_free(strs);
	}

	/*
	 * for each Vendor/Product inquiry pair, build a node and put it
	 * into the the binddb.
	 */
	if (ddi_prop_lookup_string_array(DDI_DEV_T_ANY, dip, DDI_PROP_DONTPASS,
	    "inquiry-config-list", &strs, &nelems) == DDI_PROP_SUCCESS) {

		if (nelems % 2 == 1) {
			sgen_log(NULL, CE_WARN, "inquiry-config-list must "
			    "contain Vendor/Product pairs, "
			    "device unit-address @%s",
			    ddi_get_name_addr(dip));
			nelems--;
		}
		for (idx = 0; idx < nelems; idx += 2) {
			sgen_inq_node_t *nodep;
			/*
			 * Grab vendor and product ID.
			 */
			vcp = strs[idx];
			vcplen = strlen(vcp);
			if (vcplen == 0 || vcplen > SGEN_VENDID_MAX) {
				sgen_log(NULL, CE_WARN,
				    "Invalid vendor ID '%s', "
				    "device unit-address @%s",
				    vcp, ddi_get_name_addr(dip));
				continue;
			}

			pcp = strs[idx + 1];
			pcplen = strlen(pcp);
			if (pcplen == 0 || pcplen > SGEN_PRODID_MAX) {
				sgen_log(NULL, CE_WARN,
				    "Invalid product ID '%s', "
				    "device unit-address @%s",
				    pcp, ddi_get_name_addr(dip));
				continue;
			}

			nodep = kmem_zalloc(sizeof (sgen_inq_node_t),
			    KM_SLEEP);
			nodep->node_vendor = kmem_alloc(vcplen + 1, KM_SLEEP);
			(void) strcpy(nodep->node_vendor, vcp);
			nodep->node_product = kmem_alloc(pcplen + 1, KM_SLEEP);
			(void) strcpy(nodep->node_product, pcp);

			nodep->node_next = sgen_binddb.sdb_inq_nodes;
			sgen_binddb.sdb_inq_nodes = nodep;

			sgen_log(NULL, SGEN_DIAG2, "found inquiry string "
			    "'%s' '%s' in device-type-config-list, "
			    "device unit-address @%s",
			    nodep->node_vendor, nodep->node_product,
			    ddi_get_name_addr(dip));
		}
		ddi_prop_free(strs);
	}

	sgen_binddb.sdb_init = 1;
}

/*
 * sgen_cleanup_binddb()
 *	deallocate data structures for binding database.
 */
static void
sgen_cleanup_binddb()
{
	sgen_inq_node_t *inqp, *inqnextp;
	sgen_type_node_t *typep, *typenextp;

	mutex_enter(&sgen_binddb.sdb_lock);
	if (sgen_binddb.sdb_init == 0) {
		mutex_exit(&sgen_binddb.sdb_lock);
		return;
	}

	for (inqp = sgen_binddb.sdb_inq_nodes; inqp != NULL; inqp = inqnextp) {
		inqnextp = inqp->node_next;
		ASSERT(inqp->node_vendor && inqp->node_product);
		kmem_free(inqp->node_vendor,
		    strlen(inqp->node_vendor) + 1);
		kmem_free(inqp->node_product,
		    strlen(inqp->node_product) + 1);
		kmem_free(inqp, sizeof (sgen_inq_node_t));
	}

	for (typep = sgen_binddb.sdb_type_nodes; typep != NULL;
	    typep = typenextp) {
		typenextp = typep->node_next;
		kmem_free(typep, sizeof (sgen_type_node_t));
	}
	mutex_exit(&sgen_binddb.sdb_lock);
}

/*
 * sgen_bind_byinq()
 *	lookup a device in the binding database by its inquiry data.
 */
static int
sgen_bind_byinq(dev_info_t *dip)
{
	sgen_inq_node_t *nodep;
	char vend_str[SGEN_VENDID_MAX+1];
	char prod_str[SGEN_PRODID_MAX+1];
	struct scsi_device *scsidevp;

	scsidevp = ddi_get_driver_private(dip);

	/*
	 * inq_vid and inq_pid are laid out by the protocol in order in the
	 * inquiry structure, and are not delimited by \0.
	 */
	bcopy(scsidevp->sd_inq->inq_vid, vend_str, SGEN_VENDID_MAX);
	vend_str[SGEN_VENDID_MAX] = '\0';
	bcopy(scsidevp->sd_inq->inq_pid, prod_str, SGEN_PRODID_MAX);
	prod_str[SGEN_PRODID_MAX] = '\0';

	for (nodep = sgen_binddb.sdb_inq_nodes; nodep != NULL;
	    nodep = nodep->node_next) {
		/*
		 * Allow the "*" wildcard to match all vendor IDs.
		 */
		if (strcmp(nodep->node_vendor, "*") != 0) {
			if (strncasecmp(nodep->node_vendor, vend_str,
			    strlen(nodep->node_vendor)) != 0) {
				continue;
			}
		}

		/*
		 * Using strncasecmp() with the key length allows substring
		 * matching for product data.
		 */
		if (strncasecmp(nodep->node_product, prod_str,
		    strlen(nodep->node_product)) == 0) {
			return (0);
		}
	}
	return (-1);
}

/*
 * sgen_bind_bytype()
 *	lookup a device type in the binding database; if found, return a
 *	format string corresponding to the string in the .conf file.
 */
static int
sgen_bind_bytype(dev_info_t *dip)
{
	sgen_type_node_t *nodep;
	struct scsi_device *scsidevp;

	scsidevp = ddi_get_driver_private(dip);

	for (nodep = sgen_binddb.sdb_type_nodes; nodep != NULL;
	    nodep = nodep->node_next) {
		if (nodep->node_type == scsidevp->sd_inq->inq_dtype) {
			return (0);
		}
	}
	return (-1);
}

/*
 * sgen_get_binding()
 *	Check to see if the device in question matches the criteria for
 *	sgen to bind.
 *
 *	Either the .conf file must specify a device_type entry which
 *	matches the SCSI device type of this device, or the inquiry
 *	string provided by the device must match an inquiry string specified
 *	in the .conf file.  Inquiry data is matched first.
 */
static int
sgen_get_binding(dev_info_t *dip)
{
	int retval = 0;

	mutex_enter(&sgen_binddb.sdb_lock);
	if (sgen_binddb.sdb_init == 0)
		sgen_setup_binddb(dip);
	mutex_exit(&sgen_binddb.sdb_lock);


	/*
	 * Check device-type-config-list for a match by device type.
	 */
	if (sgen_bind_bytype(dip) == 0)
		goto done;

	/*
	 * Check inquiry-config-list for a match by Vendor/Product ID.
	 */
	if (sgen_bind_byinq(dip) == 0)
		goto done;

	retval = -1;
done:
	return (retval);
}

/*
 * sgen_attach()
 *	attach(9e) entrypoint.
 */
static int
sgen_attach(dev_info_t *dip, ddi_attach_cmd_t cmd)
{
	int err;

	sgen_log(NULL, SGEN_DIAG2, "in sgen_attach(), device unit-address @%s",
	    ddi_get_name_addr(dip));

	switch (cmd) {
	case DDI_ATTACH:
		err = sgen_do_attach(dip);
		break;
	case DDI_RESUME:
		err = DDI_SUCCESS;
		break;
	case DDI_PM_RESUME:
	default:
		err = DDI_FAILURE;
		break;
	}

	sgen_log(NULL, SGEN_DIAG2, "%s sgen_attach(), device unit-address @%s",
	    err == DDI_SUCCESS ? "done" : "failed", ddi_get_name_addr(dip));
	return (err);
}

/*
 * sgen_do_attach()
 *	handle the nitty details of attach.
 */
static int
sgen_do_attach(dev_info_t *dip)
{
	int instance;
	struct scsi_device *scsidevp;
	sgen_state_t *sg_state;
	uchar_t devtype;
	struct scsi_inquiry *inq;

	instance = ddi_get_instance(dip);

	scsidevp = ddi_get_driver_private(dip);
	ASSERT(scsidevp);

	sgen_log(NULL, SGEN_DIAG2, "sgen_do_attach: instance = %d, "
	    "device unit-address @%s", instance, ddi_get_name_addr(dip));

	/*
	 * Probe the device in order to get its device type to name the minor
	 * node.
	 */
	if (scsi_probe(scsidevp, NULL_FUNC) != SCSIPROBE_EXISTS) {
		scsi_unprobe(scsidevp);
		return (DDI_FAILURE);
	}

	if (ddi_soft_state_zalloc(sgen_soft_state, instance) != DDI_SUCCESS) {
		sgen_log(NULL, SGEN_DIAG1,
		    "sgen_do_attach: failed to allocate softstate, "
		    "device unit-address @%s", ddi_get_name_addr(dip));
		scsi_unprobe(scsidevp);
		return (DDI_FAILURE);
	}

	inq = scsidevp->sd_inq;		/* valid while device is probed... */
	devtype = inq->inq_dtype;

	sg_state = ddi_get_soft_state(sgen_soft_state, instance);
	sg_state->sgen_scsidev = scsidevp;
	scsidevp->sd_dev = dip;

	/*
	 * Now that sg_state->sgen_scsidev is initialized, it's ok to
	 * call sgen_log with sg_state instead of NULL.
	 */

	/*
	 * If the user specified the sgen_diag property, override the global
	 * sgen_diag setting by setting sg_state's sgen_diag value.  If the
	 * user gave a value out of range, default to '0'.
	 */
	sg_state->sgen_diag = ddi_getprop(DDI_DEV_T_ANY, dip, DDI_PROP_DONTPASS,
	    "sgen-diag", -1);

	if (sg_state->sgen_diag != -1) {
		if (sg_state->sgen_diag < 0 || sg_state->sgen_diag > 3)
			sg_state->sgen_diag = 0;
	}

	sgen_log(sg_state, SGEN_DIAG2,
	    "sgen_do_attach: sgen_soft_state=0x%p, instance=%d, "
	    "device unit-address @%s",
	    sgen_soft_state, instance, ddi_get_name_addr(dip));

	/*
	 * For simplicity, the minor number == the instance number
	 */
	if (ddi_create_minor_node(dip, sgen_typename(devtype), S_IFCHR,
	    instance, DDI_NT_SGEN, 0) == DDI_FAILURE) {
		scsi_unprobe(scsidevp);
		ddi_prop_remove_all(dip);
		sgen_log(sg_state, SGEN_DIAG1,
		    "sgen_do_attach: minor node creation failed, "
		    "device unit-address @%s", ddi_get_name_addr(dip));
		ddi_soft_state_free(sgen_soft_state, instance);
		return (DDI_FAILURE);
	}

	/*
	 * Allocate the command buffer, then create a condition variable for
	 * managing it; mark the command buffer as free.
	 */
	sg_state->sgen_cmdbuf = getrbuf(KM_SLEEP);
	cv_init(&sg_state->sgen_cmdbuf_cv, NULL, CV_DRIVER, NULL);

	SGEN_CLR_BUSY(sg_state);
	SGEN_CLR_OPEN(sg_state);
	SGEN_CLR_SUSP(sg_state);

	/*
	 * If the hba and the target both support wide xfers, enable them.
	 */
	if (scsi_ifgetcap(&sg_state->sgen_scsiaddr, "wide-xfer", 1) != -1) {
		int wide = 0;
		if ((inq->inq_rdf == RDF_SCSI2) &&
		    (inq->inq_wbus16 || inq->inq_wbus32))
			wide = 1;
		if (scsi_ifsetcap(&sg_state->sgen_scsiaddr, "wide-xfer",
		    wide, 1) == 1) {
			sgen_log(sg_state, SGEN_DIAG1,
			    "sgen_attach: wide xfer %s, "
			    "device unit-address @%s",
			    wide ? "enabled" : "disabled",
			    ddi_get_name_addr(dip));
		}
	}

	/*
	 * This is a little debugging code-- since the codepath for auto-sense
	 * and 'manual' sense is split, toggling this variable will make
	 * sgen act as though the adapter in question can't do auto-sense.
	 */
	if (sgen_force_manual_sense) {
		if (scsi_ifsetcap(&sg_state->sgen_scsiaddr, "auto-rqsense",
		    0, 1) == 1) {
			sg_state->sgen_arq_enabled = 0;
		} else {
			sg_state->sgen_arq_enabled = 1;
		}
	} else {
		/*
		 * Enable autorequest sense, if supported
		 */
		if (scsi_ifgetcap(&sg_state->sgen_scsiaddr,
		    "auto-rqsense", 1) != 1) {
			if (scsi_ifsetcap(&sg_state->sgen_scsiaddr,
			    "auto-rqsense", 1, 1) == 1) {
				sg_state->sgen_arq_enabled = 1;
				sgen_log(sg_state, SGEN_DIAG1,
				    "sgen_attach: auto-request-sense enabled, "
				    "device unit-address @%s",
				    ddi_get_name_addr(dip));
			} else {
				sg_state->sgen_arq_enabled = 0;
				sgen_log(sg_state, SGEN_DIAG1,
				    "sgen_attach: auto-request-sense disabled, "
				    "device unit-address @%s",
				    ddi_get_name_addr(dip));
			}
		} else {
			sg_state->sgen_arq_enabled = 1;	/* already enabled */
			sgen_log(sg_state, SGEN_DIAG1,
			    "sgen_attach: auto-request-sense enabled, "
			    "device unit-address @%s", ddi_get_name_addr(dip));
		}
	}

	/*
	 * Allocate plumbing for manually fetching sense.
	 */
	if (sgen_setup_sense(sg_state) != 0) {
		freerbuf(sg_state->sgen_cmdbuf);
		ddi_prop_remove_all(dip);
		ddi_remove_minor_node(dip, NULL);
		scsi_unprobe(scsidevp);
		sgen_log(sg_state, SGEN_DIAG1,
		    "sgen_do_attach: failed to setup request-sense, "
		    "device unit-address @%s", ddi_get_name_addr(dip));
		ddi_soft_state_free(sgen_soft_state, instance);
		return (DDI_FAILURE);
	}

	sgen_create_errstats(sg_state, instance);

	ddi_report_dev(dip);

	return (DDI_SUCCESS);
}

/*
 * sgen_setup_sense()
 *	Allocate a request sense packet so that if sgen needs to fetch sense
 *	data for the user, it will have a pkt ready to send.
 */
static int
sgen_setup_sense(sgen_state_t *sg_state)
{
	struct buf *bp;
	struct scsi_pkt *rqpkt;

	if ((bp = scsi_alloc_consistent_buf(&sg_state->sgen_scsiaddr, NULL,
	    MAX_SENSE_LENGTH, B_READ, SLEEP_FUNC, NULL)) == NULL) {
		return (-1);
	}

	if ((rqpkt = scsi_init_pkt(&sg_state->sgen_scsiaddr, NULL, bp,
	    CDB_GROUP0, 1, 0, PKT_CONSISTENT, SLEEP_FUNC, NULL)) == NULL) {
		scsi_free_consistent_buf(bp);
		return (-1);
	}

	/*
	 * Make the results of running a SENSE available by filling out the
	 * sd_sense field of the scsi device (sgen_sense is just an alias).
	 */
	sg_state->sgen_sense = (struct scsi_extended_sense *)bp->b_un.b_addr;

	(void) scsi_setup_cdb((union scsi_cdb *)rqpkt->pkt_cdbp,
	    SCMD_REQUEST_SENSE, 0, MAX_SENSE_LENGTH, 0);
	FILL_SCSI1_LUN(sg_state->sgen_scsidev, rqpkt);

	rqpkt->pkt_comp = sgen_callback;
	rqpkt->pkt_time = SGEN_IO_TIME;
	rqpkt->pkt_flags |= FLAG_SENSING;
	rqpkt->pkt_private = sg_state;

	sg_state->sgen_rqspkt = rqpkt;
	sg_state->sgen_rqsbuf = bp;

	return (0);
}

/*
 * sgen_create_errstats()
 *	create named kstats for tracking occurrence of errors.
 */
static void
sgen_create_errstats(sgen_state_t *sg_state, int instance)
{
	char kstatname[KSTAT_STRLEN];
	struct sgen_errstats *stp;

	(void) snprintf(kstatname, KSTAT_STRLEN, "%s%d,err",
	    sgen_label, instance);
	sg_state->sgen_kstats = kstat_create("sgenerr", instance,
	    kstatname, "device_error", KSTAT_TYPE_NAMED,
	    sizeof (struct sgen_errstats) / sizeof (kstat_named_t),
	    KSTAT_FLAG_PERSISTENT);

	if (sg_state->sgen_kstats == NULL)
		return;

	stp = (struct sgen_errstats *)sg_state->sgen_kstats->ks_data;
	kstat_named_init(&stp->sgen_trans_err, "transport_errors",
	    KSTAT_DATA_UINT32);
	kstat_named_init(&stp->sgen_restart, "command_restarts",
	    KSTAT_DATA_UINT32);
	kstat_named_init(&stp->sgen_incmp_err, "incomplete_commands",
	    KSTAT_DATA_UINT32);
	kstat_named_init(&stp->sgen_autosen_rcv, "autosense_occurred",
	    KSTAT_DATA_UINT32);
	kstat_named_init(&stp->sgen_autosen_bad, "autosense_undecipherable",
	    KSTAT_DATA_UINT32);
	kstat_named_init(&stp->sgen_sense_rcv, "sense_fetches",
	    KSTAT_DATA_UINT32);
	kstat_named_init(&stp->sgen_sense_bad, "sense_data_undecipherable",
	    KSTAT_DATA_UINT32);
	kstat_named_init(&stp->sgen_recov_err, "recoverable_error",
	    KSTAT_DATA_UINT32);
	kstat_named_init(&stp->sgen_nosen_err, "NO_SENSE_sense_key",
	    KSTAT_DATA_UINT32);
	kstat_named_init(&stp->sgen_unrecov_err, "unrecoverable_sense_error",
	    KSTAT_DATA_UINT32);
	sg_state->sgen_kstats->ks_private = sg_state;
	sg_state->sgen_kstats->ks_update = nulldev;
	kstat_install(sg_state->sgen_kstats);
}

/*
 * sgen_detach()
 *	detach(9E) entrypoint
 */
static int
sgen_detach(dev_info_t *dip, ddi_detach_cmd_t cmd)
{
	int instance;
	sgen_state_t *sg_state;

	instance = ddi_get_instance(dip);
	sg_state = ddi_get_soft_state(sgen_soft_state, instance);

	sgen_log(sg_state, SGEN_DIAG2, "in sgen_detach(), "
	    "device unit-address @%s", ddi_get_name_addr(dip));

	if (sg_state == NULL) {
		sgen_log(NULL, SGEN_DIAG1,
		    "sgen_detach: failed, no softstate found (%d), "
		    "device unit-address @%s",
		    instance, ddi_get_name_addr(dip));
		return (DDI_FAILURE);
	}

	switch (cmd) {
	case DDI_DETACH:
		return (sgen_do_detach(dip));
	case DDI_SUSPEND:
		return (sgen_do_suspend(dip));
	case DDI_PM_SUSPEND:
	default:
		return (DDI_FAILURE);
	}
}

/*
 * sgen_do_detach()
 *	detach the driver, tearing down resources.
 */
static int
sgen_do_detach(dev_info_t *dip)
{
	int instance;
	sgen_state_t *sg_state;
	struct scsi_device *devp;

	instance = ddi_get_instance(dip);
	sg_state = ddi_get_soft_state(sgen_soft_state, instance);
	ASSERT(sg_state);

	sgen_log(sg_state, SGEN_DIAG2, "in sgen_do_detach(), "
	    "device unit-address @%s", ddi_get_name_addr(dip));
	devp = ddi_get_driver_private(dip);

	mutex_enter(&sg_state->sgen_mutex);
	if (SGEN_IS_BUSY(sg_state)) {
		mutex_exit(&sg_state->sgen_mutex);
		sgen_log(sg_state, SGEN_DIAG1, "sgen_do_detach: failed because "
		    "device is busy, device unit-address @%s",
		    ddi_get_name_addr(dip));
		return (DDI_FAILURE);
	}
	mutex_exit(&sg_state->sgen_mutex);

	/*
	 * Final approach for detach.  Free data allocated by scsi_probe()
	 * in attach.
	 */
	if (sg_state->sgen_restart_timeid)
		(void) untimeout(sg_state->sgen_restart_timeid);
	sg_state->sgen_restart_timeid = 0;
	scsi_unprobe(devp);

	/*
	 * Free auto-request plumbing.
	 */
	scsi_free_consistent_buf(sg_state->sgen_rqsbuf);
	scsi_destroy_pkt(sg_state->sgen_rqspkt);

	if (sg_state->sgen_kstats) {
		kstat_delete(sg_state->sgen_kstats);
		sg_state->sgen_kstats = NULL;
	}

	/*
	 * Free command buffer and clean up
	 */
	freerbuf(sg_state->sgen_cmdbuf);
	cv_destroy(&sg_state->sgen_cmdbuf_cv);

	sgen_log(sg_state, SGEN_DIAG2, "done sgen_do_detach(), "
	    "device unit-address @%s", ddi_get_name_addr(dip));

	ddi_soft_state_free(sgen_soft_state, instance);
	ddi_prop_remove_all(dip);
	ddi_remove_minor_node(dip, NULL);
	return (DDI_SUCCESS);
}

/*
 * sgen_do_suspend()
 *	suspend the driver.  This sets the "suspend" bit for this target if it
 *	is currently open; once resumed, the suspend bit will cause
 *	subsequent I/Os to fail.  We want user programs to close and
 *	reopen the device to acknowledge that they need to reexamine its
 *	state and do the right thing.
 */
static int
sgen_do_suspend(dev_info_t *dip)
{
	int instance;
	sgen_state_t *sg_state;

	instance = ddi_get_instance(dip);
	sg_state = ddi_get_soft_state(sgen_soft_state, instance);
	ASSERT(sg_state);

	sgen_log(sg_state, SGEN_DIAG2, "in sgen_do_suspend(), "
	    "device unit-address @%s", ddi_get_name_addr(dip));

	if (sg_state->sgen_restart_timeid) {
		(void) untimeout(sg_state->sgen_restart_timeid);
	}
	sg_state->sgen_restart_timeid = 0;

	mutex_enter(&sg_state->sgen_mutex);
	if (SGEN_IS_OPEN(sg_state))
		SGEN_SET_SUSP(sg_state);
	mutex_exit(&sg_state->sgen_mutex);

	sgen_log(sg_state, SGEN_DIAG2, "done sgen_do_suspend(), "
	    "device unit-address @%s", ddi_get_name_addr(dip));
	return (DDI_SUCCESS);
}

/*
 * sgen_getinfo()
 *	getinfo(9e) entrypoint.
 */
/*ARGSUSED*/
static int
sgen_getinfo(dev_info_t *dip, ddi_info_cmd_t infocmd, void *arg, void **result)
{
	dev_t dev;
	sgen_state_t *sg_state;
	int instance, error;
	switch (infocmd) {
	case DDI_INFO_DEVT2DEVINFO:
		dev = (dev_t)arg;
		instance = getminor(dev);
		if ((sg_state = ddi_get_soft_state(sgen_soft_state, instance))
		    == NULL)
			return (DDI_FAILURE);
		*result = (void *) sg_state->sgen_scsidev->sd_dev;
		error = DDI_SUCCESS;
		break;
	case DDI_INFO_DEVT2INSTANCE:
		dev = (dev_t)arg;
		instance = getminor(dev);
		*result = (void *)(uintptr_t)instance;
		error = DDI_SUCCESS;
		break;
	default:
		error = DDI_FAILURE;
	}
	return (error);
}

/*
 * sgen_probe()
 *	probe(9e) entrypoint.  sgen *never* returns DDI_PROBE_PARTIAL, in
 *	order to avoid leaving around extra devinfos.  If sgen's binding
 *	rules indicate that it should bind, it returns DDI_PROBE_SUCCESS.
 */
static int
sgen_probe(dev_info_t *dip)
{
	struct scsi_device *scsidevp;
	int instance;
	int rval;

	scsidevp = ddi_get_driver_private(dip);
	instance = ddi_get_instance(dip);
	sgen_log(NULL, SGEN_DIAG2, "in sgen_probe(): instance = %d, "
	    "device unit-address @%s", instance, ddi_get_name_addr(dip));

	if (ddi_dev_is_sid(dip) == DDI_SUCCESS)
		return (DDI_PROBE_DONTCARE);

	if (ddi_get_soft_state(sgen_soft_state, instance) != NULL)
		return (DDI_PROBE_FAILURE);

	mutex_enter(&sgen_binddb.sdb_lock);
	if (sgen_binddb.sdb_init == 0) {
		sgen_setup_binddb(dip);
	}
	mutex_exit(&sgen_binddb.sdb_lock);

	/*
	 * A small optimization: if it's impossible for sgen to bind to
	 * any devices, don't bother probing, just fail.
	 */
	if ((sgen_binddb.sdb_inq_nodes == NULL) &&
	    (sgen_binddb.sdb_type_nodes == NULL)) {
		return (DDI_PROBE_FAILURE);
	}

	if (scsi_probe(scsidevp, NULL_FUNC) == SCSIPROBE_EXISTS) {
		if (sgen_get_binding(dip) == 0) {
			rval = DDI_PROBE_SUCCESS;
		}
	} else {
		rval = DDI_PROBE_FAILURE;
	}
	scsi_unprobe(scsidevp);

	sgen_log(NULL, SGEN_DIAG2, "sgen_probe() %s, device unit-address @%s",
	    rval == DDI_PROBE_SUCCESS ? "succeeded" : "failed",
	    ddi_get_name_addr(dip));
	return (rval);
}

/*
 * sgen_open()
 *	open(9e) entrypoint.  sgen enforces a strict exclusive open policy per
 *	target.
 */
/*ARGSUSED1*/
static int
sgen_open(dev_t *dev_p, int flag, int otyp, cred_t *cred_p)
{
	dev_t dev = *dev_p;
	sgen_state_t *sg_state;
	int instance;

	instance = getminor(dev);

	if ((sg_state = ddi_get_soft_state(sgen_soft_state, instance)) == NULL)
		return (ENXIO);

	sgen_log(sg_state, SGEN_DIAG2, "in sgen_open(): instance = %d",
	    instance);

	mutex_enter(&sg_state->sgen_mutex);

	/*
	 * Don't allow new opens of a suspended device until the last close has
	 * happened.  This is rather simplistic, but keeps the implementation
	 * straightforward.
	 */
	if (SGEN_IS_SUSP(sg_state)) {
		mutex_exit(&sg_state->sgen_mutex);
		return (EIO);
	}

	/*
	 * Enforce exclusive access.
	 */
	if (SGEN_IS_EXCL(sg_state) ||
	    (SGEN_IS_OPEN(sg_state) && (flag & FEXCL))) {
		mutex_exit(&sg_state->sgen_mutex);
		return (EBUSY);
	}

	if (flag & FEXCL)
		SGEN_SET_EXCL(sg_state);

	SGEN_SET_OPEN(sg_state);

	mutex_exit(&sg_state->sgen_mutex);

	return (0);
}

/*
 * sgen_close()
 *	close(9e) entrypoint.
 */
/*ARGSUSED1*/
static int
sgen_close(dev_t dev, int flag, int otyp, cred_t *cred_p)
{
	sgen_state_t *sg_state;
	int instance;

	instance = getminor(dev);

	if ((sg_state = ddi_get_soft_state(sgen_soft_state, instance)) == NULL)
		return (ENXIO);

	sgen_log(sg_state, SGEN_DIAG2, "in sgen_close(): instance = %d",
	    instance);

	mutex_enter(&sg_state->sgen_mutex);
	SGEN_CLR_OPEN(sg_state);
	SGEN_CLR_EXCL(sg_state);
	SGEN_CLR_SUSP(sg_state); /* closing clears the 'I was suspended' bit */
	mutex_exit(&sg_state->sgen_mutex);

	sgen_log(sg_state, SGEN_DIAG2, "done sgen_close()");

	return (0);
}

/*
 * sgen_ioctl()
 *	sgen supports the uscsi(4I) ioctl interface.
 */
/*ARGSUSED4*/
static int
sgen_ioctl(dev_t dev,
    int cmd, intptr_t arg, int flag, cred_t *cred_p, int *rval_p)
{
	int retval = 0;
	sgen_state_t *sg_state;
	int instance;

	instance = getminor(dev);

	if ((sg_state = ddi_get_soft_state(sgen_soft_state, instance)) == NULL)
		return (ENXIO);

	sgen_log(sg_state, SGEN_DIAG2, "in sgen_ioctl(): instance = %d",
	    instance);

	/*
	 * If the driver has been suspended since the last open, fail all
	 * subsequent IO's so that the userland consumer reinitializes state.
	 */
	mutex_enter(&sg_state->sgen_mutex);
	if (SGEN_IS_SUSP(sg_state)) {
		mutex_exit(&sg_state->sgen_mutex);
		sgen_log(sg_state, SGEN_DIAG1, "sgen_ioctl: returning EIO: "
		    "driver instance %d was previously suspended", instance);
		return (EIO);
	}
	mutex_exit(&sg_state->sgen_mutex);

	switch (cmd) {
	case SGEN_IOC_DIAG: {
		if (arg > 3) {
			arg = 0;
		}
		sg_state->sgen_diag = (int)arg;
		retval = 0;
		break;
	}

	case SGEN_IOC_READY: {
		if (sgen_tur(dev) != 0) {
			retval = EIO;
		} else {
			retval = 0;
		}
		break;
	}

	case USCSICMD:
		retval = sgen_uscsi_cmd(dev, (struct uscsi_cmd *)arg, flag);
		break;

	default:
		retval = ENOTTY;
	}

	sgen_log(sg_state, SGEN_DIAG2, "done sgen_ioctl(), returning %d",
	    retval);

	return (retval);
}

/*
 * sgen_uscsi_cmd()
 *	Setup, configuration and teardown for a uscsi(4I) command
 */
/*ARGSUSED*/
static int
sgen_uscsi_cmd(dev_t dev, struct uscsi_cmd *ucmd, int flag)
{
	struct uscsi_cmd	*uscmd;
	struct buf	*bp;
	sgen_state_t	*sg_state;
	enum uio_seg	uioseg;
	int	instance;
	int	flags;
	int	err;

	instance = getminor(dev);

	sg_state = ddi_get_soft_state(sgen_soft_state, instance);
	ASSERT(sg_state);

	sgen_log(sg_state, SGEN_DIAG2, "in sgen_uscsi_cmd(): instance = %d",
	    instance);

	/*
	 * At this point, we start affecting state relevant to the target,
	 * so access needs to be serialized.
	 */
	if (sgen_hold_cmdbuf(sg_state) != 0) {
		sgen_log(sg_state, SGEN_DIAG1, "sgen_uscsi_cmd: interrupted");
		return (EINTR);
	}

	err = scsi_uscsi_alloc_and_copyin((intptr_t)ucmd, flag,
	    &sg_state->sgen_scsiaddr, &uscmd);
	if (err != 0) {
		sgen_rele_cmdbuf(sg_state);
		sgen_log(sg_state, SGEN_DIAG1, "sgen_uscsi_cmd: "
		    "scsi_uscsi_alloc_and_copyin failed\n");
		return (err);
	}

	/*
	 * Clear out undesirable command flags
	 */
	flags = (uscmd->uscsi_flags & ~(USCSI_NOINTR | USCSI_NOPARITY |
	    USCSI_OTAG | USCSI_HTAG | USCSI_HEAD));
	if (flags != uscmd->uscsi_flags) {
		sgen_log(sg_state, SGEN_DIAG1, "sgen_uscsi_cmd: cleared "
		    "unsafe uscsi_flags 0x%x", uscmd->uscsi_flags & ~flags);
		uscmd->uscsi_flags = flags;
	}

	if (uscmd->uscsi_cdb != NULL) {
		sgen_dump_cdb(sg_state, "sgen_uscsi_cmd: ",
		    (union scsi_cdb *)uscmd->uscsi_cdb, uscmd->uscsi_cdblen);
	}

	/*
	 * Stash the sense buffer into sgen_rqs_sen for convenience.
	 */
	sg_state->sgen_rqs_sen = uscmd->uscsi_rqbuf;

	bp = sg_state->sgen_cmdbuf;
	bp->av_back = NULL;
	bp->av_forw = NULL;
	bp->b_private = (struct buf *)uscmd;
	uioseg = (flag & FKIOCTL) ? UIO_SYSSPACE : UIO_USERSPACE;

	err = scsi_uscsi_handle_cmd(dev, uioseg, uscmd, sgen_start, bp, NULL);

	if (sg_state->sgen_cmdpkt != NULL) {
		uscmd->uscsi_status = SCBP_C(sg_state->sgen_cmdpkt);
	} else {
		uscmd->uscsi_status = 0;
	}

	sgen_log(sg_state, SGEN_DIAG3, "sgen_uscsi_cmd: awake from waiting "
	    "for command.  Status is 0x%x", uscmd->uscsi_status);

	if (uscmd->uscsi_rqbuf != NULL) {
		int rqlen = uscmd->uscsi_rqlen - uscmd->uscsi_rqresid;
		sgen_dump_sense(sg_state, rqlen,
		    (uchar_t *)uscmd->uscsi_rqbuf);
	}

	(void) scsi_uscsi_copyout_and_free((intptr_t)ucmd, uscmd);

	if (sg_state->sgen_cmdpkt != NULL) {
		scsi_destroy_pkt(sg_state->sgen_cmdpkt);
		sg_state->sgen_cmdpkt = NULL;
	}

	/*
	 * After this point, we can't touch per-target state.
	 */
	sgen_rele_cmdbuf(sg_state);

	sgen_log(sg_state, SGEN_DIAG2, "done sgen_uscsi_cmd()");

	return (err);
}

/*
 * sgen_hold_cmdbuf()
 *	Acquire a lock on the command buffer for the given target.  Returns
 *	non-zero if interrupted.
 */
static int
sgen_hold_cmdbuf(sgen_state_t *sg_state)
{
	mutex_enter(&sg_state->sgen_mutex);
	while (SGEN_IS_BUSY(sg_state)) {
		if (!cv_wait_sig(&sg_state->sgen_cmdbuf_cv,
		    &sg_state->sgen_mutex)) {
			mutex_exit(&sg_state->sgen_mutex);
			return (-1);
		}
	}
	SGEN_SET_BUSY(sg_state);
	mutex_exit(&sg_state->sgen_mutex);
	return (0);
}

/*
 * sgen_rele_cmdbuf()
 *	release the command buffer for a particular target.
 */
static void
sgen_rele_cmdbuf(sgen_state_t *sg_state)
{
	mutex_enter(&sg_state->sgen_mutex);
	SGEN_CLR_BUSY(sg_state);
	cv_signal(&sg_state->sgen_cmdbuf_cv);
	mutex_exit(&sg_state->sgen_mutex);
}

/*
 * sgen_start()
 *	Transport a uscsi command; this is invoked by physio() or directly
 *	by sgen_uscsi_cmd().
 */
static int
sgen_start(struct buf *bp)
{
	sgen_state_t *sg_state;
	dev_t dev = bp->b_edev;
	int trans_err;

	if ((sg_state = ddi_get_soft_state(sgen_soft_state,
	    getminor(dev))) == NULL) {
		bp->b_resid = bp->b_bcount;
		bioerror(bp, ENXIO);
		biodone(bp);
		return (ENXIO);
	}

	/*
	 * Sanity checks - command should not be complete, no packet should
	 * be allocated, and there ought to be a uscsi cmd in b_private
	 */
	ASSERT(bp == sg_state->sgen_cmdbuf && sg_state->sgen_cmdpkt == NULL);
	ASSERT((bp->b_flags & B_DONE) == 0);
	ASSERT(bp->b_private);
	if (sgen_make_uscsi_cmd(sg_state, bp) != 0) {
		bp->b_resid = bp->b_bcount;
		bioerror(bp, EFAULT);
		biodone(bp);
		return (EFAULT);
	}

	ASSERT(sg_state->sgen_cmdpkt != NULL);

	/*
	 * Clear out the residual and error fields
	 */
	bp->b_resid = 0;
	bp->b_error = 0;

	trans_err = sgen_scsi_transport(sg_state->sgen_cmdpkt);
	switch (trans_err) {
	case TRAN_ACCEPT:
		break;
	case TRAN_BUSY:
		sgen_log(sg_state, SGEN_DIAG2,
		    "sgen_start: scsi_transport() returned TRAN_BUSY");
		sg_state->sgen_restart_timeid = timeout(sgen_restart, sg_state,
		    SGEN_BSY_TIMEOUT);
		break;
	default:
		/*
		 * Indicate there has been an I/O transfer error.
		 * Be done with the command.
		 */
		mutex_enter(&sg_state->sgen_mutex);
		SGEN_DO_ERRSTATS(sg_state, sgen_trans_err);
		mutex_exit(&sg_state->sgen_mutex);
		sgen_log(sg_state, SGEN_DIAG2, "sgen_start: scsi_transport() "
		    "returned %d", trans_err);
		bioerror(bp, EIO);
		biodone(bp);
		return (EIO);
	}
	sgen_log(sg_state, SGEN_DIAG2, "sgen_start: b_flags 0x%x", bp->b_flags);
	return (0);
}

/*
 * sgen_scsi_transport()
 *	a simple scsi_transport() wrapper which can be configured to inject
 *	sporadic errors for testing.
 */
static int
sgen_scsi_transport(struct scsi_pkt *pkt)
{
	int trans_err;
	static int cnt = 0;
	sgen_state_t *sg_state = pkt->pkt_private;

	if (sgen_sporadic_failures == 0) {
		return (scsi_transport(pkt));
	}

	cnt = (cnt * 2416 + 374441) % 1771875;	/* borrowed from kmem.c */
	if (cnt % 40 == 1) {
		sgen_log(sg_state, SGEN_DIAG1, "sgen_scsi_transport: "
		    "injecting sporadic BUSY");
		trans_err = TRAN_BUSY;
	} else if (cnt % 40 == 2) {
		sgen_log(sg_state, SGEN_DIAG1, "sgen_scsi_transport: "
		    "injecting sporadic BADPKT");
		trans_err = TRAN_BADPKT;
	} else {
		/*
		 * Most of the time we take the normal path
		 */
		trans_err = scsi_transport(pkt);
	}
	return (trans_err);
}

/*
 * sgen_make_uscsi_cmd()
 *	Initialize a SCSI packet usable for USCSI.
 */
static int
sgen_make_uscsi_cmd(sgen_state_t *sg_state, struct buf *bp)
{
	struct scsi_pkt	*pkt;
	struct uscsi_cmd *ucmd;
	int stat_size = 1;
	int flags = 0;

	ASSERT(bp);

	sgen_log(sg_state, SGEN_DIAG2, "in sgen_make_uscsi_cmd()");

	ucmd = (struct uscsi_cmd *)bp->b_private;

	if (ucmd->uscsi_flags & USCSI_RQENABLE) {
		if (ucmd->uscsi_rqlen > SENSE_LENGTH) {
			stat_size = (int)(ucmd->uscsi_rqlen) +
			    sizeof (struct scsi_arq_status) -
			    sizeof (struct scsi_extended_sense);
			flags = PKT_XARQ;
		} else {
			stat_size = sizeof (struct scsi_arq_status);
		}
	}

	sgen_log(sg_state, SGEN_DIAG3, "sgen_make_uscsi_cmd: b_bcount = %ld",
	    bp->b_bcount);
	pkt = scsi_init_pkt(&sg_state->sgen_scsiaddr,
	    NULL,			/* in_pkt - null so it'll be alloc'd */
	    bp->b_bcount ? bp : NULL,	/* buf structure for data xfer */
	    ucmd->uscsi_cdblen,		/* cmdlen */
	    stat_size,			/* statuslen */
	    0,				/* privatelen */
	    flags,			/* flags */
	    SLEEP_FUNC,			/* callback */
	    (caddr_t)sg_state);		/* callback_arg */

	if (pkt == NULL) {
		sgen_log(sg_state, SGEN_DIAG2, "failed sgen_make_uscsi_cmd()");
		return (-1);
	}

	pkt->pkt_comp = sgen_callback;
	pkt->pkt_private = sg_state;
	sg_state->sgen_cmdpkt = pkt;

	/*
	 * We *don't* call scsi_setup_cdb here, as is customary, since the
	 * user could specify a command from one group, but pass cdblen
	 * as something totally different.  If cdblen is smaller than expected,
	 * this results in scsi_setup_cdb writing past the end of the cdb.
	 */
	bcopy(ucmd->uscsi_cdb, pkt->pkt_cdbp, ucmd->uscsi_cdblen);
	if (ucmd->uscsi_cdblen >= CDB_GROUP0) {
		FILL_SCSI1_LUN(sg_state->sgen_scsidev, pkt);
	}

	if (ucmd->uscsi_timeout > 0)
		pkt->pkt_time = ucmd->uscsi_timeout;
	else
		pkt->pkt_time = SGEN_IO_TIME;

	/*
	 * Set packet options
	 */
	if (ucmd->uscsi_flags & USCSI_SILENT)
		pkt->pkt_flags |= FLAG_SILENT;
	if (ucmd->uscsi_flags & USCSI_ISOLATE)
		pkt->pkt_flags |= FLAG_ISOLATE;
	if (ucmd->uscsi_flags & USCSI_DIAGNOSE)
		pkt->pkt_flags |= FLAG_DIAGNOSE;
	if (ucmd->uscsi_flags & USCSI_RENEGOT) {
		pkt->pkt_flags |= FLAG_RENEGOTIATE_WIDE_SYNC;
	}

	/* Transfer uscsi information to scsi_pkt */
	(void) scsi_uscsi_pktinit(ucmd, pkt);

	sgen_log(sg_state, SGEN_DIAG2, "done sgen_make_uscsi_cmd()");
	return (0);
}


/*
 * sgen_restart()
 *	sgen_restart() is called after a timeout, when a command has been
 *	postponed due to a TRAN_BUSY response from the HBA.
 */
static void
sgen_restart(void *arg)
{
	sgen_state_t *sg_state = (sgen_state_t *)arg;
	struct scsi_pkt *pkt;
	struct buf *bp;

	sgen_log(sg_state, SGEN_DIAG2, "in sgen_restart()");

	bp = sg_state->sgen_cmdbuf;
	pkt = sg_state->sgen_cmdpkt;
	ASSERT(bp && pkt);

	SGEN_DO_ERRSTATS(sg_state, sgen_restart);

	/*
	 * If the packet is marked with the sensing flag, sgen is off running
	 * a request sense, and *that packet* is what needs to be restarted.
	 */
	if (pkt->pkt_flags & FLAG_SENSING) {
		sgen_log(sg_state, SGEN_DIAG3,
		    "sgen_restart: restarting REQUEST SENSE");
		pkt = sg_state->sgen_rqspkt;
	}

	if (sgen_scsi_transport(pkt) != TRAN_ACCEPT) {
		bp->b_resid = bp->b_bcount;
		bioerror(bp, EIO);
		biodone(bp);
	}
}

/*
 * sgen_callback()
 *	Command completion processing
 *
 *	sgen's completion processing is very pessimistic-- it does not retry
 *	failed commands; instead, it allows the user application to make
 *	decisions about what has gone wrong.
 */
static void
sgen_callback(struct scsi_pkt *pkt)
{
	sgen_state_t *sg_state;
	struct uscsi_cmd *ucmd;
	struct buf *bp;
	int action;

	sg_state = pkt->pkt_private;
	/*
	 * bp should always be the command buffer regardless of whether
	 * this is a command completion or a request-sense completion.
	 * This is because there is no need to biodone() the sense buf
	 * when it completes-- we want to biodone() the actual command buffer!
	 */
	bp = sg_state->sgen_cmdbuf;
	if (pkt->pkt_flags & FLAG_SENSING) {
		ASSERT(pkt == sg_state->sgen_rqspkt);
		sgen_log(sg_state, SGEN_DIAG2,
		    "in sgen_callback() (SENSE completion callback)");
	} else {
		ASSERT(pkt == sg_state->sgen_cmdpkt);
		sgen_log(sg_state, SGEN_DIAG2,
		    "in sgen_callback() (command completion callback)");
	}
	ucmd = (struct uscsi_cmd *)bp->b_private;

	sgen_log(sg_state, SGEN_DIAG3, "sgen_callback: reason=0x%x resid=%ld "
	    "state=0x%x", pkt->pkt_reason, pkt->pkt_resid, pkt->pkt_state);

	/* Transfer scsi_pkt information to uscsi */
	(void) scsi_uscsi_pktfini(pkt, ucmd);

	if (pkt->pkt_reason != CMD_CMPLT) {
		/*
		 * The command did not complete.
		 */
		sgen_log(sg_state, SGEN_DIAG3,
		    "sgen_callback: command did not complete");
		action = sgen_handle_incomplete(sg_state, pkt);
	} else if (sg_state->sgen_arq_enabled &&
	    (pkt->pkt_state & STATE_ARQ_DONE)) {
		/*
		 * The auto-rqsense happened, and the packet has a filled-in
		 * scsi_arq_status structure, pointed to by pkt_scbp.
		 */
		sgen_log(sg_state, SGEN_DIAG3,
		    "sgen_callback: received auto-requested sense");
		action = sgen_handle_autosense(sg_state, pkt);
		ASSERT(action != FETCH_SENSE);
	} else if (pkt->pkt_flags & FLAG_SENSING) {
		/*
		 * sgen was running a REQUEST SENSE. Decode the sense data and
		 * decide what to do next.
		 *
		 * Clear FLAG_SENSING on the original packet for completeness.
		 */
		sgen_log(sg_state, SGEN_DIAG3, "sgen_callback: received sense");
		sg_state->sgen_cmdpkt->pkt_flags &= ~FLAG_SENSING;
		action = sgen_handle_sense(sg_state);
		ASSERT(action != FETCH_SENSE);
	} else {
		/*
		 * Command completed and we're not getting sense. Check for
		 * errors and decide what to do next.
		 */
		sgen_log(sg_state, SGEN_DIAG3,
		    "sgen_callback: command appears complete");
		action = sgen_check_error(sg_state, bp);
	}

	switch (action) {
	case FETCH_SENSE:
		/*
		 * If there is sense to fetch, break out to prevent biodone'ing
		 * until the sense fetch is complete.
		 */
		if (sgen_initiate_sense(sg_state,
		    scsi_pkt_allocated_correctly(pkt) ?
		    pkt->pkt_path_instance : 0) == 0)
			break;
		/*FALLTHROUGH*/
	case COMMAND_DONE_ERROR:
		bp->b_resid = bp->b_bcount;
		bioerror(bp, EIO);
		/*FALLTHROUGH*/
	case COMMAND_DONE:
		biodone(bp);
		break;
	default:
		ASSERT(0);
		break;
	}

	sgen_log(sg_state, SGEN_DIAG2, "done sgen_callback()");
}

/*
 * sgen_initiate_sense()
 *	Send the sgen_rqspkt to the target, thereby requesting sense data.
 */
static int
sgen_initiate_sense(sgen_state_t *sg_state, int path_instance)
{
	/* use same path_instance as command */
	if (scsi_pkt_allocated_correctly(sg_state->sgen_rqspkt))
		sg_state->sgen_rqspkt->pkt_path_instance = path_instance;

	switch (sgen_scsi_transport(sg_state->sgen_rqspkt)) {
	case TRAN_ACCEPT:
		sgen_log(sg_state, SGEN_DIAG3, "sgen_initiate_sense: "
		    "sense fetch transport accepted.");
		return (0);
	case TRAN_BUSY:
		sgen_log(sg_state, SGEN_DIAG2, "sgen_initiate_sense: "
		    "sense fetch transport busy, setting timeout.");
		sg_state->sgen_restart_timeid = timeout(sgen_restart, sg_state,
		    SGEN_BSY_TIMEOUT);
		return (0);
	default:
		sgen_log(sg_state, SGEN_DIAG2, "sgen_initiate_sense: "
		    "sense fetch transport failed or busy.");
		return (-1);
	}
}

/*
 * sgen_handle_incomplete()
 *	sgen is pessimistic, but also careful-- it doesn't try to retry
 *	incomplete commands, but it also doesn't go resetting devices;
 *	it is hard to tell if the device will be tolerant of that sort
 *	of prodding.
 *
 *	This routine has been left as a guide for the future--- the
 *	current administration's hands-off policy may need modification.
 */
/*ARGSUSED*/
static int
sgen_handle_incomplete(sgen_state_t *sg_state, struct scsi_pkt *pkt)
{
	SGEN_DO_ERRSTATS(sg_state, sgen_incmp_err);
	return (COMMAND_DONE_ERROR);
}

/*
 * sgen_handle_autosense()
 *	Deal with SENSE data acquired automatically via the auto-request-sense
 *	facility.
 *
 *	Sgen takes a pessimistic view of things-- it doesn't retry commands,
 *	and unless the device recovered from the problem, this routine returns
 *	COMMAND_DONE_ERROR.
 */
static int
sgen_handle_autosense(sgen_state_t *sg_state, struct scsi_pkt *pkt)
{
	struct scsi_arq_status *arqstat;
	struct uscsi_cmd *ucmd =
	    (struct uscsi_cmd *)sg_state->sgen_cmdbuf->b_private;
	int amt;

	arqstat = (struct scsi_arq_status *)(pkt->pkt_scbp);

	SGEN_DO_ERRSTATS(sg_state, sgen_autosen_rcv);

	if (arqstat->sts_rqpkt_reason != CMD_CMPLT) {
		sgen_log(sg_state, SGEN_DIAG1, "sgen_handle_autosense: ARQ"
		    "failed to complete.");
		SGEN_DO_ERRSTATS(sg_state, sgen_autosen_bad);
		return (COMMAND_DONE_ERROR);
	}

	if (pkt->pkt_state & STATE_XARQ_DONE) {
		amt = MAX_SENSE_LENGTH - arqstat->sts_rqpkt_resid;
	} else {
		if (arqstat->sts_rqpkt_resid > SENSE_LENGTH) {
			amt = MAX_SENSE_LENGTH - arqstat->sts_rqpkt_resid;
		} else {
			amt = SENSE_LENGTH - arqstat->sts_rqpkt_resid;
		}
	}

	if (ucmd->uscsi_flags & USCSI_RQENABLE) {
		ucmd->uscsi_rqstatus = *((char *)&arqstat->sts_rqpkt_status);
		uchar_t rqlen = min((uchar_t)amt, ucmd->uscsi_rqlen);
		ucmd->uscsi_rqresid = ucmd->uscsi_rqlen - rqlen;
		ASSERT(ucmd->uscsi_rqlen && sg_state->sgen_rqs_sen);
		bcopy(&(arqstat->sts_sensedata), sg_state->sgen_rqs_sen, rqlen);
		sgen_log(sg_state, SGEN_DIAG2, "sgen_handle_autosense: "
		    "uscsi_rqstatus=0x%x uscsi_rqresid=%d\n",
		    ucmd->uscsi_rqstatus, ucmd->uscsi_rqresid);
	}

	if (arqstat->sts_rqpkt_status.sts_chk) {
		sgen_log(sg_state, SGEN_DIAG1, "sgen_handle_autosense: got "
		    "check condition on auto request sense!");
		SGEN_DO_ERRSTATS(sg_state, sgen_autosen_bad);
		return (COMMAND_DONE_ERROR);
	}

	if (((arqstat->sts_rqpkt_state & STATE_XFERRED_DATA) == 0) ||
	    (amt == 0)) {
		sgen_log(sg_state, SGEN_DIAG1, "sgen_handle_autosense: got "
		    "auto-sense, but it contains no data!");
		SGEN_DO_ERRSTATS(sg_state, sgen_autosen_bad);
		return (COMMAND_DONE_ERROR);
	}

	/*
	 * Stuff the sense data pointer into sgen_sense for later retrieval
	 */
	sg_state->sgen_sense = &arqstat->sts_sensedata;

	/*
	 * Now, check to see whether we got enough sense data to make any
	 * sense out if it (heh-heh).
	 */
	if (amt < SUN_MIN_SENSE_LENGTH) {
		sgen_log(sg_state, SGEN_DIAG1, "sgen_handle_autosense: not "
		    "enough auto sense data");
		return (COMMAND_DONE_ERROR);
	}

	switch (arqstat->sts_sensedata.es_key) {
	case KEY_RECOVERABLE_ERROR:
		SGEN_DO_ERRSTATS(sg_state, sgen_recov_err);
		break;
	case KEY_NO_SENSE:
		SGEN_DO_ERRSTATS(sg_state, sgen_nosen_err);
		break;
	default:
		SGEN_DO_ERRSTATS(sg_state, sgen_unrecov_err);
		break;
	}

	return (COMMAND_DONE);
}

/*
 * sgen_handle_sense()
 *	Examine sense data that was manually fetched from the target.
 */
static int
sgen_handle_sense(sgen_state_t *sg_state)
{
	struct scsi_pkt *rqpkt = sg_state->sgen_rqspkt;
	struct scsi_status *rqstatus = (struct scsi_status *)rqpkt->pkt_scbp;
	struct uscsi_cmd *ucmd =
	    (struct uscsi_cmd *)sg_state->sgen_cmdbuf->b_private;
	int amt;

	SGEN_DO_ERRSTATS(sg_state, sgen_sense_rcv);

	amt = MAX_SENSE_LENGTH - rqpkt->pkt_resid;

	if (ucmd->uscsi_flags & USCSI_RQENABLE) {
		ucmd->uscsi_rqstatus = *((char *)rqstatus);
		uchar_t rqlen = min((uchar_t)amt, ucmd->uscsi_rqlen);
		ucmd->uscsi_rqresid = ucmd->uscsi_rqlen - rqlen;
		ASSERT(ucmd->uscsi_rqlen && sg_state->sgen_rqs_sen);
		bcopy(sg_state->sgen_sense, sg_state->sgen_rqs_sen, rqlen);
		sgen_log(sg_state, SGEN_DIAG2, "sgen_handle_sense: "
		    "uscsi_rqstatus=0x%x uscsi_rqresid=%d\n",
		    ucmd->uscsi_rqstatus, ucmd->uscsi_rqresid);
	}

	if (rqstatus->sts_busy) {
		sgen_log(sg_state, SGEN_DIAG1, "sgen_handle_sense: got busy "
		    "on request sense");
		SGEN_DO_ERRSTATS(sg_state, sgen_sense_bad);
		return (COMMAND_DONE_ERROR);
	}

	if (rqstatus->sts_chk) {
		sgen_log(sg_state, SGEN_DIAG1, "sgen_handle_sense: got check "
		    "condition on request sense!");
		SGEN_DO_ERRSTATS(sg_state, sgen_sense_bad);
		return (COMMAND_DONE_ERROR);
	}

	if ((rqpkt->pkt_state & STATE_XFERRED_DATA) == 0 || amt == 0) {
		sgen_log(sg_state, SGEN_DIAG1, "sgen_handle_sense: got "
		    "sense, but it contains no data");
		SGEN_DO_ERRSTATS(sg_state, sgen_sense_bad);
		return (COMMAND_DONE_ERROR);
	}

	/*
	 * Now, check to see whether we got enough sense data to make any
	 * sense out if it (heh-heh).
	 */
	if (amt < SUN_MIN_SENSE_LENGTH) {
		sgen_log(sg_state, SGEN_DIAG1, "sgen_handle_sense: not "
		    "enough sense data");
		SGEN_DO_ERRSTATS(sg_state, sgen_sense_bad);
		return (COMMAND_DONE_ERROR);
	}

	/*
	 * Decode the sense data-- this was deposited here for us by the
	 * setup in sgen_do_attach(). (note that sgen_sense is an alias for
	 * the sd_sense field in the scsi_device).
	 */
	sgen_log(sg_state, SGEN_DIAG1, "Sense key is %s [0x%x]",
	    scsi_sname(sg_state->sgen_sense->es_key),
	    sg_state->sgen_sense->es_key);
	switch (sg_state->sgen_sense->es_key) {
	case KEY_RECOVERABLE_ERROR:
		SGEN_DO_ERRSTATS(sg_state, sgen_recov_err);
		break;
	case KEY_NO_SENSE:
		SGEN_DO_ERRSTATS(sg_state, sgen_nosen_err);
		break;
	default:
		SGEN_DO_ERRSTATS(sg_state, sgen_unrecov_err);
		break;
	}

	return (COMMAND_DONE);
}

/*
 * sgen_check_error()
 *	examine the command packet for abnormal completion.
 *
 *	sgen_check_error should only be called at the completion of the
 *	command packet.
 */
static int
sgen_check_error(sgen_state_t *sg_state, struct buf *bp)
{
	struct scsi_pkt *pkt = sg_state->sgen_cmdpkt;
	struct scsi_status *status = (struct scsi_status *)pkt->pkt_scbp;
	struct uscsi_cmd *ucmd =
	    (struct uscsi_cmd *)sg_state->sgen_cmdbuf->b_private;

	if (status->sts_busy) {
		sgen_log(sg_state, SGEN_DIAG1,
		    "sgen_check_error: target is busy");
		return (COMMAND_DONE_ERROR);
	}

	/*
	 * pkt_resid will reflect, at this point, a residual of how many bytes
	 * were not transferred; a non-zero pkt_resid is an error.
	 */
	if (pkt->pkt_resid) {
		bp->b_resid += pkt->pkt_resid;
	}

	if (status->sts_chk) {
		if (ucmd->uscsi_flags & USCSI_RQENABLE) {
			if (sg_state->sgen_arq_enabled) {
				sgen_log(sg_state, SGEN_DIAG1,
				    "sgen_check_error: strange: target "
				    "indicates CHECK CONDITION with auto-sense "
				    "enabled.");
			}
			sgen_log(sg_state, SGEN_DIAG2, "sgen_check_error: "
			    "target ready for sense fetch");
			return (FETCH_SENSE);
		} else {
			sgen_log(sg_state, SGEN_DIAG2, "sgen_check_error: "
			    "target indicates CHECK CONDITION");
		}
	}

	return (COMMAND_DONE);
}

/*
 * sgen_tur()
 *	test if a target is ready to operate by sending it a TUR command.
 */
static int
sgen_tur(dev_t dev)
{
	char cmdblk[CDB_GROUP0];
	struct uscsi_cmd scmd;

	bzero(&scmd, sizeof (scmd));
	scmd.uscsi_bufaddr = 0;
	scmd.uscsi_buflen = 0;
	bzero(cmdblk, CDB_GROUP0);
	cmdblk[0] = (char)SCMD_TEST_UNIT_READY;
	scmd.uscsi_flags = USCSI_DIAGNOSE | USCSI_SILENT | USCSI_WRITE;
	scmd.uscsi_cdb = cmdblk;
	scmd.uscsi_cdblen = CDB_GROUP0;

	return (sgen_uscsi_cmd(dev, &scmd, FKIOCTL));
}

/*
 * sgen_diag_ok()
 *	given an sg_state and a desired diagnostic level, return true if
 *	it is acceptable to output a message.
 */
/*ARGSUSED*/
static int
sgen_diag_ok(sgen_state_t *sg_state, int level)
{
	int diag_lvl;

	switch (level) {
	case CE_WARN:
	case CE_NOTE:
	case CE_CONT:
	case CE_PANIC:
		return (1);
	case SGEN_DIAG1:
	case SGEN_DIAG2:
	case SGEN_DIAG3:
		if (sg_state) {
			/*
			 * Check to see if user overrode the diagnostics level
			 * for this instance (either via SGEN_IOC_DIAG or via
			 * .conf file).  If not, fall back to the global diag
			 * level.
			 */
			if (sg_state->sgen_diag != -1)
				diag_lvl = sg_state->sgen_diag;
			else
				diag_lvl = sgen_diag;
		} else {
			diag_lvl = sgen_diag;
		}
		if (((diag_lvl << 8) | CE_CONT) >= level) {
			return (1);
		} else {
			return (0);
		}
	default:
		return (1);
	}
}

/*PRINTFLIKE3*/
static void
sgen_log(sgen_state_t *sg_state, int level, const char *fmt, ...)
{
	va_list	ap;
	char buf[256];

	if (!sgen_diag_ok(sg_state, level))
		return;

	va_start(ap, fmt);
	(void) vsnprintf(buf, sizeof (buf), fmt, ap);
	va_end(ap);

	switch (level) {
	case CE_NOTE:
	case CE_CONT:
	case CE_WARN:
	case CE_PANIC:
		if (sg_state == (sgen_state_t *)NULL) {
			cmn_err(level, "%s", buf);
		} else {
			scsi_log(sg_state->sgen_devinfo, sgen_label, level,
			    "%s", buf);
		}
		break;
	case SGEN_DIAG1:
	case SGEN_DIAG2:
	case SGEN_DIAG3:
	default:
		if (sg_state == (sgen_state_t *)NULL) {
			scsi_log(NULL, sgen_label, CE_CONT, "%s", buf);
		} else {
			scsi_log(sg_state->sgen_devinfo, sgen_label, CE_CONT,
			    "%s", buf);
		}
	}
}

/*
 * sgen_dump_cdb()
 *	dump out the contents of a cdb.  Take care that 'label' is not too
 *	large, or 'buf' could overflow.
 */
static void
sgen_dump_cdb(sgen_state_t *sg_state, const char *label,
    union scsi_cdb *cdb, int cdblen)
{
	static char hex[] = "0123456789abcdef";
	char *buf, *p;
	size_t nbytes;
	int i;
	uchar_t	*cdbp = (uchar_t *)cdb;

	/*
	 * fastpath-- if we're not able to print out, don't do all of this
	 * extra work.
	 */
	if (!sgen_diag_ok(sg_state, SGEN_DIAG3))
		return;

	/*
	 * 3 characters for each byte (because of the ' '), plus the size of
	 * the label, plus the trailing ']' and the null character.
	 */
	nbytes = 3 * cdblen + strlen(label) + strlen(" CDB = [") + 2;
	buf = kmem_alloc(nbytes, KM_SLEEP);
	(void) sprintf(buf, "%s CDB = [", label);
	p = &buf[strlen(buf)];
	for (i = 0; i < cdblen; i++, cdbp++) {
		if (i > 0)
			*p++ = ' ';
		*p++ = hex[(*cdbp >> 4) & 0x0f];
		*p++ = hex[*cdbp & 0x0f];
	}
	*p++ = ']';
	*p = 0;
	sgen_log(sg_state, SGEN_DIAG3, buf);
	kmem_free(buf, nbytes);
}

static void
sgen_dump_sense(sgen_state_t *sg_state, size_t rqlen, uchar_t *rqbuf)
{
	static char hex[] = "0123456789abcdef";
	char *buf, *p;
	size_t nbytes;
	int i;

	/*
	 * fastpath-- if we're not able to print out, don't do all of this
	 * extra work.
	 */
	if (!sgen_diag_ok(sg_state, SGEN_DIAG3))
		return;

	/*
	 * 3 characters for each byte (because of the ' '), plus the size of
	 * the label, plus the trailing ']' and the null character.
	 */
	nbytes = 3 * rqlen + strlen(" SENSE = [") + 2;
	buf = kmem_alloc(nbytes, KM_SLEEP);
	(void) sprintf(buf, "SENSE = [");
	p = &buf[strlen(buf)];
	for (i = 0; i < rqlen; i++, rqbuf++) {
		if (i > 0)
			*p++ = ' ';
		*p++ = hex[(*rqbuf >> 4) & 0x0f];
		*p++ = hex[*rqbuf & 0x0f];
	}
	*p++ = ']';
	*p = 0;
	sgen_log(sg_state, SGEN_DIAG3, buf);
	kmem_free(buf, nbytes);
}