xref: /illumos-gate/usr/src/uts/common/io/scsi/targets/sd.c (revision 581cede61ac9c14d8d4ea452562a567189eead78)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 
22 /*
23  * Copyright 2009 Sun Microsystems, Inc.  All rights reserved.
24  * Use is subject to license terms.
25  */
26 
27 /*
28  * SCSI disk target driver.
29  */
30 #include <sys/scsi/scsi.h>
31 #include <sys/dkbad.h>
32 #include <sys/dklabel.h>
33 #include <sys/dkio.h>
34 #include <sys/fdio.h>
35 #include <sys/cdio.h>
36 #include <sys/mhd.h>
37 #include <sys/vtoc.h>
38 #include <sys/dktp/fdisk.h>
39 #include <sys/kstat.h>
40 #include <sys/vtrace.h>
41 #include <sys/note.h>
42 #include <sys/thread.h>
43 #include <sys/proc.h>
44 #include <sys/efi_partition.h>
45 #include <sys/var.h>
46 #include <sys/aio_req.h>
47 
48 #ifdef __lock_lint
49 #define	_LP64
50 #define	__amd64
51 #endif
52 
53 #if (defined(__fibre))
54 /* Note: is there a leadville version of the following? */
55 #include <sys/fc4/fcal_linkapp.h>
56 #endif
57 #include <sys/taskq.h>
58 #include <sys/uuid.h>
59 #include <sys/byteorder.h>
60 #include <sys/sdt.h>
61 
62 #include "sd_xbuf.h"
63 
64 #include <sys/scsi/targets/sddef.h>
65 #include <sys/cmlb.h>
66 #include <sys/sysevent/eventdefs.h>
67 #include <sys/sysevent/dev.h>
68 
69 #include <sys/fm/protocol.h>
70 
71 /*
72  * Loadable module info.
73  */
74 #if (defined(__fibre))
75 #define	SD_MODULE_NAME	"SCSI SSA/FCAL Disk Driver"
76 char _depends_on[]	= "misc/scsi misc/cmlb drv/fcp";
77 #else /* !__fibre */
78 #define	SD_MODULE_NAME	"SCSI Disk Driver"
79 char _depends_on[]	= "misc/scsi misc/cmlb";
80 #endif /* !__fibre */
81 
82 /*
83  * Define the interconnect type, to allow the driver to distinguish
84  * between parallel SCSI (sd) and fibre channel (ssd) behaviors.
85  *
86  * This is really for backward compatibility. In the future, the driver
87  * should actually check the "interconnect-type" property as reported by
88  * the HBA; however at present this property is not defined by all HBAs,
89  * so we will use this #define (1) to permit the driver to run in
90  * backward-compatibility mode; and (2) to print a notification message
91  * if an FC HBA does not support the "interconnect-type" property.  The
92  * behavior of the driver will be to assume parallel SCSI behaviors unless
93  * the "interconnect-type" property is defined by the HBA **AND** has a
94  * value of either INTERCONNECT_FIBRE, INTERCONNECT_SSA, or
95  * INTERCONNECT_FABRIC, in which case the driver will assume Fibre
96  * Channel behaviors (as per the old ssd).  (Note that the
97  * INTERCONNECT_1394 and INTERCONNECT_USB types are not supported and
98  * will result in the driver assuming parallel SCSI behaviors.)
99  *
100  * (see common/sys/scsi/impl/services.h)
101  *
102  * Note: For ssd semantics, don't use INTERCONNECT_FABRIC as the default
103  * since some FC HBAs may already support that, and there is some code in
104  * the driver that already looks for it.  Using INTERCONNECT_FABRIC as the
105  * default would confuse that code, and besides things should work fine
106  * anyways if the FC HBA already reports INTERCONNECT_FABRIC for the
107  * "interconnect_type" property.
108  *
109  */
110 #if (defined(__fibre))
111 #define	SD_DEFAULT_INTERCONNECT_TYPE	SD_INTERCONNECT_FIBRE
112 #else
113 #define	SD_DEFAULT_INTERCONNECT_TYPE	SD_INTERCONNECT_PARALLEL
114 #endif
115 
116 /*
117  * The name of the driver, established from the module name in _init.
118  */
119 static	char *sd_label			= NULL;
120 
121 /*
122  * Driver name is unfortunately prefixed on some driver.conf properties.
123  */
124 #if (defined(__fibre))
125 #define	sd_max_xfer_size		ssd_max_xfer_size
126 #define	sd_config_list			ssd_config_list
127 static	char *sd_max_xfer_size		= "ssd_max_xfer_size";
128 static	char *sd_config_list		= "ssd-config-list";
129 #else
130 static	char *sd_max_xfer_size		= "sd_max_xfer_size";
131 static	char *sd_config_list		= "sd-config-list";
132 #endif
133 
134 /*
135  * Driver global variables
136  */
137 
138 #if (defined(__fibre))
139 /*
140  * These #defines are to avoid namespace collisions that occur because this
141  * code is currently used to compile two separate driver modules: sd and ssd.
142  * All global variables need to be treated this way (even if declared static)
143  * in order to allow the debugger to resolve the names properly.
144  * It is anticipated that in the near future the ssd module will be obsoleted,
145  * at which time this namespace issue should go away.
146  */
147 #define	sd_state			ssd_state
148 #define	sd_io_time			ssd_io_time
149 #define	sd_failfast_enable		ssd_failfast_enable
150 #define	sd_ua_retry_count		ssd_ua_retry_count
151 #define	sd_report_pfa			ssd_report_pfa
152 #define	sd_max_throttle			ssd_max_throttle
153 #define	sd_min_throttle			ssd_min_throttle
154 #define	sd_rot_delay			ssd_rot_delay
155 
156 #define	sd_retry_on_reservation_conflict	\
157 					ssd_retry_on_reservation_conflict
158 #define	sd_reinstate_resv_delay		ssd_reinstate_resv_delay
159 #define	sd_resv_conflict_name		ssd_resv_conflict_name
160 
161 #define	sd_component_mask		ssd_component_mask
162 #define	sd_level_mask			ssd_level_mask
163 #define	sd_debug_un			ssd_debug_un
164 #define	sd_error_level			ssd_error_level
165 
166 #define	sd_xbuf_active_limit		ssd_xbuf_active_limit
167 #define	sd_xbuf_reserve_limit		ssd_xbuf_reserve_limit
168 
169 #define	sd_tr				ssd_tr
170 #define	sd_reset_throttle_timeout	ssd_reset_throttle_timeout
171 #define	sd_qfull_throttle_timeout	ssd_qfull_throttle_timeout
172 #define	sd_qfull_throttle_enable	ssd_qfull_throttle_enable
173 #define	sd_check_media_time		ssd_check_media_time
174 #define	sd_wait_cmds_complete		ssd_wait_cmds_complete
175 #define	sd_label_mutex			ssd_label_mutex
176 #define	sd_detach_mutex			ssd_detach_mutex
177 #define	sd_log_buf			ssd_log_buf
178 #define	sd_log_mutex			ssd_log_mutex
179 
180 #define	sd_disk_table			ssd_disk_table
181 #define	sd_disk_table_size		ssd_disk_table_size
182 #define	sd_sense_mutex			ssd_sense_mutex
183 #define	sd_cdbtab			ssd_cdbtab
184 
185 #define	sd_cb_ops			ssd_cb_ops
186 #define	sd_ops				ssd_ops
187 #define	sd_additional_codes		ssd_additional_codes
188 #define	sd_tgops			ssd_tgops
189 
190 #define	sd_minor_data			ssd_minor_data
191 #define	sd_minor_data_efi		ssd_minor_data_efi
192 
193 #define	sd_tq				ssd_tq
194 #define	sd_wmr_tq			ssd_wmr_tq
195 #define	sd_taskq_name			ssd_taskq_name
196 #define	sd_wmr_taskq_name		ssd_wmr_taskq_name
197 #define	sd_taskq_minalloc		ssd_taskq_minalloc
198 #define	sd_taskq_maxalloc		ssd_taskq_maxalloc
199 
200 #define	sd_dump_format_string		ssd_dump_format_string
201 
202 #define	sd_iostart_chain		ssd_iostart_chain
203 #define	sd_iodone_chain			ssd_iodone_chain
204 
205 #define	sd_pm_idletime			ssd_pm_idletime
206 
207 #define	sd_force_pm_supported		ssd_force_pm_supported
208 
209 #define	sd_dtype_optical_bind		ssd_dtype_optical_bind
210 
211 #define	sd_ssc_init			ssd_ssc_init
212 #define	sd_ssc_send			ssd_ssc_send
213 #define	sd_ssc_fini			ssd_ssc_fini
214 #define	sd_ssc_assessment		ssd_ssc_assessment
215 #define	sd_ssc_post			ssd_ssc_post
216 #define	sd_ssc_print			ssd_ssc_print
217 #define	sd_ssc_ereport_post		ssd_ssc_ereport_post
218 #define	sd_ssc_set_info			ssd_ssc_set_info
219 #define	sd_ssc_extract_info		ssd_ssc_extract_info
220 
221 #endif
222 
223 #ifdef	SDDEBUG
224 int	sd_force_pm_supported		= 0;
225 #endif	/* SDDEBUG */
226 
227 void *sd_state				= NULL;
228 int sd_io_time				= SD_IO_TIME;
229 int sd_failfast_enable			= 1;
230 int sd_ua_retry_count			= SD_UA_RETRY_COUNT;
231 int sd_report_pfa			= 1;
232 int sd_max_throttle			= SD_MAX_THROTTLE;
233 int sd_min_throttle			= SD_MIN_THROTTLE;
234 int sd_rot_delay			= 4; /* Default 4ms Rotation delay */
235 int sd_qfull_throttle_enable		= TRUE;
236 
237 int sd_retry_on_reservation_conflict	= 1;
238 int sd_reinstate_resv_delay		= SD_REINSTATE_RESV_DELAY;
239 _NOTE(SCHEME_PROTECTS_DATA("safe sharing", sd_reinstate_resv_delay))
240 
241 static int sd_dtype_optical_bind	= -1;
242 
243 /* Note: the following is not a bug, it really is "sd_" and not "ssd_" */
244 static	char *sd_resv_conflict_name	= "sd_retry_on_reservation_conflict";
245 
246 /*
247  * Global data for debug logging. To enable debug printing, sd_component_mask
248  * and sd_level_mask should be set to the desired bit patterns as outlined in
249  * sddef.h.
250  */
251 uint_t	sd_component_mask		= 0x0;
252 uint_t	sd_level_mask			= 0x0;
253 struct	sd_lun *sd_debug_un		= NULL;
254 uint_t	sd_error_level			= SCSI_ERR_RETRYABLE;
255 
256 /* Note: these may go away in the future... */
257 static uint32_t	sd_xbuf_active_limit	= 512;
258 static uint32_t sd_xbuf_reserve_limit	= 16;
259 
260 static struct sd_resv_reclaim_request	sd_tr = { NULL, NULL, NULL, 0, 0, 0 };
261 
262 /*
263  * Timer value used to reset the throttle after it has been reduced
264  * (typically in response to TRAN_BUSY or STATUS_QFULL)
265  */
266 static int sd_reset_throttle_timeout	= SD_RESET_THROTTLE_TIMEOUT;
267 static int sd_qfull_throttle_timeout	= SD_QFULL_THROTTLE_TIMEOUT;
268 
269 /*
270  * Interval value associated with the media change scsi watch.
271  */
272 static int sd_check_media_time		= 3000000;
273 
274 /*
275  * Wait value used for in progress operations during a DDI_SUSPEND
276  */
277 static int sd_wait_cmds_complete	= SD_WAIT_CMDS_COMPLETE;
278 
279 /*
280  * sd_label_mutex protects a static buffer used in the disk label
281  * component of the driver
282  */
283 static kmutex_t sd_label_mutex;
284 
285 /*
286  * sd_detach_mutex protects un_layer_count, un_detach_count, and
287  * un_opens_in_progress in the sd_lun structure.
288  */
289 static kmutex_t sd_detach_mutex;
290 
291 _NOTE(MUTEX_PROTECTS_DATA(sd_detach_mutex,
292 	sd_lun::{un_layer_count un_detach_count un_opens_in_progress}))
293 
294 /*
295  * Global buffer and mutex for debug logging
296  */
297 static char	sd_log_buf[1024];
298 static kmutex_t	sd_log_mutex;
299 
300 /*
301  * Structs and globals for recording attached lun information.
302  * This maintains a chain. Each node in the chain represents a SCSI controller.
303  * The structure records the number of luns attached to each target connected
304  * with the controller.
305  * For parallel scsi device only.
306  */
307 struct sd_scsi_hba_tgt_lun {
308 	struct sd_scsi_hba_tgt_lun	*next;
309 	dev_info_t			*pdip;
310 	int				nlun[NTARGETS_WIDE];
311 };
312 
313 /*
314  * Flag to indicate the lun is attached or detached
315  */
316 #define	SD_SCSI_LUN_ATTACH	0
317 #define	SD_SCSI_LUN_DETACH	1
318 
319 static kmutex_t	sd_scsi_target_lun_mutex;
320 static struct sd_scsi_hba_tgt_lun	*sd_scsi_target_lun_head = NULL;
321 
322 _NOTE(MUTEX_PROTECTS_DATA(sd_scsi_target_lun_mutex,
323     sd_scsi_hba_tgt_lun::next sd_scsi_hba_tgt_lun::pdip))
324 
325 _NOTE(MUTEX_PROTECTS_DATA(sd_scsi_target_lun_mutex,
326     sd_scsi_target_lun_head))
327 
328 /*
329  * "Smart" Probe Caching structs, globals, #defines, etc.
330  * For parallel scsi and non-self-identify device only.
331  */
332 
333 /*
334  * The following resources and routines are implemented to support
335  * "smart" probing, which caches the scsi_probe() results in an array,
336  * in order to help avoid long probe times.
337  */
338 struct sd_scsi_probe_cache {
339 	struct	sd_scsi_probe_cache	*next;
340 	dev_info_t	*pdip;
341 	int		cache[NTARGETS_WIDE];
342 };
343 
344 static kmutex_t	sd_scsi_probe_cache_mutex;
345 static struct	sd_scsi_probe_cache *sd_scsi_probe_cache_head = NULL;
346 
347 /*
348  * Really we only need protection on the head of the linked list, but
349  * better safe than sorry.
350  */
351 _NOTE(MUTEX_PROTECTS_DATA(sd_scsi_probe_cache_mutex,
352     sd_scsi_probe_cache::next sd_scsi_probe_cache::pdip))
353 
354 _NOTE(MUTEX_PROTECTS_DATA(sd_scsi_probe_cache_mutex,
355     sd_scsi_probe_cache_head))
356 
357 /*
358  * Power attribute table
359  */
360 static sd_power_attr_ss sd_pwr_ss = {
361 	{ "NAME=spindle-motor", "0=off", "1=on", NULL },
362 	{0, 100},
363 	{30, 0},
364 	{20000, 0}
365 };
366 
367 static sd_power_attr_pc sd_pwr_pc = {
368 	{ "NAME=spindle-motor", "0=stopped", "1=standby", "2=idle",
369 		"3=active", NULL },
370 	{0, 0, 0, 100},
371 	{90, 90, 20, 0},
372 	{15000, 15000, 1000, 0}
373 };
374 
375 /*
376  * Power level to power condition
377  */
378 static int sd_pl2pc[] = {
379 	SD_TARGET_START_VALID,
380 	SD_TARGET_STANDBY,
381 	SD_TARGET_IDLE,
382 	SD_TARGET_ACTIVE
383 };
384 
385 /*
386  * Vendor specific data name property declarations
387  */
388 
389 #if defined(__fibre) || defined(__i386) ||defined(__amd64)
390 
391 static sd_tunables seagate_properties = {
392 	SEAGATE_THROTTLE_VALUE,
393 	0,
394 	0,
395 	0,
396 	0,
397 	0,
398 	0,
399 	0,
400 	0
401 };
402 
403 
404 static sd_tunables fujitsu_properties = {
405 	FUJITSU_THROTTLE_VALUE,
406 	0,
407 	0,
408 	0,
409 	0,
410 	0,
411 	0,
412 	0,
413 	0
414 };
415 
416 static sd_tunables ibm_properties = {
417 	IBM_THROTTLE_VALUE,
418 	0,
419 	0,
420 	0,
421 	0,
422 	0,
423 	0,
424 	0,
425 	0
426 };
427 
428 static sd_tunables purple_properties = {
429 	PURPLE_THROTTLE_VALUE,
430 	0,
431 	0,
432 	PURPLE_BUSY_RETRIES,
433 	PURPLE_RESET_RETRY_COUNT,
434 	PURPLE_RESERVE_RELEASE_TIME,
435 	0,
436 	0,
437 	0
438 };
439 
440 static sd_tunables sve_properties = {
441 	SVE_THROTTLE_VALUE,
442 	0,
443 	0,
444 	SVE_BUSY_RETRIES,
445 	SVE_RESET_RETRY_COUNT,
446 	SVE_RESERVE_RELEASE_TIME,
447 	SVE_MIN_THROTTLE_VALUE,
448 	SVE_DISKSORT_DISABLED_FLAG,
449 	0
450 };
451 
452 static sd_tunables maserati_properties = {
453 	0,
454 	0,
455 	0,
456 	0,
457 	0,
458 	0,
459 	0,
460 	MASERATI_DISKSORT_DISABLED_FLAG,
461 	MASERATI_LUN_RESET_ENABLED_FLAG
462 };
463 
464 static sd_tunables pirus_properties = {
465 	PIRUS_THROTTLE_VALUE,
466 	0,
467 	PIRUS_NRR_COUNT,
468 	PIRUS_BUSY_RETRIES,
469 	PIRUS_RESET_RETRY_COUNT,
470 	0,
471 	PIRUS_MIN_THROTTLE_VALUE,
472 	PIRUS_DISKSORT_DISABLED_FLAG,
473 	PIRUS_LUN_RESET_ENABLED_FLAG
474 };
475 
476 #endif
477 
478 #if (defined(__sparc) && !defined(__fibre)) || \
479 	(defined(__i386) || defined(__amd64))
480 
481 
482 static sd_tunables elite_properties = {
483 	ELITE_THROTTLE_VALUE,
484 	0,
485 	0,
486 	0,
487 	0,
488 	0,
489 	0,
490 	0,
491 	0
492 };
493 
494 static sd_tunables st31200n_properties = {
495 	ST31200N_THROTTLE_VALUE,
496 	0,
497 	0,
498 	0,
499 	0,
500 	0,
501 	0,
502 	0,
503 	0
504 };
505 
506 #endif /* Fibre or not */
507 
508 static sd_tunables lsi_properties_scsi = {
509 	LSI_THROTTLE_VALUE,
510 	0,
511 	LSI_NOTREADY_RETRIES,
512 	0,
513 	0,
514 	0,
515 	0,
516 	0,
517 	0
518 };
519 
520 static sd_tunables symbios_properties = {
521 	SYMBIOS_THROTTLE_VALUE,
522 	0,
523 	SYMBIOS_NOTREADY_RETRIES,
524 	0,
525 	0,
526 	0,
527 	0,
528 	0,
529 	0
530 };
531 
532 static sd_tunables lsi_properties = {
533 	0,
534 	0,
535 	LSI_NOTREADY_RETRIES,
536 	0,
537 	0,
538 	0,
539 	0,
540 	0,
541 	0
542 };
543 
544 static sd_tunables lsi_oem_properties = {
545 	0,
546 	0,
547 	LSI_OEM_NOTREADY_RETRIES,
548 	0,
549 	0,
550 	0,
551 	0,
552 	0,
553 	0,
554 	1
555 };
556 
557 
558 
559 #if (defined(SD_PROP_TST))
560 
561 #define	SD_TST_CTYPE_VAL	CTYPE_CDROM
562 #define	SD_TST_THROTTLE_VAL	16
563 #define	SD_TST_NOTREADY_VAL	12
564 #define	SD_TST_BUSY_VAL		60
565 #define	SD_TST_RST_RETRY_VAL	36
566 #define	SD_TST_RSV_REL_TIME	60
567 
568 static sd_tunables tst_properties = {
569 	SD_TST_THROTTLE_VAL,
570 	SD_TST_CTYPE_VAL,
571 	SD_TST_NOTREADY_VAL,
572 	SD_TST_BUSY_VAL,
573 	SD_TST_RST_RETRY_VAL,
574 	SD_TST_RSV_REL_TIME,
575 	0,
576 	0,
577 	0
578 };
579 #endif
580 
581 /* This is similar to the ANSI toupper implementation */
582 #define	SD_TOUPPER(C)	(((C) >= 'a' && (C) <= 'z') ? (C) - 'a' + 'A' : (C))
583 
584 /*
585  * Static Driver Configuration Table
586  *
587  * This is the table of disks which need throttle adjustment (or, perhaps
588  * something else as defined by the flags at a future time.)  device_id
589  * is a string consisting of concatenated vid (vendor), pid (product/model)
590  * and revision strings as defined in the scsi_inquiry structure.  Offsets of
591  * the parts of the string are as defined by the sizes in the scsi_inquiry
592  * structure.  Device type is searched as far as the device_id string is
593  * defined.  Flags defines which values are to be set in the driver from the
594  * properties list.
595  *
596  * Entries below which begin and end with a "*" are a special case.
597  * These do not have a specific vendor, and the string which follows
598  * can appear anywhere in the 16 byte PID portion of the inquiry data.
599  *
600  * Entries below which begin and end with a " " (blank) are a special
601  * case. The comparison function will treat multiple consecutive blanks
602  * as equivalent to a single blank. For example, this causes a
603  * sd_disk_table entry of " NEC CDROM " to match a device's id string
604  * of  "NEC       CDROM".
605  *
606  * Note: The MD21 controller type has been obsoleted.
607  *	 ST318202F is a Legacy device
608  *	 MAM3182FC, MAM3364FC, MAM3738FC do not appear to have ever been
609  *	 made with an FC connection. The entries here are a legacy.
610  */
611 static sd_disk_config_t sd_disk_table[] = {
612 #if defined(__fibre) || defined(__i386) || defined(__amd64)
613 	{ "SEAGATE ST34371FC", SD_CONF_BSET_THROTTLE, &seagate_properties },
614 	{ "SEAGATE ST19171FC", SD_CONF_BSET_THROTTLE, &seagate_properties },
615 	{ "SEAGATE ST39102FC", SD_CONF_BSET_THROTTLE, &seagate_properties },
616 	{ "SEAGATE ST39103FC", SD_CONF_BSET_THROTTLE, &seagate_properties },
617 	{ "SEAGATE ST118273F", SD_CONF_BSET_THROTTLE, &seagate_properties },
618 	{ "SEAGATE ST318202F", SD_CONF_BSET_THROTTLE, &seagate_properties },
619 	{ "SEAGATE ST318203F", SD_CONF_BSET_THROTTLE, &seagate_properties },
620 	{ "SEAGATE ST136403F", SD_CONF_BSET_THROTTLE, &seagate_properties },
621 	{ "SEAGATE ST318304F", SD_CONF_BSET_THROTTLE, &seagate_properties },
622 	{ "SEAGATE ST336704F", SD_CONF_BSET_THROTTLE, &seagate_properties },
623 	{ "SEAGATE ST373405F", SD_CONF_BSET_THROTTLE, &seagate_properties },
624 	{ "SEAGATE ST336605F", SD_CONF_BSET_THROTTLE, &seagate_properties },
625 	{ "SEAGATE ST336752F", SD_CONF_BSET_THROTTLE, &seagate_properties },
626 	{ "SEAGATE ST318452F", SD_CONF_BSET_THROTTLE, &seagate_properties },
627 	{ "FUJITSU MAG3091F",  SD_CONF_BSET_THROTTLE, &fujitsu_properties },
628 	{ "FUJITSU MAG3182F",  SD_CONF_BSET_THROTTLE, &fujitsu_properties },
629 	{ "FUJITSU MAA3182F",  SD_CONF_BSET_THROTTLE, &fujitsu_properties },
630 	{ "FUJITSU MAF3364F",  SD_CONF_BSET_THROTTLE, &fujitsu_properties },
631 	{ "FUJITSU MAL3364F",  SD_CONF_BSET_THROTTLE, &fujitsu_properties },
632 	{ "FUJITSU MAL3738F",  SD_CONF_BSET_THROTTLE, &fujitsu_properties },
633 	{ "FUJITSU MAM3182FC",  SD_CONF_BSET_THROTTLE, &fujitsu_properties },
634 	{ "FUJITSU MAM3364FC",  SD_CONF_BSET_THROTTLE, &fujitsu_properties },
635 	{ "FUJITSU MAM3738FC",  SD_CONF_BSET_THROTTLE, &fujitsu_properties },
636 	{ "IBM     DDYFT1835",  SD_CONF_BSET_THROTTLE, &ibm_properties },
637 	{ "IBM     DDYFT3695",  SD_CONF_BSET_THROTTLE, &ibm_properties },
638 	{ "IBM     IC35LF2D2",  SD_CONF_BSET_THROTTLE, &ibm_properties },
639 	{ "IBM     IC35LF2PR",  SD_CONF_BSET_THROTTLE, &ibm_properties },
640 	{ "IBM     1724-100",   SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
641 	{ "IBM     1726-2xx",   SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
642 	{ "IBM     1726-22x",   SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
643 	{ "IBM     1726-4xx",   SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
644 	{ "IBM     1726-42x",   SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
645 	{ "IBM     1726-3xx",   SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
646 	{ "IBM     3526",	SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
647 	{ "IBM     3542",	SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
648 	{ "IBM     3552",	SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
649 	{ "IBM     1722",	SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
650 	{ "IBM     1742",	SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
651 	{ "IBM     1815",	SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
652 	{ "IBM     FAStT",	SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
653 	{ "IBM     1814",	SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
654 	{ "IBM     1814-200",	SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
655 	{ "IBM     1818",	SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
656 	{ "DELL    MD3000",	SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
657 	{ "DELL    MD3000i",	SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
658 	{ "LSI     INF",	SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
659 	{ "ENGENIO INF",	SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
660 	{ "SGI     TP",		SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
661 	{ "SGI     IS",		SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
662 	{ "*CSM100_*",		SD_CONF_BSET_NRR_COUNT |
663 			SD_CONF_BSET_CACHE_IS_NV, &lsi_oem_properties },
664 	{ "*CSM200_*",		SD_CONF_BSET_NRR_COUNT |
665 			SD_CONF_BSET_CACHE_IS_NV, &lsi_oem_properties },
666 	{ "Fujitsu SX300",	SD_CONF_BSET_THROTTLE,  &lsi_oem_properties },
667 	{ "LSI",		SD_CONF_BSET_NRR_COUNT, &lsi_properties },
668 	{ "SUN     T3", SD_CONF_BSET_THROTTLE |
669 			SD_CONF_BSET_BSY_RETRY_COUNT|
670 			SD_CONF_BSET_RST_RETRIES|
671 			SD_CONF_BSET_RSV_REL_TIME,
672 		&purple_properties },
673 	{ "SUN     SESS01", SD_CONF_BSET_THROTTLE |
674 		SD_CONF_BSET_BSY_RETRY_COUNT|
675 		SD_CONF_BSET_RST_RETRIES|
676 		SD_CONF_BSET_RSV_REL_TIME|
677 		SD_CONF_BSET_MIN_THROTTLE|
678 		SD_CONF_BSET_DISKSORT_DISABLED,
679 		&sve_properties },
680 	{ "SUN     T4", SD_CONF_BSET_THROTTLE |
681 			SD_CONF_BSET_BSY_RETRY_COUNT|
682 			SD_CONF_BSET_RST_RETRIES|
683 			SD_CONF_BSET_RSV_REL_TIME,
684 		&purple_properties },
685 	{ "SUN     SVE01", SD_CONF_BSET_DISKSORT_DISABLED |
686 		SD_CONF_BSET_LUN_RESET_ENABLED,
687 		&maserati_properties },
688 	{ "SUN     SE6920", SD_CONF_BSET_THROTTLE |
689 		SD_CONF_BSET_NRR_COUNT|
690 		SD_CONF_BSET_BSY_RETRY_COUNT|
691 		SD_CONF_BSET_RST_RETRIES|
692 		SD_CONF_BSET_MIN_THROTTLE|
693 		SD_CONF_BSET_DISKSORT_DISABLED|
694 		SD_CONF_BSET_LUN_RESET_ENABLED,
695 		&pirus_properties },
696 	{ "SUN     SE6940", SD_CONF_BSET_THROTTLE |
697 		SD_CONF_BSET_NRR_COUNT|
698 		SD_CONF_BSET_BSY_RETRY_COUNT|
699 		SD_CONF_BSET_RST_RETRIES|
700 		SD_CONF_BSET_MIN_THROTTLE|
701 		SD_CONF_BSET_DISKSORT_DISABLED|
702 		SD_CONF_BSET_LUN_RESET_ENABLED,
703 		&pirus_properties },
704 	{ "SUN     StorageTek 6920", SD_CONF_BSET_THROTTLE |
705 		SD_CONF_BSET_NRR_COUNT|
706 		SD_CONF_BSET_BSY_RETRY_COUNT|
707 		SD_CONF_BSET_RST_RETRIES|
708 		SD_CONF_BSET_MIN_THROTTLE|
709 		SD_CONF_BSET_DISKSORT_DISABLED|
710 		SD_CONF_BSET_LUN_RESET_ENABLED,
711 		&pirus_properties },
712 	{ "SUN     StorageTek 6940", SD_CONF_BSET_THROTTLE |
713 		SD_CONF_BSET_NRR_COUNT|
714 		SD_CONF_BSET_BSY_RETRY_COUNT|
715 		SD_CONF_BSET_RST_RETRIES|
716 		SD_CONF_BSET_MIN_THROTTLE|
717 		SD_CONF_BSET_DISKSORT_DISABLED|
718 		SD_CONF_BSET_LUN_RESET_ENABLED,
719 		&pirus_properties },
720 	{ "SUN     PSX1000", SD_CONF_BSET_THROTTLE |
721 		SD_CONF_BSET_NRR_COUNT|
722 		SD_CONF_BSET_BSY_RETRY_COUNT|
723 		SD_CONF_BSET_RST_RETRIES|
724 		SD_CONF_BSET_MIN_THROTTLE|
725 		SD_CONF_BSET_DISKSORT_DISABLED|
726 		SD_CONF_BSET_LUN_RESET_ENABLED,
727 		&pirus_properties },
728 	{ "SUN     SE6330", SD_CONF_BSET_THROTTLE |
729 		SD_CONF_BSET_NRR_COUNT|
730 		SD_CONF_BSET_BSY_RETRY_COUNT|
731 		SD_CONF_BSET_RST_RETRIES|
732 		SD_CONF_BSET_MIN_THROTTLE|
733 		SD_CONF_BSET_DISKSORT_DISABLED|
734 		SD_CONF_BSET_LUN_RESET_ENABLED,
735 		&pirus_properties },
736 	{ "SUN     STK6580_6780", SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
737 	{ "SUN     SUN_6180", SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
738 	{ "STK     OPENstorage", SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
739 	{ "STK     OpenStorage", SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
740 	{ "STK     BladeCtlr",	SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
741 	{ "STK     FLEXLINE",	SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
742 	{ "SYMBIOS", SD_CONF_BSET_NRR_COUNT, &symbios_properties },
743 #endif /* fibre or NON-sparc platforms */
744 #if ((defined(__sparc) && !defined(__fibre)) ||\
745 	(defined(__i386) || defined(__amd64)))
746 	{ "SEAGATE ST42400N", SD_CONF_BSET_THROTTLE, &elite_properties },
747 	{ "SEAGATE ST31200N", SD_CONF_BSET_THROTTLE, &st31200n_properties },
748 	{ "SEAGATE ST41600N", SD_CONF_BSET_TUR_CHECK, NULL },
749 	{ "CONNER  CP30540",  SD_CONF_BSET_NOCACHE,  NULL },
750 	{ "*SUN0104*", SD_CONF_BSET_FAB_DEVID, NULL },
751 	{ "*SUN0207*", SD_CONF_BSET_FAB_DEVID, NULL },
752 	{ "*SUN0327*", SD_CONF_BSET_FAB_DEVID, NULL },
753 	{ "*SUN0340*", SD_CONF_BSET_FAB_DEVID, NULL },
754 	{ "*SUN0424*", SD_CONF_BSET_FAB_DEVID, NULL },
755 	{ "*SUN0669*", SD_CONF_BSET_FAB_DEVID, NULL },
756 	{ "*SUN1.0G*", SD_CONF_BSET_FAB_DEVID, NULL },
757 	{ "SYMBIOS INF-01-00       ", SD_CONF_BSET_FAB_DEVID, NULL },
758 	{ "SYMBIOS", SD_CONF_BSET_THROTTLE|SD_CONF_BSET_NRR_COUNT,
759 	    &symbios_properties },
760 	{ "LSI", SD_CONF_BSET_THROTTLE | SD_CONF_BSET_NRR_COUNT,
761 	    &lsi_properties_scsi },
762 #if defined(__i386) || defined(__amd64)
763 	{ " NEC CD-ROM DRIVE:260 ", (SD_CONF_BSET_PLAYMSF_BCD
764 				    | SD_CONF_BSET_READSUB_BCD
765 				    | SD_CONF_BSET_READ_TOC_ADDR_BCD
766 				    | SD_CONF_BSET_NO_READ_HEADER
767 				    | SD_CONF_BSET_READ_CD_XD4), NULL },
768 
769 	{ " NEC CD-ROM DRIVE:270 ", (SD_CONF_BSET_PLAYMSF_BCD
770 				    | SD_CONF_BSET_READSUB_BCD
771 				    | SD_CONF_BSET_READ_TOC_ADDR_BCD
772 				    | SD_CONF_BSET_NO_READ_HEADER
773 				    | SD_CONF_BSET_READ_CD_XD4), NULL },
774 #endif /* __i386 || __amd64 */
775 #endif /* sparc NON-fibre or NON-sparc platforms */
776 
777 #if (defined(SD_PROP_TST))
778 	{ "VENDOR  PRODUCT ", (SD_CONF_BSET_THROTTLE
779 				| SD_CONF_BSET_CTYPE
780 				| SD_CONF_BSET_NRR_COUNT
781 				| SD_CONF_BSET_FAB_DEVID
782 				| SD_CONF_BSET_NOCACHE
783 				| SD_CONF_BSET_BSY_RETRY_COUNT
784 				| SD_CONF_BSET_PLAYMSF_BCD
785 				| SD_CONF_BSET_READSUB_BCD
786 				| SD_CONF_BSET_READ_TOC_TRK_BCD
787 				| SD_CONF_BSET_READ_TOC_ADDR_BCD
788 				| SD_CONF_BSET_NO_READ_HEADER
789 				| SD_CONF_BSET_READ_CD_XD4
790 				| SD_CONF_BSET_RST_RETRIES
791 				| SD_CONF_BSET_RSV_REL_TIME
792 				| SD_CONF_BSET_TUR_CHECK), &tst_properties},
793 #endif
794 };
795 
796 static const int sd_disk_table_size =
797 	sizeof (sd_disk_table)/ sizeof (sd_disk_config_t);
798 
799 
800 
801 #define	SD_INTERCONNECT_PARALLEL	0
802 #define	SD_INTERCONNECT_FABRIC		1
803 #define	SD_INTERCONNECT_FIBRE		2
804 #define	SD_INTERCONNECT_SSA		3
805 #define	SD_INTERCONNECT_SATA		4
806 #define	SD_INTERCONNECT_SAS		5
807 
808 #define	SD_IS_PARALLEL_SCSI(un)		\
809 	((un)->un_interconnect_type == SD_INTERCONNECT_PARALLEL)
810 #define	SD_IS_SERIAL(un)		\
811 	(((un)->un_interconnect_type == SD_INTERCONNECT_SATA) ||\
812 	((un)->un_interconnect_type == SD_INTERCONNECT_SAS))
813 
814 /*
815  * Definitions used by device id registration routines
816  */
817 #define	VPD_HEAD_OFFSET		3	/* size of head for vpd page */
818 #define	VPD_PAGE_LENGTH		3	/* offset for pge length data */
819 #define	VPD_MODE_PAGE		1	/* offset into vpd pg for "page code" */
820 
821 static kmutex_t sd_sense_mutex = {0};
822 
823 /*
824  * Macros for updates of the driver state
825  */
826 #define	New_state(un, s)        \
827 	(un)->un_last_state = (un)->un_state, (un)->un_state = (s)
828 #define	Restore_state(un)	\
829 	{ uchar_t tmp = (un)->un_last_state; New_state((un), tmp); }
830 
831 static struct sd_cdbinfo sd_cdbtab[] = {
832 	{ CDB_GROUP0, 0x00,	   0x1FFFFF,   0xFF,	    },
833 	{ CDB_GROUP1, SCMD_GROUP1, 0xFFFFFFFF, 0xFFFF,	    },
834 	{ CDB_GROUP5, SCMD_GROUP5, 0xFFFFFFFF, 0xFFFFFFFF,  },
835 	{ CDB_GROUP4, SCMD_GROUP4, 0xFFFFFFFFFFFFFFFF, 0xFFFFFFFF, },
836 };
837 
838 /*
839  * Specifies the number of seconds that must have elapsed since the last
840  * cmd. has completed for a device to be declared idle to the PM framework.
841  */
842 static int sd_pm_idletime = 1;
843 
844 /*
845  * Internal function prototypes
846  */
847 
848 #if (defined(__fibre))
849 /*
850  * These #defines are to avoid namespace collisions that occur because this
851  * code is currently used to compile two separate driver modules: sd and ssd.
852  * All function names need to be treated this way (even if declared static)
853  * in order to allow the debugger to resolve the names properly.
854  * It is anticipated that in the near future the ssd module will be obsoleted,
855  * at which time this ugliness should go away.
856  */
857 #define	sd_log_trace			ssd_log_trace
858 #define	sd_log_info			ssd_log_info
859 #define	sd_log_err			ssd_log_err
860 #define	sdprobe				ssdprobe
861 #define	sdinfo				ssdinfo
862 #define	sd_prop_op			ssd_prop_op
863 #define	sd_scsi_probe_cache_init	ssd_scsi_probe_cache_init
864 #define	sd_scsi_probe_cache_fini	ssd_scsi_probe_cache_fini
865 #define	sd_scsi_clear_probe_cache	ssd_scsi_clear_probe_cache
866 #define	sd_scsi_probe_with_cache	ssd_scsi_probe_with_cache
867 #define	sd_scsi_target_lun_init		ssd_scsi_target_lun_init
868 #define	sd_scsi_target_lun_fini		ssd_scsi_target_lun_fini
869 #define	sd_scsi_get_target_lun_count	ssd_scsi_get_target_lun_count
870 #define	sd_scsi_update_lun_on_target	ssd_scsi_update_lun_on_target
871 #define	sd_spin_up_unit			ssd_spin_up_unit
872 #define	sd_enable_descr_sense		ssd_enable_descr_sense
873 #define	sd_reenable_dsense_task		ssd_reenable_dsense_task
874 #define	sd_set_mmc_caps			ssd_set_mmc_caps
875 #define	sd_read_unit_properties		ssd_read_unit_properties
876 #define	sd_process_sdconf_file		ssd_process_sdconf_file
877 #define	sd_process_sdconf_table		ssd_process_sdconf_table
878 #define	sd_sdconf_id_match		ssd_sdconf_id_match
879 #define	sd_blank_cmp			ssd_blank_cmp
880 #define	sd_chk_vers1_data		ssd_chk_vers1_data
881 #define	sd_set_vers1_properties		ssd_set_vers1_properties
882 #define	sd_check_solid_state		ssd_check_solid_state
883 
884 #define	sd_get_physical_geometry	ssd_get_physical_geometry
885 #define	sd_get_virtual_geometry		ssd_get_virtual_geometry
886 #define	sd_update_block_info		ssd_update_block_info
887 #define	sd_register_devid		ssd_register_devid
888 #define	sd_get_devid			ssd_get_devid
889 #define	sd_create_devid			ssd_create_devid
890 #define	sd_write_deviceid		ssd_write_deviceid
891 #define	sd_check_vpd_page_support	ssd_check_vpd_page_support
892 #define	sd_setup_pm			ssd_setup_pm
893 #define	sd_create_pm_components		ssd_create_pm_components
894 #define	sd_ddi_suspend			ssd_ddi_suspend
895 #define	sd_ddi_resume			ssd_ddi_resume
896 #define	sd_pm_state_change		ssd_pm_state_change
897 #define	sdpower				ssdpower
898 #define	sdattach			ssdattach
899 #define	sddetach			ssddetach
900 #define	sd_unit_attach			ssd_unit_attach
901 #define	sd_unit_detach			ssd_unit_detach
902 #define	sd_set_unit_attributes		ssd_set_unit_attributes
903 #define	sd_create_errstats		ssd_create_errstats
904 #define	sd_set_errstats			ssd_set_errstats
905 #define	sd_set_pstats			ssd_set_pstats
906 #define	sddump				ssddump
907 #define	sd_scsi_poll			ssd_scsi_poll
908 #define	sd_send_polled_RQS		ssd_send_polled_RQS
909 #define	sd_ddi_scsi_poll		ssd_ddi_scsi_poll
910 #define	sd_init_event_callbacks		ssd_init_event_callbacks
911 #define	sd_event_callback		ssd_event_callback
912 #define	sd_cache_control		ssd_cache_control
913 #define	sd_get_write_cache_enabled	ssd_get_write_cache_enabled
914 #define	sd_get_nv_sup			ssd_get_nv_sup
915 #define	sd_make_device			ssd_make_device
916 #define	sdopen				ssdopen
917 #define	sdclose				ssdclose
918 #define	sd_ready_and_valid		ssd_ready_and_valid
919 #define	sdmin				ssdmin
920 #define	sdread				ssdread
921 #define	sdwrite				ssdwrite
922 #define	sdaread				ssdaread
923 #define	sdawrite			ssdawrite
924 #define	sdstrategy			ssdstrategy
925 #define	sdioctl				ssdioctl
926 #define	sd_mapblockaddr_iostart		ssd_mapblockaddr_iostart
927 #define	sd_mapblocksize_iostart		ssd_mapblocksize_iostart
928 #define	sd_checksum_iostart		ssd_checksum_iostart
929 #define	sd_checksum_uscsi_iostart	ssd_checksum_uscsi_iostart
930 #define	sd_pm_iostart			ssd_pm_iostart
931 #define	sd_core_iostart			ssd_core_iostart
932 #define	sd_mapblockaddr_iodone		ssd_mapblockaddr_iodone
933 #define	sd_mapblocksize_iodone		ssd_mapblocksize_iodone
934 #define	sd_checksum_iodone		ssd_checksum_iodone
935 #define	sd_checksum_uscsi_iodone	ssd_checksum_uscsi_iodone
936 #define	sd_pm_iodone			ssd_pm_iodone
937 #define	sd_initpkt_for_buf		ssd_initpkt_for_buf
938 #define	sd_destroypkt_for_buf		ssd_destroypkt_for_buf
939 #define	sd_setup_rw_pkt			ssd_setup_rw_pkt
940 #define	sd_setup_next_rw_pkt		ssd_setup_next_rw_pkt
941 #define	sd_buf_iodone			ssd_buf_iodone
942 #define	sd_uscsi_strategy		ssd_uscsi_strategy
943 #define	sd_initpkt_for_uscsi		ssd_initpkt_for_uscsi
944 #define	sd_destroypkt_for_uscsi		ssd_destroypkt_for_uscsi
945 #define	sd_uscsi_iodone			ssd_uscsi_iodone
946 #define	sd_xbuf_strategy		ssd_xbuf_strategy
947 #define	sd_xbuf_init			ssd_xbuf_init
948 #define	sd_pm_entry			ssd_pm_entry
949 #define	sd_pm_exit			ssd_pm_exit
950 
951 #define	sd_pm_idletimeout_handler	ssd_pm_idletimeout_handler
952 #define	sd_pm_timeout_handler		ssd_pm_timeout_handler
953 
954 #define	sd_add_buf_to_waitq		ssd_add_buf_to_waitq
955 #define	sdintr				ssdintr
956 #define	sd_start_cmds			ssd_start_cmds
957 #define	sd_send_scsi_cmd		ssd_send_scsi_cmd
958 #define	sd_bioclone_alloc		ssd_bioclone_alloc
959 #define	sd_bioclone_free		ssd_bioclone_free
960 #define	sd_shadow_buf_alloc		ssd_shadow_buf_alloc
961 #define	sd_shadow_buf_free		ssd_shadow_buf_free
962 #define	sd_print_transport_rejected_message	\
963 					ssd_print_transport_rejected_message
964 #define	sd_retry_command		ssd_retry_command
965 #define	sd_set_retry_bp			ssd_set_retry_bp
966 #define	sd_send_request_sense_command	ssd_send_request_sense_command
967 #define	sd_start_retry_command		ssd_start_retry_command
968 #define	sd_start_direct_priority_command	\
969 					ssd_start_direct_priority_command
970 #define	sd_return_failed_command	ssd_return_failed_command
971 #define	sd_return_failed_command_no_restart	\
972 					ssd_return_failed_command_no_restart
973 #define	sd_return_command		ssd_return_command
974 #define	sd_sync_with_callback		ssd_sync_with_callback
975 #define	sdrunout			ssdrunout
976 #define	sd_mark_rqs_busy		ssd_mark_rqs_busy
977 #define	sd_mark_rqs_idle		ssd_mark_rqs_idle
978 #define	sd_reduce_throttle		ssd_reduce_throttle
979 #define	sd_restore_throttle		ssd_restore_throttle
980 #define	sd_print_incomplete_msg		ssd_print_incomplete_msg
981 #define	sd_init_cdb_limits		ssd_init_cdb_limits
982 #define	sd_pkt_status_good		ssd_pkt_status_good
983 #define	sd_pkt_status_check_condition	ssd_pkt_status_check_condition
984 #define	sd_pkt_status_busy		ssd_pkt_status_busy
985 #define	sd_pkt_status_reservation_conflict	\
986 					ssd_pkt_status_reservation_conflict
987 #define	sd_pkt_status_qfull		ssd_pkt_status_qfull
988 #define	sd_handle_request_sense		ssd_handle_request_sense
989 #define	sd_handle_auto_request_sense	ssd_handle_auto_request_sense
990 #define	sd_print_sense_failed_msg	ssd_print_sense_failed_msg
991 #define	sd_validate_sense_data		ssd_validate_sense_data
992 #define	sd_decode_sense			ssd_decode_sense
993 #define	sd_print_sense_msg		ssd_print_sense_msg
994 #define	sd_sense_key_no_sense		ssd_sense_key_no_sense
995 #define	sd_sense_key_recoverable_error	ssd_sense_key_recoverable_error
996 #define	sd_sense_key_not_ready		ssd_sense_key_not_ready
997 #define	sd_sense_key_medium_or_hardware_error	\
998 					ssd_sense_key_medium_or_hardware_error
999 #define	sd_sense_key_illegal_request	ssd_sense_key_illegal_request
1000 #define	sd_sense_key_unit_attention	ssd_sense_key_unit_attention
1001 #define	sd_sense_key_fail_command	ssd_sense_key_fail_command
1002 #define	sd_sense_key_blank_check	ssd_sense_key_blank_check
1003 #define	sd_sense_key_aborted_command	ssd_sense_key_aborted_command
1004 #define	sd_sense_key_default		ssd_sense_key_default
1005 #define	sd_print_retry_msg		ssd_print_retry_msg
1006 #define	sd_print_cmd_incomplete_msg	ssd_print_cmd_incomplete_msg
1007 #define	sd_pkt_reason_cmd_incomplete	ssd_pkt_reason_cmd_incomplete
1008 #define	sd_pkt_reason_cmd_tran_err	ssd_pkt_reason_cmd_tran_err
1009 #define	sd_pkt_reason_cmd_reset		ssd_pkt_reason_cmd_reset
1010 #define	sd_pkt_reason_cmd_aborted	ssd_pkt_reason_cmd_aborted
1011 #define	sd_pkt_reason_cmd_timeout	ssd_pkt_reason_cmd_timeout
1012 #define	sd_pkt_reason_cmd_unx_bus_free	ssd_pkt_reason_cmd_unx_bus_free
1013 #define	sd_pkt_reason_cmd_tag_reject	ssd_pkt_reason_cmd_tag_reject
1014 #define	sd_pkt_reason_default		ssd_pkt_reason_default
1015 #define	sd_reset_target			ssd_reset_target
1016 #define	sd_start_stop_unit_callback	ssd_start_stop_unit_callback
1017 #define	sd_start_stop_unit_task		ssd_start_stop_unit_task
1018 #define	sd_taskq_create			ssd_taskq_create
1019 #define	sd_taskq_delete			ssd_taskq_delete
1020 #define	sd_target_change_task		ssd_target_change_task
1021 #define	sd_log_lun_expansion_event	ssd_log_lun_expansion_event
1022 #define	sd_media_change_task		ssd_media_change_task
1023 #define	sd_handle_mchange		ssd_handle_mchange
1024 #define	sd_send_scsi_DOORLOCK		ssd_send_scsi_DOORLOCK
1025 #define	sd_send_scsi_READ_CAPACITY	ssd_send_scsi_READ_CAPACITY
1026 #define	sd_send_scsi_READ_CAPACITY_16	ssd_send_scsi_READ_CAPACITY_16
1027 #define	sd_send_scsi_GET_CONFIGURATION	ssd_send_scsi_GET_CONFIGURATION
1028 #define	sd_send_scsi_feature_GET_CONFIGURATION	\
1029 					sd_send_scsi_feature_GET_CONFIGURATION
1030 #define	sd_send_scsi_START_STOP_UNIT	ssd_send_scsi_START_STOP_UNIT
1031 #define	sd_send_scsi_INQUIRY		ssd_send_scsi_INQUIRY
1032 #define	sd_send_scsi_TEST_UNIT_READY	ssd_send_scsi_TEST_UNIT_READY
1033 #define	sd_send_scsi_PERSISTENT_RESERVE_IN	\
1034 					ssd_send_scsi_PERSISTENT_RESERVE_IN
1035 #define	sd_send_scsi_PERSISTENT_RESERVE_OUT	\
1036 					ssd_send_scsi_PERSISTENT_RESERVE_OUT
1037 #define	sd_send_scsi_SYNCHRONIZE_CACHE	ssd_send_scsi_SYNCHRONIZE_CACHE
1038 #define	sd_send_scsi_SYNCHRONIZE_CACHE_biodone	\
1039 					ssd_send_scsi_SYNCHRONIZE_CACHE_biodone
1040 #define	sd_send_scsi_MODE_SENSE		ssd_send_scsi_MODE_SENSE
1041 #define	sd_send_scsi_MODE_SELECT	ssd_send_scsi_MODE_SELECT
1042 #define	sd_send_scsi_RDWR		ssd_send_scsi_RDWR
1043 #define	sd_send_scsi_LOG_SENSE		ssd_send_scsi_LOG_SENSE
1044 #define	sd_alloc_rqs			ssd_alloc_rqs
1045 #define	sd_free_rqs			ssd_free_rqs
1046 #define	sd_dump_memory			ssd_dump_memory
1047 #define	sd_get_media_info		ssd_get_media_info
1048 #define	sd_get_media_info_ext		ssd_get_media_info_ext
1049 #define	sd_dkio_ctrl_info		ssd_dkio_ctrl_info
1050 #define	sd_nvpair_str_decode		ssd_nvpair_str_decode
1051 #define	sd_strtok_r			ssd_strtok_r
1052 #define	sd_set_properties		ssd_set_properties
1053 #define	sd_get_tunables_from_conf	ssd_get_tunables_from_conf
1054 #define	sd_setup_next_xfer		ssd_setup_next_xfer
1055 #define	sd_dkio_get_temp		ssd_dkio_get_temp
1056 #define	sd_check_mhd			ssd_check_mhd
1057 #define	sd_mhd_watch_cb			ssd_mhd_watch_cb
1058 #define	sd_mhd_watch_incomplete		ssd_mhd_watch_incomplete
1059 #define	sd_sname			ssd_sname
1060 #define	sd_mhd_resvd_recover		ssd_mhd_resvd_recover
1061 #define	sd_resv_reclaim_thread		ssd_resv_reclaim_thread
1062 #define	sd_take_ownership		ssd_take_ownership
1063 #define	sd_reserve_release		ssd_reserve_release
1064 #define	sd_rmv_resv_reclaim_req		ssd_rmv_resv_reclaim_req
1065 #define	sd_mhd_reset_notify_cb		ssd_mhd_reset_notify_cb
1066 #define	sd_persistent_reservation_in_read_keys	\
1067 					ssd_persistent_reservation_in_read_keys
1068 #define	sd_persistent_reservation_in_read_resv	\
1069 					ssd_persistent_reservation_in_read_resv
1070 #define	sd_mhdioc_takeown		ssd_mhdioc_takeown
1071 #define	sd_mhdioc_failfast		ssd_mhdioc_failfast
1072 #define	sd_mhdioc_release		ssd_mhdioc_release
1073 #define	sd_mhdioc_register_devid	ssd_mhdioc_register_devid
1074 #define	sd_mhdioc_inkeys		ssd_mhdioc_inkeys
1075 #define	sd_mhdioc_inresv		ssd_mhdioc_inresv
1076 #define	sr_change_blkmode		ssr_change_blkmode
1077 #define	sr_change_speed			ssr_change_speed
1078 #define	sr_atapi_change_speed		ssr_atapi_change_speed
1079 #define	sr_pause_resume			ssr_pause_resume
1080 #define	sr_play_msf			ssr_play_msf
1081 #define	sr_play_trkind			ssr_play_trkind
1082 #define	sr_read_all_subcodes		ssr_read_all_subcodes
1083 #define	sr_read_subchannel		ssr_read_subchannel
1084 #define	sr_read_tocentry		ssr_read_tocentry
1085 #define	sr_read_tochdr			ssr_read_tochdr
1086 #define	sr_read_cdda			ssr_read_cdda
1087 #define	sr_read_cdxa			ssr_read_cdxa
1088 #define	sr_read_mode1			ssr_read_mode1
1089 #define	sr_read_mode2			ssr_read_mode2
1090 #define	sr_read_cd_mode2		ssr_read_cd_mode2
1091 #define	sr_sector_mode			ssr_sector_mode
1092 #define	sr_eject			ssr_eject
1093 #define	sr_ejected			ssr_ejected
1094 #define	sr_check_wp			ssr_check_wp
1095 #define	sd_check_media			ssd_check_media
1096 #define	sd_media_watch_cb		ssd_media_watch_cb
1097 #define	sd_delayed_cv_broadcast		ssd_delayed_cv_broadcast
1098 #define	sr_volume_ctrl			ssr_volume_ctrl
1099 #define	sr_read_sony_session_offset	ssr_read_sony_session_offset
1100 #define	sd_log_page_supported		ssd_log_page_supported
1101 #define	sd_check_for_writable_cd	ssd_check_for_writable_cd
1102 #define	sd_wm_cache_constructor		ssd_wm_cache_constructor
1103 #define	sd_wm_cache_destructor		ssd_wm_cache_destructor
1104 #define	sd_range_lock			ssd_range_lock
1105 #define	sd_get_range			ssd_get_range
1106 #define	sd_free_inlist_wmap		ssd_free_inlist_wmap
1107 #define	sd_range_unlock			ssd_range_unlock
1108 #define	sd_read_modify_write_task	ssd_read_modify_write_task
1109 #define	sddump_do_read_of_rmw		ssddump_do_read_of_rmw
1110 
1111 #define	sd_iostart_chain		ssd_iostart_chain
1112 #define	sd_iodone_chain			ssd_iodone_chain
1113 #define	sd_initpkt_map			ssd_initpkt_map
1114 #define	sd_destroypkt_map		ssd_destroypkt_map
1115 #define	sd_chain_type_map		ssd_chain_type_map
1116 #define	sd_chain_index_map		ssd_chain_index_map
1117 
1118 #define	sd_failfast_flushctl		ssd_failfast_flushctl
1119 #define	sd_failfast_flushq		ssd_failfast_flushq
1120 #define	sd_failfast_flushq_callback	ssd_failfast_flushq_callback
1121 
1122 #define	sd_is_lsi			ssd_is_lsi
1123 #define	sd_tg_rdwr			ssd_tg_rdwr
1124 #define	sd_tg_getinfo			ssd_tg_getinfo
1125 #define	sd_rmw_msg_print_handler	ssd_rmw_msg_print_handler
1126 
1127 #endif	/* #if (defined(__fibre)) */
1128 
1129 
1130 int _init(void);
1131 int _fini(void);
1132 int _info(struct modinfo *modinfop);
1133 
1134 /*PRINTFLIKE3*/
1135 static void sd_log_trace(uint_t comp, struct sd_lun *un, const char *fmt, ...);
1136 /*PRINTFLIKE3*/
1137 static void sd_log_info(uint_t comp, struct sd_lun *un, const char *fmt, ...);
1138 /*PRINTFLIKE3*/
1139 static void sd_log_err(uint_t comp, struct sd_lun *un, const char *fmt, ...);
1140 
1141 static int sdprobe(dev_info_t *devi);
1142 static int sdinfo(dev_info_t *dip, ddi_info_cmd_t infocmd, void *arg,
1143     void **result);
1144 static int sd_prop_op(dev_t dev, dev_info_t *dip, ddi_prop_op_t prop_op,
1145     int mod_flags, char *name, caddr_t valuep, int *lengthp);
1146 
1147 /*
1148  * Smart probe for parallel scsi
1149  */
1150 static void sd_scsi_probe_cache_init(void);
1151 static void sd_scsi_probe_cache_fini(void);
1152 static void sd_scsi_clear_probe_cache(void);
1153 static int  sd_scsi_probe_with_cache(struct scsi_device *devp, int (*fn)());
1154 
1155 /*
1156  * Attached luns on target for parallel scsi
1157  */
1158 static void sd_scsi_target_lun_init(void);
1159 static void sd_scsi_target_lun_fini(void);
1160 static int  sd_scsi_get_target_lun_count(dev_info_t *dip, int target);
1161 static void sd_scsi_update_lun_on_target(dev_info_t *dip, int target, int flag);
1162 
1163 static int	sd_spin_up_unit(sd_ssc_t *ssc);
1164 
1165 /*
1166  * Using sd_ssc_init to establish sd_ssc_t struct
1167  * Using sd_ssc_send to send uscsi internal command
1168  * Using sd_ssc_fini to free sd_ssc_t struct
1169  */
1170 static sd_ssc_t *sd_ssc_init(struct sd_lun *un);
1171 static int sd_ssc_send(sd_ssc_t *ssc, struct uscsi_cmd *incmd,
1172     int flag, enum uio_seg dataspace, int path_flag);
1173 static void sd_ssc_fini(sd_ssc_t *ssc);
1174 
1175 /*
1176  * Using sd_ssc_assessment to set correct type-of-assessment
1177  * Using sd_ssc_post to post ereport & system log
1178  *       sd_ssc_post will call sd_ssc_print to print system log
1179  *       sd_ssc_post will call sd_ssd_ereport_post to post ereport
1180  */
1181 static void sd_ssc_assessment(sd_ssc_t *ssc,
1182     enum sd_type_assessment tp_assess);
1183 
1184 static void sd_ssc_post(sd_ssc_t *ssc, enum sd_driver_assessment sd_assess);
1185 static void sd_ssc_print(sd_ssc_t *ssc, int sd_severity);
1186 static void sd_ssc_ereport_post(sd_ssc_t *ssc,
1187     enum sd_driver_assessment drv_assess);
1188 
1189 /*
1190  * Using sd_ssc_set_info to mark an un-decodable-data error.
1191  * Using sd_ssc_extract_info to transfer information from internal
1192  *       data structures to sd_ssc_t.
1193  */
1194 static void sd_ssc_set_info(sd_ssc_t *ssc, int ssc_flags, uint_t comp,
1195     const char *fmt, ...);
1196 static void sd_ssc_extract_info(sd_ssc_t *ssc, struct sd_lun *un,
1197     struct scsi_pkt *pktp, struct buf *bp, struct sd_xbuf *xp);
1198 
1199 static int sd_send_scsi_cmd(dev_t dev, struct uscsi_cmd *incmd, int flag,
1200     enum uio_seg dataspace, int path_flag);
1201 
1202 #ifdef _LP64
1203 static void	sd_enable_descr_sense(sd_ssc_t *ssc);
1204 static void	sd_reenable_dsense_task(void *arg);
1205 #endif /* _LP64 */
1206 
1207 static void	sd_set_mmc_caps(sd_ssc_t *ssc);
1208 
1209 static void sd_read_unit_properties(struct sd_lun *un);
1210 static int  sd_process_sdconf_file(struct sd_lun *un);
1211 static void sd_nvpair_str_decode(struct sd_lun *un, char *nvpair_str);
1212 static char *sd_strtok_r(char *string, const char *sepset, char **lasts);
1213 static void sd_set_properties(struct sd_lun *un, char *name, char *value);
1214 static void sd_get_tunables_from_conf(struct sd_lun *un, int flags,
1215     int *data_list, sd_tunables *values);
1216 static void sd_process_sdconf_table(struct sd_lun *un);
1217 static int  sd_sdconf_id_match(struct sd_lun *un, char *id, int idlen);
1218 static int  sd_blank_cmp(struct sd_lun *un, char *id, int idlen);
1219 static int  sd_chk_vers1_data(struct sd_lun *un, int flags, int *prop_list,
1220 	int list_len, char *dataname_ptr);
1221 static void sd_set_vers1_properties(struct sd_lun *un, int flags,
1222     sd_tunables *prop_list);
1223 
1224 static void sd_register_devid(sd_ssc_t *ssc, dev_info_t *devi,
1225     int reservation_flag);
1226 static int  sd_get_devid(sd_ssc_t *ssc);
1227 static ddi_devid_t sd_create_devid(sd_ssc_t *ssc);
1228 static int  sd_write_deviceid(sd_ssc_t *ssc);
1229 static int  sd_get_devid_page(struct sd_lun *un, uchar_t *wwn, int *len);
1230 static int  sd_check_vpd_page_support(sd_ssc_t *ssc);
1231 
1232 static void sd_setup_pm(sd_ssc_t *ssc, dev_info_t *devi);
1233 static void sd_create_pm_components(dev_info_t *devi, struct sd_lun *un);
1234 
1235 static int  sd_ddi_suspend(dev_info_t *devi);
1236 static int  sd_ddi_resume(dev_info_t *devi);
1237 static int  sd_pm_state_change(struct sd_lun *un, int level, int flag);
1238 static int  sdpower(dev_info_t *devi, int component, int level);
1239 
1240 static int  sdattach(dev_info_t *devi, ddi_attach_cmd_t cmd);
1241 static int  sddetach(dev_info_t *devi, ddi_detach_cmd_t cmd);
1242 static int  sd_unit_attach(dev_info_t *devi);
1243 static int  sd_unit_detach(dev_info_t *devi);
1244 
1245 static void sd_set_unit_attributes(struct sd_lun *un, dev_info_t *devi);
1246 static void sd_create_errstats(struct sd_lun *un, int instance);
1247 static void sd_set_errstats(struct sd_lun *un);
1248 static void sd_set_pstats(struct sd_lun *un);
1249 
1250 static int  sddump(dev_t dev, caddr_t addr, daddr_t blkno, int nblk);
1251 static int  sd_scsi_poll(struct sd_lun *un, struct scsi_pkt *pkt);
1252 static int  sd_send_polled_RQS(struct sd_lun *un);
1253 static int  sd_ddi_scsi_poll(struct scsi_pkt *pkt);
1254 
1255 #if (defined(__fibre))
1256 /*
1257  * Event callbacks (photon)
1258  */
1259 static void sd_init_event_callbacks(struct sd_lun *un);
1260 static void  sd_event_callback(dev_info_t *, ddi_eventcookie_t, void *, void *);
1261 #endif
1262 
1263 /*
1264  * Defines for sd_cache_control
1265  */
1266 
1267 #define	SD_CACHE_ENABLE		1
1268 #define	SD_CACHE_DISABLE	0
1269 #define	SD_CACHE_NOCHANGE	-1
1270 
1271 static int   sd_cache_control(sd_ssc_t *ssc, int rcd_flag, int wce_flag);
1272 static int   sd_get_write_cache_enabled(sd_ssc_t *ssc, int *is_enabled);
1273 static void  sd_get_nv_sup(sd_ssc_t *ssc);
1274 static dev_t sd_make_device(dev_info_t *devi);
1275 static void  sd_check_solid_state(sd_ssc_t *ssc);
1276 
1277 static void  sd_update_block_info(struct sd_lun *un, uint32_t lbasize,
1278 	uint64_t capacity);
1279 
1280 /*
1281  * Driver entry point functions.
1282  */
1283 static int  sdopen(dev_t *dev_p, int flag, int otyp, cred_t *cred_p);
1284 static int  sdclose(dev_t dev, int flag, int otyp, cred_t *cred_p);
1285 static int  sd_ready_and_valid(sd_ssc_t *ssc, int part);
1286 
1287 static void sdmin(struct buf *bp);
1288 static int sdread(dev_t dev, struct uio *uio, cred_t *cred_p);
1289 static int sdwrite(dev_t dev, struct uio *uio, cred_t *cred_p);
1290 static int sdaread(dev_t dev, struct aio_req *aio, cred_t *cred_p);
1291 static int sdawrite(dev_t dev, struct aio_req *aio, cred_t *cred_p);
1292 
1293 static int sdstrategy(struct buf *bp);
1294 static int sdioctl(dev_t, int, intptr_t, int, cred_t *, int *);
1295 
1296 /*
1297  * Function prototypes for layering functions in the iostart chain.
1298  */
1299 static void sd_mapblockaddr_iostart(int index, struct sd_lun *un,
1300 	struct buf *bp);
1301 static void sd_mapblocksize_iostart(int index, struct sd_lun *un,
1302 	struct buf *bp);
1303 static void sd_checksum_iostart(int index, struct sd_lun *un, struct buf *bp);
1304 static void sd_checksum_uscsi_iostart(int index, struct sd_lun *un,
1305 	struct buf *bp);
1306 static void sd_pm_iostart(int index, struct sd_lun *un, struct buf *bp);
1307 static void sd_core_iostart(int index, struct sd_lun *un, struct buf *bp);
1308 
1309 /*
1310  * Function prototypes for layering functions in the iodone chain.
1311  */
1312 static void sd_buf_iodone(int index, struct sd_lun *un, struct buf *bp);
1313 static void sd_uscsi_iodone(int index, struct sd_lun *un, struct buf *bp);
1314 static void sd_mapblockaddr_iodone(int index, struct sd_lun *un,
1315 	struct buf *bp);
1316 static void sd_mapblocksize_iodone(int index, struct sd_lun *un,
1317 	struct buf *bp);
1318 static void sd_checksum_iodone(int index, struct sd_lun *un, struct buf *bp);
1319 static void sd_checksum_uscsi_iodone(int index, struct sd_lun *un,
1320 	struct buf *bp);
1321 static void sd_pm_iodone(int index, struct sd_lun *un, struct buf *bp);
1322 
1323 /*
1324  * Prototypes for functions to support buf(9S) based IO.
1325  */
1326 static void sd_xbuf_strategy(struct buf *bp, ddi_xbuf_t xp, void *arg);
1327 static int sd_initpkt_for_buf(struct buf *, struct scsi_pkt **);
1328 static void sd_destroypkt_for_buf(struct buf *);
1329 static int sd_setup_rw_pkt(struct sd_lun *un, struct scsi_pkt **pktpp,
1330 	struct buf *bp, int flags,
1331 	int (*callback)(caddr_t), caddr_t callback_arg,
1332 	diskaddr_t lba, uint32_t blockcount);
1333 static int sd_setup_next_rw_pkt(struct sd_lun *un, struct scsi_pkt *pktp,
1334 	struct buf *bp, diskaddr_t lba, uint32_t blockcount);
1335 
1336 /*
1337  * Prototypes for functions to support USCSI IO.
1338  */
1339 static int sd_uscsi_strategy(struct buf *bp);
1340 static int sd_initpkt_for_uscsi(struct buf *, struct scsi_pkt **);
1341 static void sd_destroypkt_for_uscsi(struct buf *);
1342 
1343 static void sd_xbuf_init(struct sd_lun *un, struct buf *bp, struct sd_xbuf *xp,
1344 	uchar_t chain_type, void *pktinfop);
1345 
1346 static int  sd_pm_entry(struct sd_lun *un);
1347 static void sd_pm_exit(struct sd_lun *un);
1348 
1349 static void sd_pm_idletimeout_handler(void *arg);
1350 
1351 /*
1352  * sd_core internal functions (used at the sd_core_io layer).
1353  */
1354 static void sd_add_buf_to_waitq(struct sd_lun *un, struct buf *bp);
1355 static void sdintr(struct scsi_pkt *pktp);
1356 static void sd_start_cmds(struct sd_lun *un, struct buf *immed_bp);
1357 
1358 static int sd_send_scsi_cmd(dev_t dev, struct uscsi_cmd *incmd, int flag,
1359 	enum uio_seg dataspace, int path_flag);
1360 
1361 static struct buf *sd_bioclone_alloc(struct buf *bp, size_t datalen,
1362 	daddr_t blkno, int (*func)(struct buf *));
1363 static struct buf *sd_shadow_buf_alloc(struct buf *bp, size_t datalen,
1364 	uint_t bflags, daddr_t blkno, int (*func)(struct buf *));
1365 static void sd_bioclone_free(struct buf *bp);
1366 static void sd_shadow_buf_free(struct buf *bp);
1367 
1368 static void sd_print_transport_rejected_message(struct sd_lun *un,
1369 	struct sd_xbuf *xp, int code);
1370 static void sd_print_incomplete_msg(struct sd_lun *un, struct buf *bp,
1371     void *arg, int code);
1372 static void sd_print_sense_failed_msg(struct sd_lun *un, struct buf *bp,
1373     void *arg, int code);
1374 static void sd_print_cmd_incomplete_msg(struct sd_lun *un, struct buf *bp,
1375     void *arg, int code);
1376 
1377 static void sd_retry_command(struct sd_lun *un, struct buf *bp,
1378 	int retry_check_flag,
1379 	void (*user_funcp)(struct sd_lun *un, struct buf *bp, void *argp,
1380 		int c),
1381 	void *user_arg, int failure_code,  clock_t retry_delay,
1382 	void (*statp)(kstat_io_t *));
1383 
1384 static void sd_set_retry_bp(struct sd_lun *un, struct buf *bp,
1385 	clock_t retry_delay, void (*statp)(kstat_io_t *));
1386 
1387 static void sd_send_request_sense_command(struct sd_lun *un, struct buf *bp,
1388 	struct scsi_pkt *pktp);
1389 static void sd_start_retry_command(void *arg);
1390 static void sd_start_direct_priority_command(void *arg);
1391 static void sd_return_failed_command(struct sd_lun *un, struct buf *bp,
1392 	int errcode);
1393 static void sd_return_failed_command_no_restart(struct sd_lun *un,
1394 	struct buf *bp, int errcode);
1395 static void sd_return_command(struct sd_lun *un, struct buf *bp);
1396 static void sd_sync_with_callback(struct sd_lun *un);
1397 static int sdrunout(caddr_t arg);
1398 
1399 static void sd_mark_rqs_busy(struct sd_lun *un, struct buf *bp);
1400 static struct buf *sd_mark_rqs_idle(struct sd_lun *un, struct sd_xbuf *xp);
1401 
1402 static void sd_reduce_throttle(struct sd_lun *un, int throttle_type);
1403 static void sd_restore_throttle(void *arg);
1404 
1405 static void sd_init_cdb_limits(struct sd_lun *un);
1406 
1407 static void sd_pkt_status_good(struct sd_lun *un, struct buf *bp,
1408 	struct sd_xbuf *xp, struct scsi_pkt *pktp);
1409 
1410 /*
1411  * Error handling functions
1412  */
1413 static void sd_pkt_status_check_condition(struct sd_lun *un, struct buf *bp,
1414 	struct sd_xbuf *xp, struct scsi_pkt *pktp);
1415 static void sd_pkt_status_busy(struct sd_lun *un, struct buf *bp,
1416 	struct sd_xbuf *xp, struct scsi_pkt *pktp);
1417 static void sd_pkt_status_reservation_conflict(struct sd_lun *un,
1418 	struct buf *bp, struct sd_xbuf *xp, struct scsi_pkt *pktp);
1419 static void sd_pkt_status_qfull(struct sd_lun *un, struct buf *bp,
1420 	struct sd_xbuf *xp, struct scsi_pkt *pktp);
1421 
1422 static void sd_handle_request_sense(struct sd_lun *un, struct buf *bp,
1423 	struct sd_xbuf *xp, struct scsi_pkt *pktp);
1424 static void sd_handle_auto_request_sense(struct sd_lun *un, struct buf *bp,
1425 	struct sd_xbuf *xp, struct scsi_pkt *pktp);
1426 static int sd_validate_sense_data(struct sd_lun *un, struct buf *bp,
1427 	struct sd_xbuf *xp, size_t actual_len);
1428 static void sd_decode_sense(struct sd_lun *un, struct buf *bp,
1429 	struct sd_xbuf *xp, struct scsi_pkt *pktp);
1430 
1431 static void sd_print_sense_msg(struct sd_lun *un, struct buf *bp,
1432 	void *arg, int code);
1433 
1434 static void sd_sense_key_no_sense(struct sd_lun *un, struct buf *bp,
1435 	struct sd_xbuf *xp, struct scsi_pkt *pktp);
1436 static void sd_sense_key_recoverable_error(struct sd_lun *un,
1437 	uint8_t *sense_datap,
1438 	struct buf *bp, struct sd_xbuf *xp, struct scsi_pkt *pktp);
1439 static void sd_sense_key_not_ready(struct sd_lun *un,
1440 	uint8_t *sense_datap,
1441 	struct buf *bp, struct sd_xbuf *xp, struct scsi_pkt *pktp);
1442 static void sd_sense_key_medium_or_hardware_error(struct sd_lun *un,
1443 	uint8_t *sense_datap,
1444 	struct buf *bp, struct sd_xbuf *xp, struct scsi_pkt *pktp);
1445 static void sd_sense_key_illegal_request(struct sd_lun *un, struct buf *bp,
1446 	struct sd_xbuf *xp, struct scsi_pkt *pktp);
1447 static void sd_sense_key_unit_attention(struct sd_lun *un,
1448 	uint8_t *sense_datap,
1449 	struct buf *bp, struct sd_xbuf *xp, struct scsi_pkt *pktp);
1450 static void sd_sense_key_fail_command(struct sd_lun *un, struct buf *bp,
1451 	struct sd_xbuf *xp, struct scsi_pkt *pktp);
1452 static void sd_sense_key_blank_check(struct sd_lun *un, struct buf *bp,
1453 	struct sd_xbuf *xp, struct scsi_pkt *pktp);
1454 static void sd_sense_key_aborted_command(struct sd_lun *un, struct buf *bp,
1455 	struct sd_xbuf *xp, struct scsi_pkt *pktp);
1456 static void sd_sense_key_default(struct sd_lun *un,
1457 	uint8_t *sense_datap,
1458 	struct buf *bp, struct sd_xbuf *xp, struct scsi_pkt *pktp);
1459 
1460 static void sd_print_retry_msg(struct sd_lun *un, struct buf *bp,
1461 	void *arg, int flag);
1462 
1463 static void sd_pkt_reason_cmd_incomplete(struct sd_lun *un, struct buf *bp,
1464 	struct sd_xbuf *xp, struct scsi_pkt *pktp);
1465 static void sd_pkt_reason_cmd_tran_err(struct sd_lun *un, struct buf *bp,
1466 	struct sd_xbuf *xp, struct scsi_pkt *pktp);
1467 static void sd_pkt_reason_cmd_reset(struct sd_lun *un, struct buf *bp,
1468 	struct sd_xbuf *xp, struct scsi_pkt *pktp);
1469 static void sd_pkt_reason_cmd_aborted(struct sd_lun *un, struct buf *bp,
1470 	struct sd_xbuf *xp, struct scsi_pkt *pktp);
1471 static void sd_pkt_reason_cmd_timeout(struct sd_lun *un, struct buf *bp,
1472 	struct sd_xbuf *xp, struct scsi_pkt *pktp);
1473 static void sd_pkt_reason_cmd_unx_bus_free(struct sd_lun *un, struct buf *bp,
1474 	struct sd_xbuf *xp, struct scsi_pkt *pktp);
1475 static void sd_pkt_reason_cmd_tag_reject(struct sd_lun *un, struct buf *bp,
1476 	struct sd_xbuf *xp, struct scsi_pkt *pktp);
1477 static void sd_pkt_reason_default(struct sd_lun *un, struct buf *bp,
1478 	struct sd_xbuf *xp, struct scsi_pkt *pktp);
1479 
1480 static void sd_reset_target(struct sd_lun *un, struct scsi_pkt *pktp);
1481 
1482 static void sd_start_stop_unit_callback(void *arg);
1483 static void sd_start_stop_unit_task(void *arg);
1484 
1485 static void sd_taskq_create(void);
1486 static void sd_taskq_delete(void);
1487 static void sd_target_change_task(void *arg);
1488 static void sd_log_lun_expansion_event(struct sd_lun *un, int km_flag);
1489 static void sd_media_change_task(void *arg);
1490 
1491 static int sd_handle_mchange(struct sd_lun *un);
1492 static int sd_send_scsi_DOORLOCK(sd_ssc_t *ssc, int flag, int path_flag);
1493 static int sd_send_scsi_READ_CAPACITY(sd_ssc_t *ssc, uint64_t *capp,
1494 	uint32_t *lbap, int path_flag);
1495 static int sd_send_scsi_READ_CAPACITY_16(sd_ssc_t *ssc, uint64_t *capp,
1496 	uint32_t *lbap, uint32_t *psp, int path_flag);
1497 static int sd_send_scsi_START_STOP_UNIT(sd_ssc_t *ssc, int pc_flag,
1498 	int flag, int path_flag);
1499 static int sd_send_scsi_INQUIRY(sd_ssc_t *ssc, uchar_t *bufaddr,
1500 	size_t buflen, uchar_t evpd, uchar_t page_code, size_t *residp);
1501 static int sd_send_scsi_TEST_UNIT_READY(sd_ssc_t *ssc, int flag);
1502 static int sd_send_scsi_PERSISTENT_RESERVE_IN(sd_ssc_t *ssc,
1503 	uchar_t usr_cmd, uint16_t data_len, uchar_t *data_bufp);
1504 static int sd_send_scsi_PERSISTENT_RESERVE_OUT(sd_ssc_t *ssc,
1505 	uchar_t usr_cmd, uchar_t *usr_bufp);
1506 static int sd_send_scsi_SYNCHRONIZE_CACHE(struct sd_lun *un,
1507 	struct dk_callback *dkc);
1508 static int sd_send_scsi_SYNCHRONIZE_CACHE_biodone(struct buf *bp);
1509 static int sd_send_scsi_GET_CONFIGURATION(sd_ssc_t *ssc,
1510 	struct uscsi_cmd *ucmdbuf, uchar_t *rqbuf, uint_t rqbuflen,
1511 	uchar_t *bufaddr, uint_t buflen, int path_flag);
1512 static int sd_send_scsi_feature_GET_CONFIGURATION(sd_ssc_t *ssc,
1513 	struct uscsi_cmd *ucmdbuf, uchar_t *rqbuf, uint_t rqbuflen,
1514 	uchar_t *bufaddr, uint_t buflen, char feature, int path_flag);
1515 static int sd_send_scsi_MODE_SENSE(sd_ssc_t *ssc, int cdbsize,
1516 	uchar_t *bufaddr, size_t buflen, uchar_t page_code, int path_flag);
1517 static int sd_send_scsi_MODE_SELECT(sd_ssc_t *ssc, int cdbsize,
1518 	uchar_t *bufaddr, size_t buflen, uchar_t save_page, int path_flag);
1519 static int sd_send_scsi_RDWR(sd_ssc_t *ssc, uchar_t cmd, void *bufaddr,
1520 	size_t buflen, daddr_t start_block, int path_flag);
1521 #define	sd_send_scsi_READ(ssc, bufaddr, buflen, start_block, path_flag)	\
1522 	sd_send_scsi_RDWR(ssc, SCMD_READ, bufaddr, buflen, start_block, \
1523 	path_flag)
1524 #define	sd_send_scsi_WRITE(ssc, bufaddr, buflen, start_block, path_flag)\
1525 	sd_send_scsi_RDWR(ssc, SCMD_WRITE, bufaddr, buflen, start_block,\
1526 	path_flag)
1527 
1528 static int sd_send_scsi_LOG_SENSE(sd_ssc_t *ssc, uchar_t *bufaddr,
1529 	uint16_t buflen, uchar_t page_code, uchar_t page_control,
1530 	uint16_t param_ptr, int path_flag);
1531 
1532 static int  sd_alloc_rqs(struct scsi_device *devp, struct sd_lun *un);
1533 static void sd_free_rqs(struct sd_lun *un);
1534 
1535 static void sd_dump_memory(struct sd_lun *un, uint_t comp, char *title,
1536 	uchar_t *data, int len, int fmt);
1537 static void sd_panic_for_res_conflict(struct sd_lun *un);
1538 
1539 /*
1540  * Disk Ioctl Function Prototypes
1541  */
1542 static int sd_get_media_info(dev_t dev, caddr_t arg, int flag);
1543 static int sd_get_media_info_ext(dev_t dev, caddr_t arg, int flag);
1544 static int sd_dkio_ctrl_info(dev_t dev, caddr_t arg, int flag);
1545 static int sd_dkio_get_temp(dev_t dev, caddr_t arg, int flag);
1546 
1547 /*
1548  * Multi-host Ioctl Prototypes
1549  */
1550 static int sd_check_mhd(dev_t dev, int interval);
1551 static int sd_mhd_watch_cb(caddr_t arg, struct scsi_watch_result *resultp);
1552 static void sd_mhd_watch_incomplete(struct sd_lun *un, struct scsi_pkt *pkt);
1553 static char *sd_sname(uchar_t status);
1554 static void sd_mhd_resvd_recover(void *arg);
1555 static void sd_resv_reclaim_thread();
1556 static int sd_take_ownership(dev_t dev, struct mhioctkown *p);
1557 static int sd_reserve_release(dev_t dev, int cmd);
1558 static void sd_rmv_resv_reclaim_req(dev_t dev);
1559 static void sd_mhd_reset_notify_cb(caddr_t arg);
1560 static int sd_persistent_reservation_in_read_keys(struct sd_lun *un,
1561 	mhioc_inkeys_t *usrp, int flag);
1562 static int sd_persistent_reservation_in_read_resv(struct sd_lun *un,
1563 	mhioc_inresvs_t *usrp, int flag);
1564 static int sd_mhdioc_takeown(dev_t dev, caddr_t arg, int flag);
1565 static int sd_mhdioc_failfast(dev_t dev, caddr_t arg, int flag);
1566 static int sd_mhdioc_release(dev_t dev);
1567 static int sd_mhdioc_register_devid(dev_t dev);
1568 static int sd_mhdioc_inkeys(dev_t dev, caddr_t arg, int flag);
1569 static int sd_mhdioc_inresv(dev_t dev, caddr_t arg, int flag);
1570 
1571 /*
1572  * SCSI removable prototypes
1573  */
1574 static int sr_change_blkmode(dev_t dev, int cmd, intptr_t data, int flag);
1575 static int sr_change_speed(dev_t dev, int cmd, intptr_t data, int flag);
1576 static int sr_atapi_change_speed(dev_t dev, int cmd, intptr_t data, int flag);
1577 static int sr_pause_resume(dev_t dev, int mode);
1578 static int sr_play_msf(dev_t dev, caddr_t data, int flag);
1579 static int sr_play_trkind(dev_t dev, caddr_t data, int flag);
1580 static int sr_read_all_subcodes(dev_t dev, caddr_t data, int flag);
1581 static int sr_read_subchannel(dev_t dev, caddr_t data, int flag);
1582 static int sr_read_tocentry(dev_t dev, caddr_t data, int flag);
1583 static int sr_read_tochdr(dev_t dev, caddr_t data, int flag);
1584 static int sr_read_cdda(dev_t dev, caddr_t data, int flag);
1585 static int sr_read_cdxa(dev_t dev, caddr_t data, int flag);
1586 static int sr_read_mode1(dev_t dev, caddr_t data, int flag);
1587 static int sr_read_mode2(dev_t dev, caddr_t data, int flag);
1588 static int sr_read_cd_mode2(dev_t dev, caddr_t data, int flag);
1589 static int sr_sector_mode(dev_t dev, uint32_t blksize);
1590 static int sr_eject(dev_t dev);
1591 static void sr_ejected(register struct sd_lun *un);
1592 static int sr_check_wp(dev_t dev);
1593 static int sd_check_media(dev_t dev, enum dkio_state state);
1594 static int sd_media_watch_cb(caddr_t arg, struct scsi_watch_result *resultp);
1595 static void sd_delayed_cv_broadcast(void *arg);
1596 static int sr_volume_ctrl(dev_t dev, caddr_t data, int flag);
1597 static int sr_read_sony_session_offset(dev_t dev, caddr_t data, int flag);
1598 
1599 static int sd_log_page_supported(sd_ssc_t *ssc, int log_page);
1600 
1601 /*
1602  * Function Prototype for the non-512 support (DVDRAM, MO etc.) functions.
1603  */
1604 static void sd_check_for_writable_cd(sd_ssc_t *ssc, int path_flag);
1605 static int sd_wm_cache_constructor(void *wm, void *un, int flags);
1606 static void sd_wm_cache_destructor(void *wm, void *un);
1607 static struct sd_w_map *sd_range_lock(struct sd_lun *un, daddr_t startb,
1608 	daddr_t endb, ushort_t typ);
1609 static struct sd_w_map *sd_get_range(struct sd_lun *un, daddr_t startb,
1610 	daddr_t endb);
1611 static void sd_free_inlist_wmap(struct sd_lun *un, struct sd_w_map *wmp);
1612 static void sd_range_unlock(struct sd_lun *un, struct sd_w_map *wm);
1613 static void sd_read_modify_write_task(void * arg);
1614 static int
1615 sddump_do_read_of_rmw(struct sd_lun *un, uint64_t blkno, uint64_t nblk,
1616 	struct buf **bpp);
1617 
1618 
1619 /*
1620  * Function prototypes for failfast support.
1621  */
1622 static void sd_failfast_flushq(struct sd_lun *un);
1623 static int sd_failfast_flushq_callback(struct buf *bp);
1624 
1625 /*
1626  * Function prototypes to check for lsi devices
1627  */
1628 static void sd_is_lsi(struct sd_lun *un);
1629 
1630 /*
1631  * Function prototypes for partial DMA support
1632  */
1633 static int sd_setup_next_xfer(struct sd_lun *un, struct buf *bp,
1634 		struct scsi_pkt *pkt, struct sd_xbuf *xp);
1635 
1636 
1637 /* Function prototypes for cmlb */
1638 static int sd_tg_rdwr(dev_info_t *devi, uchar_t cmd, void *bufaddr,
1639     diskaddr_t start_block, size_t reqlength, void *tg_cookie);
1640 
1641 static int sd_tg_getinfo(dev_info_t *devi, int cmd, void *arg, void *tg_cookie);
1642 
1643 /*
1644  * For printing RMW warning message timely
1645  */
1646 static void sd_rmw_msg_print_handler(void *arg);
1647 
1648 /*
1649  * Constants for failfast support:
1650  *
1651  * SD_FAILFAST_INACTIVE: Instance is currently in a normal state, with NO
1652  * failfast processing being performed.
1653  *
1654  * SD_FAILFAST_ACTIVE: Instance is in the failfast state and is performing
1655  * failfast processing on all bufs with B_FAILFAST set.
1656  */
1657 
1658 #define	SD_FAILFAST_INACTIVE		0
1659 #define	SD_FAILFAST_ACTIVE		1
1660 
1661 /*
1662  * Bitmask to control behavior of buf(9S) flushes when a transition to
1663  * the failfast state occurs. Optional bits include:
1664  *
1665  * SD_FAILFAST_FLUSH_ALL_BUFS: When set, flush ALL bufs including those that
1666  * do NOT have B_FAILFAST set. When clear, only bufs with B_FAILFAST will
1667  * be flushed.
1668  *
1669  * SD_FAILFAST_FLUSH_ALL_QUEUES: When set, flush any/all other queues in the
1670  * driver, in addition to the regular wait queue. This includes the xbuf
1671  * queues. When clear, only the driver's wait queue will be flushed.
1672  */
1673 #define	SD_FAILFAST_FLUSH_ALL_BUFS	0x01
1674 #define	SD_FAILFAST_FLUSH_ALL_QUEUES	0x02
1675 
1676 /*
1677  * The default behavior is to only flush bufs that have B_FAILFAST set, but
1678  * to flush all queues within the driver.
1679  */
1680 static int sd_failfast_flushctl = SD_FAILFAST_FLUSH_ALL_QUEUES;
1681 
1682 
1683 /*
1684  * SD Testing Fault Injection
1685  */
1686 #ifdef SD_FAULT_INJECTION
1687 static void sd_faultinjection_ioctl(int cmd, intptr_t arg, struct sd_lun *un);
1688 static void sd_faultinjection(struct scsi_pkt *pktp);
1689 static void sd_injection_log(char *buf, struct sd_lun *un);
1690 #endif
1691 
1692 /*
1693  * Device driver ops vector
1694  */
1695 static struct cb_ops sd_cb_ops = {
1696 	sdopen,			/* open */
1697 	sdclose,		/* close */
1698 	sdstrategy,		/* strategy */
1699 	nodev,			/* print */
1700 	sddump,			/* dump */
1701 	sdread,			/* read */
1702 	sdwrite,		/* write */
1703 	sdioctl,		/* ioctl */
1704 	nodev,			/* devmap */
1705 	nodev,			/* mmap */
1706 	nodev,			/* segmap */
1707 	nochpoll,		/* poll */
1708 	sd_prop_op,		/* cb_prop_op */
1709 	0,			/* streamtab  */
1710 	D_64BIT | D_MP | D_NEW | D_HOTPLUG, /* Driver compatibility flags */
1711 	CB_REV,			/* cb_rev */
1712 	sdaread, 		/* async I/O read entry point */
1713 	sdawrite		/* async I/O write entry point */
1714 };
1715 
1716 struct dev_ops sd_ops = {
1717 	DEVO_REV,		/* devo_rev, */
1718 	0,			/* refcnt  */
1719 	sdinfo,			/* info */
1720 	nulldev,		/* identify */
1721 	sdprobe,		/* probe */
1722 	sdattach,		/* attach */
1723 	sddetach,		/* detach */
1724 	nodev,			/* reset */
1725 	&sd_cb_ops,		/* driver operations */
1726 	NULL,			/* bus operations */
1727 	sdpower,		/* power */
1728 	ddi_quiesce_not_needed,		/* quiesce */
1729 };
1730 
1731 /*
1732  * This is the loadable module wrapper.
1733  */
1734 #include <sys/modctl.h>
1735 
1736 #ifndef XPV_HVM_DRIVER
1737 static struct modldrv modldrv = {
1738 	&mod_driverops,		/* Type of module. This one is a driver */
1739 	SD_MODULE_NAME,		/* Module name. */
1740 	&sd_ops			/* driver ops */
1741 };
1742 
1743 static struct modlinkage modlinkage = {
1744 	MODREV_1, &modldrv, NULL
1745 };
1746 
1747 #else /* XPV_HVM_DRIVER */
1748 static struct modlmisc modlmisc = {
1749 	&mod_miscops,		/* Type of module. This one is a misc */
1750 	"HVM " SD_MODULE_NAME,		/* Module name. */
1751 };
1752 
1753 static struct modlinkage modlinkage = {
1754 	MODREV_1, &modlmisc, NULL
1755 };
1756 
1757 #endif /* XPV_HVM_DRIVER */
1758 
1759 static cmlb_tg_ops_t sd_tgops = {
1760 	TG_DK_OPS_VERSION_1,
1761 	sd_tg_rdwr,
1762 	sd_tg_getinfo
1763 };
1764 
1765 static struct scsi_asq_key_strings sd_additional_codes[] = {
1766 	0x81, 0, "Logical Unit is Reserved",
1767 	0x85, 0, "Audio Address Not Valid",
1768 	0xb6, 0, "Media Load Mechanism Failed",
1769 	0xB9, 0, "Audio Play Operation Aborted",
1770 	0xbf, 0, "Buffer Overflow for Read All Subcodes Command",
1771 	0x53, 2, "Medium removal prevented",
1772 	0x6f, 0, "Authentication failed during key exchange",
1773 	0x6f, 1, "Key not present",
1774 	0x6f, 2, "Key not established",
1775 	0x6f, 3, "Read without proper authentication",
1776 	0x6f, 4, "Mismatched region to this logical unit",
1777 	0x6f, 5, "Region reset count error",
1778 	0xffff, 0x0, NULL
1779 };
1780 
1781 
1782 /*
1783  * Struct for passing printing information for sense data messages
1784  */
1785 struct sd_sense_info {
1786 	int	ssi_severity;
1787 	int	ssi_pfa_flag;
1788 };
1789 
1790 /*
1791  * Table of function pointers for iostart-side routines. Separate "chains"
1792  * of layered function calls are formed by placing the function pointers
1793  * sequentially in the desired order. Functions are called according to an
1794  * incrementing table index ordering. The last function in each chain must
1795  * be sd_core_iostart(). The corresponding iodone-side routines are expected
1796  * in the sd_iodone_chain[] array.
1797  *
1798  * Note: It may seem more natural to organize both the iostart and iodone
1799  * functions together, into an array of structures (or some similar
1800  * organization) with a common index, rather than two separate arrays which
1801  * must be maintained in synchronization. The purpose of this division is
1802  * to achieve improved performance: individual arrays allows for more
1803  * effective cache line utilization on certain platforms.
1804  */
1805 
1806 typedef void (*sd_chain_t)(int index, struct sd_lun *un, struct buf *bp);
1807 
1808 
1809 static sd_chain_t sd_iostart_chain[] = {
1810 
1811 	/* Chain for buf IO for disk drive targets (PM enabled) */
1812 	sd_mapblockaddr_iostart,	/* Index: 0 */
1813 	sd_pm_iostart,			/* Index: 1 */
1814 	sd_core_iostart,		/* Index: 2 */
1815 
1816 	/* Chain for buf IO for disk drive targets (PM disabled) */
1817 	sd_mapblockaddr_iostart,	/* Index: 3 */
1818 	sd_core_iostart,		/* Index: 4 */
1819 
1820 	/*
1821 	 * Chain for buf IO for removable-media or large sector size
1822 	 * disk drive targets with RMW needed (PM enabled)
1823 	 */
1824 	sd_mapblockaddr_iostart,	/* Index: 5 */
1825 	sd_mapblocksize_iostart,	/* Index: 6 */
1826 	sd_pm_iostart,			/* Index: 7 */
1827 	sd_core_iostart,		/* Index: 8 */
1828 
1829 	/*
1830 	 * Chain for buf IO for removable-media or large sector size
1831 	 * disk drive targets with RMW needed (PM disabled)
1832 	 */
1833 	sd_mapblockaddr_iostart,	/* Index: 9 */
1834 	sd_mapblocksize_iostart,	/* Index: 10 */
1835 	sd_core_iostart,		/* Index: 11 */
1836 
1837 	/* Chain for buf IO for disk drives with checksumming (PM enabled) */
1838 	sd_mapblockaddr_iostart,	/* Index: 12 */
1839 	sd_checksum_iostart,		/* Index: 13 */
1840 	sd_pm_iostart,			/* Index: 14 */
1841 	sd_core_iostart,		/* Index: 15 */
1842 
1843 	/* Chain for buf IO for disk drives with checksumming (PM disabled) */
1844 	sd_mapblockaddr_iostart,	/* Index: 16 */
1845 	sd_checksum_iostart,		/* Index: 17 */
1846 	sd_core_iostart,		/* Index: 18 */
1847 
1848 	/* Chain for USCSI commands (all targets) */
1849 	sd_pm_iostart,			/* Index: 19 */
1850 	sd_core_iostart,		/* Index: 20 */
1851 
1852 	/* Chain for checksumming USCSI commands (all targets) */
1853 	sd_checksum_uscsi_iostart,	/* Index: 21 */
1854 	sd_pm_iostart,			/* Index: 22 */
1855 	sd_core_iostart,		/* Index: 23 */
1856 
1857 	/* Chain for "direct" USCSI commands (all targets) */
1858 	sd_core_iostart,		/* Index: 24 */
1859 
1860 	/* Chain for "direct priority" USCSI commands (all targets) */
1861 	sd_core_iostart,		/* Index: 25 */
1862 
1863 	/*
1864 	 * Chain for buf IO for large sector size disk drive targets
1865 	 * with RMW needed with checksumming (PM enabled)
1866 	 */
1867 	sd_mapblockaddr_iostart,	/* Index: 26 */
1868 	sd_mapblocksize_iostart,	/* Index: 27 */
1869 	sd_checksum_iostart,		/* Index: 28 */
1870 	sd_pm_iostart,			/* Index: 29 */
1871 	sd_core_iostart,		/* Index: 30 */
1872 
1873 	/*
1874 	 * Chain for buf IO for large sector size disk drive targets
1875 	 * with RMW needed with checksumming (PM disabled)
1876 	 */
1877 	sd_mapblockaddr_iostart,	/* Index: 31 */
1878 	sd_mapblocksize_iostart,	/* Index: 32 */
1879 	sd_checksum_iostart,		/* Index: 33 */
1880 	sd_core_iostart,		/* Index: 34 */
1881 
1882 };
1883 
1884 /*
1885  * Macros to locate the first function of each iostart chain in the
1886  * sd_iostart_chain[] array. These are located by the index in the array.
1887  */
1888 #define	SD_CHAIN_DISK_IOSTART			0
1889 #define	SD_CHAIN_DISK_IOSTART_NO_PM		3
1890 #define	SD_CHAIN_MSS_DISK_IOSTART		5
1891 #define	SD_CHAIN_RMMEDIA_IOSTART		5
1892 #define	SD_CHAIN_MSS_DISK_IOSTART_NO_PM		9
1893 #define	SD_CHAIN_RMMEDIA_IOSTART_NO_PM		9
1894 #define	SD_CHAIN_CHKSUM_IOSTART			12
1895 #define	SD_CHAIN_CHKSUM_IOSTART_NO_PM		16
1896 #define	SD_CHAIN_USCSI_CMD_IOSTART		19
1897 #define	SD_CHAIN_USCSI_CHKSUM_IOSTART		21
1898 #define	SD_CHAIN_DIRECT_CMD_IOSTART		24
1899 #define	SD_CHAIN_PRIORITY_CMD_IOSTART		25
1900 #define	SD_CHAIN_MSS_CHKSUM_IOSTART		26
1901 #define	SD_CHAIN_MSS_CHKSUM_IOSTART_NO_PM	31
1902 
1903 
1904 /*
1905  * Table of function pointers for the iodone-side routines for the driver-
1906  * internal layering mechanism.  The calling sequence for iodone routines
1907  * uses a decrementing table index, so the last routine called in a chain
1908  * must be at the lowest array index location for that chain.  The last
1909  * routine for each chain must be either sd_buf_iodone() (for buf(9S) IOs)
1910  * or sd_uscsi_iodone() (for uscsi IOs).  Other than this, the ordering
1911  * of the functions in an iodone side chain must correspond to the ordering
1912  * of the iostart routines for that chain.  Note that there is no iodone
1913  * side routine that corresponds to sd_core_iostart(), so there is no
1914  * entry in the table for this.
1915  */
1916 
1917 static sd_chain_t sd_iodone_chain[] = {
1918 
1919 	/* Chain for buf IO for disk drive targets (PM enabled) */
1920 	sd_buf_iodone,			/* Index: 0 */
1921 	sd_mapblockaddr_iodone,		/* Index: 1 */
1922 	sd_pm_iodone,			/* Index: 2 */
1923 
1924 	/* Chain for buf IO for disk drive targets (PM disabled) */
1925 	sd_buf_iodone,			/* Index: 3 */
1926 	sd_mapblockaddr_iodone,		/* Index: 4 */
1927 
1928 	/*
1929 	 * Chain for buf IO for removable-media or large sector size
1930 	 * disk drive targets with RMW needed (PM enabled)
1931 	 */
1932 	sd_buf_iodone,			/* Index: 5 */
1933 	sd_mapblockaddr_iodone,		/* Index: 6 */
1934 	sd_mapblocksize_iodone,		/* Index: 7 */
1935 	sd_pm_iodone,			/* Index: 8 */
1936 
1937 	/*
1938 	 * Chain for buf IO for removable-media or large sector size
1939 	 * disk drive targets with RMW needed (PM disabled)
1940 	 */
1941 	sd_buf_iodone,			/* Index: 9 */
1942 	sd_mapblockaddr_iodone,		/* Index: 10 */
1943 	sd_mapblocksize_iodone,		/* Index: 11 */
1944 
1945 	/* Chain for buf IO for disk drives with checksumming (PM enabled) */
1946 	sd_buf_iodone,			/* Index: 12 */
1947 	sd_mapblockaddr_iodone,		/* Index: 13 */
1948 	sd_checksum_iodone,		/* Index: 14 */
1949 	sd_pm_iodone,			/* Index: 15 */
1950 
1951 	/* Chain for buf IO for disk drives with checksumming (PM disabled) */
1952 	sd_buf_iodone,			/* Index: 16 */
1953 	sd_mapblockaddr_iodone,		/* Index: 17 */
1954 	sd_checksum_iodone,		/* Index: 18 */
1955 
1956 	/* Chain for USCSI commands (non-checksum targets) */
1957 	sd_uscsi_iodone,		/* Index: 19 */
1958 	sd_pm_iodone,			/* Index: 20 */
1959 
1960 	/* Chain for USCSI commands (checksum targets) */
1961 	sd_uscsi_iodone,		/* Index: 21 */
1962 	sd_checksum_uscsi_iodone,	/* Index: 22 */
1963 	sd_pm_iodone,			/* Index: 22 */
1964 
1965 	/* Chain for "direct" USCSI commands (all targets) */
1966 	sd_uscsi_iodone,		/* Index: 24 */
1967 
1968 	/* Chain for "direct priority" USCSI commands (all targets) */
1969 	sd_uscsi_iodone,		/* Index: 25 */
1970 
1971 	/*
1972 	 * Chain for buf IO for large sector size disk drive targets
1973 	 * with checksumming (PM enabled)
1974 	 */
1975 	sd_buf_iodone,			/* Index: 26 */
1976 	sd_mapblockaddr_iodone,		/* Index: 27 */
1977 	sd_mapblocksize_iodone,		/* Index: 28 */
1978 	sd_checksum_iodone,		/* Index: 29 */
1979 	sd_pm_iodone,			/* Index: 30 */
1980 
1981 	/*
1982 	 * Chain for buf IO for large sector size disk drive targets
1983 	 * with checksumming (PM disabled)
1984 	 */
1985 	sd_buf_iodone,			/* Index: 31 */
1986 	sd_mapblockaddr_iodone,		/* Index: 32 */
1987 	sd_mapblocksize_iodone,		/* Index: 33 */
1988 	sd_checksum_iodone,		/* Index: 34 */
1989 };
1990 
1991 
1992 /*
1993  * Macros to locate the "first" function in the sd_iodone_chain[] array for
1994  * each iodone-side chain. These are located by the array index, but as the
1995  * iodone side functions are called in a decrementing-index order, the
1996  * highest index number in each chain must be specified (as these correspond
1997  * to the first function in the iodone chain that will be called by the core
1998  * at IO completion time).
1999  */
2000 
2001 #define	SD_CHAIN_DISK_IODONE			2
2002 #define	SD_CHAIN_DISK_IODONE_NO_PM		4
2003 #define	SD_CHAIN_RMMEDIA_IODONE			8
2004 #define	SD_CHAIN_MSS_DISK_IODONE		8
2005 #define	SD_CHAIN_RMMEDIA_IODONE_NO_PM		11
2006 #define	SD_CHAIN_MSS_DISK_IODONE_NO_PM		11
2007 #define	SD_CHAIN_CHKSUM_IODONE			15
2008 #define	SD_CHAIN_CHKSUM_IODONE_NO_PM		18
2009 #define	SD_CHAIN_USCSI_CMD_IODONE		20
2010 #define	SD_CHAIN_USCSI_CHKSUM_IODONE		22
2011 #define	SD_CHAIN_DIRECT_CMD_IODONE		24
2012 #define	SD_CHAIN_PRIORITY_CMD_IODONE		25
2013 #define	SD_CHAIN_MSS_CHKSUM_IODONE		30
2014 #define	SD_CHAIN_MSS_CHKSUM_IODONE_NO_PM	34
2015 
2016 
2017 
2018 /*
2019  * Array to map a layering chain index to the appropriate initpkt routine.
2020  * The redundant entries are present so that the index used for accessing
2021  * the above sd_iostart_chain and sd_iodone_chain tables can be used directly
2022  * with this table as well.
2023  */
2024 typedef int (*sd_initpkt_t)(struct buf *, struct scsi_pkt **);
2025 
2026 static sd_initpkt_t	sd_initpkt_map[] = {
2027 
2028 	/* Chain for buf IO for disk drive targets (PM enabled) */
2029 	sd_initpkt_for_buf,		/* Index: 0 */
2030 	sd_initpkt_for_buf,		/* Index: 1 */
2031 	sd_initpkt_for_buf,		/* Index: 2 */
2032 
2033 	/* Chain for buf IO for disk drive targets (PM disabled) */
2034 	sd_initpkt_for_buf,		/* Index: 3 */
2035 	sd_initpkt_for_buf,		/* Index: 4 */
2036 
2037 	/*
2038 	 * Chain for buf IO for removable-media or large sector size
2039 	 * disk drive targets (PM enabled)
2040 	 */
2041 	sd_initpkt_for_buf,		/* Index: 5 */
2042 	sd_initpkt_for_buf,		/* Index: 6 */
2043 	sd_initpkt_for_buf,		/* Index: 7 */
2044 	sd_initpkt_for_buf,		/* Index: 8 */
2045 
2046 	/*
2047 	 * Chain for buf IO for removable-media or large sector size
2048 	 * disk drive targets (PM disabled)
2049 	 */
2050 	sd_initpkt_for_buf,		/* Index: 9 */
2051 	sd_initpkt_for_buf,		/* Index: 10 */
2052 	sd_initpkt_for_buf,		/* Index: 11 */
2053 
2054 	/* Chain for buf IO for disk drives with checksumming (PM enabled) */
2055 	sd_initpkt_for_buf,		/* Index: 12 */
2056 	sd_initpkt_for_buf,		/* Index: 13 */
2057 	sd_initpkt_for_buf,		/* Index: 14 */
2058 	sd_initpkt_for_buf,		/* Index: 15 */
2059 
2060 	/* Chain for buf IO for disk drives with checksumming (PM disabled) */
2061 	sd_initpkt_for_buf,		/* Index: 16 */
2062 	sd_initpkt_for_buf,		/* Index: 17 */
2063 	sd_initpkt_for_buf,		/* Index: 18 */
2064 
2065 	/* Chain for USCSI commands (non-checksum targets) */
2066 	sd_initpkt_for_uscsi,		/* Index: 19 */
2067 	sd_initpkt_for_uscsi,		/* Index: 20 */
2068 
2069 	/* Chain for USCSI commands (checksum targets) */
2070 	sd_initpkt_for_uscsi,		/* Index: 21 */
2071 	sd_initpkt_for_uscsi,		/* Index: 22 */
2072 	sd_initpkt_for_uscsi,		/* Index: 22 */
2073 
2074 	/* Chain for "direct" USCSI commands (all targets) */
2075 	sd_initpkt_for_uscsi,		/* Index: 24 */
2076 
2077 	/* Chain for "direct priority" USCSI commands (all targets) */
2078 	sd_initpkt_for_uscsi,		/* Index: 25 */
2079 
2080 	/*
2081 	 * Chain for buf IO for large sector size disk drive targets
2082 	 * with checksumming (PM enabled)
2083 	 */
2084 	sd_initpkt_for_buf,		/* Index: 26 */
2085 	sd_initpkt_for_buf,		/* Index: 27 */
2086 	sd_initpkt_for_buf,		/* Index: 28 */
2087 	sd_initpkt_for_buf,		/* Index: 29 */
2088 	sd_initpkt_for_buf,		/* Index: 30 */
2089 
2090 	/*
2091 	 * Chain for buf IO for large sector size disk drive targets
2092 	 * with checksumming (PM disabled)
2093 	 */
2094 	sd_initpkt_for_buf,		/* Index: 31 */
2095 	sd_initpkt_for_buf,		/* Index: 32 */
2096 	sd_initpkt_for_buf,		/* Index: 33 */
2097 	sd_initpkt_for_buf,		/* Index: 34 */
2098 };
2099 
2100 
2101 /*
2102  * Array to map a layering chain index to the appropriate destroypktpkt routine.
2103  * The redundant entries are present so that the index used for accessing
2104  * the above sd_iostart_chain and sd_iodone_chain tables can be used directly
2105  * with this table as well.
2106  */
2107 typedef void (*sd_destroypkt_t)(struct buf *);
2108 
2109 static sd_destroypkt_t	sd_destroypkt_map[] = {
2110 
2111 	/* Chain for buf IO for disk drive targets (PM enabled) */
2112 	sd_destroypkt_for_buf,		/* Index: 0 */
2113 	sd_destroypkt_for_buf,		/* Index: 1 */
2114 	sd_destroypkt_for_buf,		/* Index: 2 */
2115 
2116 	/* Chain for buf IO for disk drive targets (PM disabled) */
2117 	sd_destroypkt_for_buf,		/* Index: 3 */
2118 	sd_destroypkt_for_buf,		/* Index: 4 */
2119 
2120 	/*
2121 	 * Chain for buf IO for removable-media or large sector size
2122 	 * disk drive targets (PM enabled)
2123 	 */
2124 	sd_destroypkt_for_buf,		/* Index: 5 */
2125 	sd_destroypkt_for_buf,		/* Index: 6 */
2126 	sd_destroypkt_for_buf,		/* Index: 7 */
2127 	sd_destroypkt_for_buf,		/* Index: 8 */
2128 
2129 	/*
2130 	 * Chain for buf IO for removable-media or large sector size
2131 	 * disk drive targets (PM disabled)
2132 	 */
2133 	sd_destroypkt_for_buf,		/* Index: 9 */
2134 	sd_destroypkt_for_buf,		/* Index: 10 */
2135 	sd_destroypkt_for_buf,		/* Index: 11 */
2136 
2137 	/* Chain for buf IO for disk drives with checksumming (PM enabled) */
2138 	sd_destroypkt_for_buf,		/* Index: 12 */
2139 	sd_destroypkt_for_buf,		/* Index: 13 */
2140 	sd_destroypkt_for_buf,		/* Index: 14 */
2141 	sd_destroypkt_for_buf,		/* Index: 15 */
2142 
2143 	/* Chain for buf IO for disk drives with checksumming (PM disabled) */
2144 	sd_destroypkt_for_buf,		/* Index: 16 */
2145 	sd_destroypkt_for_buf,		/* Index: 17 */
2146 	sd_destroypkt_for_buf,		/* Index: 18 */
2147 
2148 	/* Chain for USCSI commands (non-checksum targets) */
2149 	sd_destroypkt_for_uscsi,	/* Index: 19 */
2150 	sd_destroypkt_for_uscsi,	/* Index: 20 */
2151 
2152 	/* Chain for USCSI commands (checksum targets) */
2153 	sd_destroypkt_for_uscsi,	/* Index: 21 */
2154 	sd_destroypkt_for_uscsi,	/* Index: 22 */
2155 	sd_destroypkt_for_uscsi,	/* Index: 22 */
2156 
2157 	/* Chain for "direct" USCSI commands (all targets) */
2158 	sd_destroypkt_for_uscsi,	/* Index: 24 */
2159 
2160 	/* Chain for "direct priority" USCSI commands (all targets) */
2161 	sd_destroypkt_for_uscsi,	/* Index: 25 */
2162 
2163 	/*
2164 	 * Chain for buf IO for large sector size disk drive targets
2165 	 * with checksumming (PM disabled)
2166 	 */
2167 	sd_destroypkt_for_buf,		/* Index: 26 */
2168 	sd_destroypkt_for_buf,		/* Index: 27 */
2169 	sd_destroypkt_for_buf,		/* Index: 28 */
2170 	sd_destroypkt_for_buf,		/* Index: 29 */
2171 	sd_destroypkt_for_buf,		/* Index: 30 */
2172 
2173 	/*
2174 	 * Chain for buf IO for large sector size disk drive targets
2175 	 * with checksumming (PM enabled)
2176 	 */
2177 	sd_destroypkt_for_buf,		/* Index: 31 */
2178 	sd_destroypkt_for_buf,		/* Index: 32 */
2179 	sd_destroypkt_for_buf,		/* Index: 33 */
2180 	sd_destroypkt_for_buf,		/* Index: 34 */
2181 };
2182 
2183 
2184 
2185 /*
2186  * Array to map a layering chain index to the appropriate chain "type".
2187  * The chain type indicates a specific property/usage of the chain.
2188  * The redundant entries are present so that the index used for accessing
2189  * the above sd_iostart_chain and sd_iodone_chain tables can be used directly
2190  * with this table as well.
2191  */
2192 
2193 #define	SD_CHAIN_NULL			0	/* for the special RQS cmd */
2194 #define	SD_CHAIN_BUFIO			1	/* regular buf IO */
2195 #define	SD_CHAIN_USCSI			2	/* regular USCSI commands */
2196 #define	SD_CHAIN_DIRECT			3	/* uscsi, w/ bypass power mgt */
2197 #define	SD_CHAIN_DIRECT_PRIORITY	4	/* uscsi, w/ bypass power mgt */
2198 						/* (for error recovery) */
2199 
2200 static int sd_chain_type_map[] = {
2201 
2202 	/* Chain for buf IO for disk drive targets (PM enabled) */
2203 	SD_CHAIN_BUFIO,			/* Index: 0 */
2204 	SD_CHAIN_BUFIO,			/* Index: 1 */
2205 	SD_CHAIN_BUFIO,			/* Index: 2 */
2206 
2207 	/* Chain for buf IO for disk drive targets (PM disabled) */
2208 	SD_CHAIN_BUFIO,			/* Index: 3 */
2209 	SD_CHAIN_BUFIO,			/* Index: 4 */
2210 
2211 	/*
2212 	 * Chain for buf IO for removable-media or large sector size
2213 	 * disk drive targets (PM enabled)
2214 	 */
2215 	SD_CHAIN_BUFIO,			/* Index: 5 */
2216 	SD_CHAIN_BUFIO,			/* Index: 6 */
2217 	SD_CHAIN_BUFIO,			/* Index: 7 */
2218 	SD_CHAIN_BUFIO,			/* Index: 8 */
2219 
2220 	/*
2221 	 * Chain for buf IO for removable-media or large sector size
2222 	 * disk drive targets (PM disabled)
2223 	 */
2224 	SD_CHAIN_BUFIO,			/* Index: 9 */
2225 	SD_CHAIN_BUFIO,			/* Index: 10 */
2226 	SD_CHAIN_BUFIO,			/* Index: 11 */
2227 
2228 	/* Chain for buf IO for disk drives with checksumming (PM enabled) */
2229 	SD_CHAIN_BUFIO,			/* Index: 12 */
2230 	SD_CHAIN_BUFIO,			/* Index: 13 */
2231 	SD_CHAIN_BUFIO,			/* Index: 14 */
2232 	SD_CHAIN_BUFIO,			/* Index: 15 */
2233 
2234 	/* Chain for buf IO for disk drives with checksumming (PM disabled) */
2235 	SD_CHAIN_BUFIO,			/* Index: 16 */
2236 	SD_CHAIN_BUFIO,			/* Index: 17 */
2237 	SD_CHAIN_BUFIO,			/* Index: 18 */
2238 
2239 	/* Chain for USCSI commands (non-checksum targets) */
2240 	SD_CHAIN_USCSI,			/* Index: 19 */
2241 	SD_CHAIN_USCSI,			/* Index: 20 */
2242 
2243 	/* Chain for USCSI commands (checksum targets) */
2244 	SD_CHAIN_USCSI,			/* Index: 21 */
2245 	SD_CHAIN_USCSI,			/* Index: 22 */
2246 	SD_CHAIN_USCSI,			/* Index: 23 */
2247 
2248 	/* Chain for "direct" USCSI commands (all targets) */
2249 	SD_CHAIN_DIRECT,		/* Index: 24 */
2250 
2251 	/* Chain for "direct priority" USCSI commands (all targets) */
2252 	SD_CHAIN_DIRECT_PRIORITY,	/* Index: 25 */
2253 
2254 	/*
2255 	 * Chain for buf IO for large sector size disk drive targets
2256 	 * with checksumming (PM enabled)
2257 	 */
2258 	SD_CHAIN_BUFIO,			/* Index: 26 */
2259 	SD_CHAIN_BUFIO,			/* Index: 27 */
2260 	SD_CHAIN_BUFIO,			/* Index: 28 */
2261 	SD_CHAIN_BUFIO,			/* Index: 29 */
2262 	SD_CHAIN_BUFIO,			/* Index: 30 */
2263 
2264 	/*
2265 	 * Chain for buf IO for large sector size disk drive targets
2266 	 * with checksumming (PM disabled)
2267 	 */
2268 	SD_CHAIN_BUFIO,			/* Index: 31 */
2269 	SD_CHAIN_BUFIO,			/* Index: 32 */
2270 	SD_CHAIN_BUFIO,			/* Index: 33 */
2271 	SD_CHAIN_BUFIO,			/* Index: 34 */
2272 };
2273 
2274 
2275 /* Macro to return TRUE if the IO has come from the sd_buf_iostart() chain. */
2276 #define	SD_IS_BUFIO(xp)			\
2277 	(sd_chain_type_map[(xp)->xb_chain_iostart] == SD_CHAIN_BUFIO)
2278 
2279 /* Macro to return TRUE if the IO has come from the "direct priority" chain. */
2280 #define	SD_IS_DIRECT_PRIORITY(xp)	\
2281 	(sd_chain_type_map[(xp)->xb_chain_iostart] == SD_CHAIN_DIRECT_PRIORITY)
2282 
2283 
2284 
2285 /*
2286  * Struct, array, and macros to map a specific chain to the appropriate
2287  * layering indexes in the sd_iostart_chain[] and sd_iodone_chain[] arrays.
2288  *
2289  * The sd_chain_index_map[] array is used at attach time to set the various
2290  * un_xxx_chain type members of the sd_lun softstate to the specific layering
2291  * chain to be used with the instance. This allows different instances to use
2292  * different chain for buf IO, uscsi IO, etc.. Also, since the xb_chain_iostart
2293  * and xb_chain_iodone index values in the sd_xbuf are initialized to these
2294  * values at sd_xbuf init time, this allows (1) layering chains may be changed
2295  * dynamically & without the use of locking; and (2) a layer may update the
2296  * xb_chain_io[start|done] member in a given xbuf with its current index value,
2297  * to allow for deferred processing of an IO within the same chain from a
2298  * different execution context.
2299  */
2300 
2301 struct sd_chain_index {
2302 	int	sci_iostart_index;
2303 	int	sci_iodone_index;
2304 };
2305 
2306 static struct sd_chain_index	sd_chain_index_map[] = {
2307 	{ SD_CHAIN_DISK_IOSTART,		SD_CHAIN_DISK_IODONE },
2308 	{ SD_CHAIN_DISK_IOSTART_NO_PM,		SD_CHAIN_DISK_IODONE_NO_PM },
2309 	{ SD_CHAIN_RMMEDIA_IOSTART,		SD_CHAIN_RMMEDIA_IODONE },
2310 	{ SD_CHAIN_RMMEDIA_IOSTART_NO_PM,	SD_CHAIN_RMMEDIA_IODONE_NO_PM },
2311 	{ SD_CHAIN_CHKSUM_IOSTART,		SD_CHAIN_CHKSUM_IODONE },
2312 	{ SD_CHAIN_CHKSUM_IOSTART_NO_PM,	SD_CHAIN_CHKSUM_IODONE_NO_PM },
2313 	{ SD_CHAIN_USCSI_CMD_IOSTART,		SD_CHAIN_USCSI_CMD_IODONE },
2314 	{ SD_CHAIN_USCSI_CHKSUM_IOSTART,	SD_CHAIN_USCSI_CHKSUM_IODONE },
2315 	{ SD_CHAIN_DIRECT_CMD_IOSTART,		SD_CHAIN_DIRECT_CMD_IODONE },
2316 	{ SD_CHAIN_PRIORITY_CMD_IOSTART,	SD_CHAIN_PRIORITY_CMD_IODONE },
2317 	{ SD_CHAIN_MSS_CHKSUM_IOSTART,		SD_CHAIN_MSS_CHKSUM_IODONE },
2318 	{ SD_CHAIN_MSS_CHKSUM_IOSTART_NO_PM, SD_CHAIN_MSS_CHKSUM_IODONE_NO_PM },
2319 
2320 };
2321 
2322 
2323 /*
2324  * The following are indexes into the sd_chain_index_map[] array.
2325  */
2326 
2327 /* un->un_buf_chain_type must be set to one of these */
2328 #define	SD_CHAIN_INFO_DISK		0
2329 #define	SD_CHAIN_INFO_DISK_NO_PM	1
2330 #define	SD_CHAIN_INFO_RMMEDIA		2
2331 #define	SD_CHAIN_INFO_MSS_DISK		2
2332 #define	SD_CHAIN_INFO_RMMEDIA_NO_PM	3
2333 #define	SD_CHAIN_INFO_MSS_DSK_NO_PM	3
2334 #define	SD_CHAIN_INFO_CHKSUM		4
2335 #define	SD_CHAIN_INFO_CHKSUM_NO_PM	5
2336 #define	SD_CHAIN_INFO_MSS_DISK_CHKSUM	10
2337 #define	SD_CHAIN_INFO_MSS_DISK_CHKSUM_NO_PM	11
2338 
2339 /* un->un_uscsi_chain_type must be set to one of these */
2340 #define	SD_CHAIN_INFO_USCSI_CMD		6
2341 /* USCSI with PM disabled is the same as DIRECT */
2342 #define	SD_CHAIN_INFO_USCSI_CMD_NO_PM	8
2343 #define	SD_CHAIN_INFO_USCSI_CHKSUM	7
2344 
2345 /* un->un_direct_chain_type must be set to one of these */
2346 #define	SD_CHAIN_INFO_DIRECT_CMD	8
2347 
2348 /* un->un_priority_chain_type must be set to one of these */
2349 #define	SD_CHAIN_INFO_PRIORITY_CMD	9
2350 
2351 /* size for devid inquiries */
2352 #define	MAX_INQUIRY_SIZE		0xF0
2353 
2354 /*
2355  * Macros used by functions to pass a given buf(9S) struct along to the
2356  * next function in the layering chain for further processing.
2357  *
2358  * In the following macros, passing more than three arguments to the called
2359  * routines causes the optimizer for the SPARC compiler to stop doing tail
2360  * call elimination which results in significant performance degradation.
2361  */
2362 #define	SD_BEGIN_IOSTART(index, un, bp)	\
2363 	((*(sd_iostart_chain[index]))(index, un, bp))
2364 
2365 #define	SD_BEGIN_IODONE(index, un, bp)	\
2366 	((*(sd_iodone_chain[index]))(index, un, bp))
2367 
2368 #define	SD_NEXT_IOSTART(index, un, bp)				\
2369 	((*(sd_iostart_chain[(index) + 1]))((index) + 1, un, bp))
2370 
2371 #define	SD_NEXT_IODONE(index, un, bp)				\
2372 	((*(sd_iodone_chain[(index) - 1]))((index) - 1, un, bp))
2373 
2374 /*
2375  *    Function: _init
2376  *
2377  * Description: This is the driver _init(9E) entry point.
2378  *
2379  * Return Code: Returns the value from mod_install(9F) or
2380  *		ddi_soft_state_init(9F) as appropriate.
2381  *
2382  *     Context: Called when driver module loaded.
2383  */
2384 
2385 int
2386 _init(void)
2387 {
2388 	int	err;
2389 
2390 	/* establish driver name from module name */
2391 	sd_label = (char *)mod_modname(&modlinkage);
2392 
2393 #ifndef XPV_HVM_DRIVER
2394 	err = ddi_soft_state_init(&sd_state, sizeof (struct sd_lun),
2395 	    SD_MAXUNIT);
2396 	if (err != 0) {
2397 		return (err);
2398 	}
2399 
2400 #else /* XPV_HVM_DRIVER */
2401 	/* Remove the leading "hvm_" from the module name */
2402 	ASSERT(strncmp(sd_label, "hvm_", strlen("hvm_")) == 0);
2403 	sd_label += strlen("hvm_");
2404 
2405 #endif /* XPV_HVM_DRIVER */
2406 
2407 	mutex_init(&sd_detach_mutex, NULL, MUTEX_DRIVER, NULL);
2408 	mutex_init(&sd_log_mutex,    NULL, MUTEX_DRIVER, NULL);
2409 	mutex_init(&sd_label_mutex,  NULL, MUTEX_DRIVER, NULL);
2410 
2411 	mutex_init(&sd_tr.srq_resv_reclaim_mutex, NULL, MUTEX_DRIVER, NULL);
2412 	cv_init(&sd_tr.srq_resv_reclaim_cv, NULL, CV_DRIVER, NULL);
2413 	cv_init(&sd_tr.srq_inprocess_cv, NULL, CV_DRIVER, NULL);
2414 
2415 	/*
2416 	 * it's ok to init here even for fibre device
2417 	 */
2418 	sd_scsi_probe_cache_init();
2419 
2420 	sd_scsi_target_lun_init();
2421 
2422 	/*
2423 	 * Creating taskq before mod_install ensures that all callers (threads)
2424 	 * that enter the module after a successful mod_install encounter
2425 	 * a valid taskq.
2426 	 */
2427 	sd_taskq_create();
2428 
2429 	err = mod_install(&modlinkage);
2430 	if (err != 0) {
2431 		/* delete taskq if install fails */
2432 		sd_taskq_delete();
2433 
2434 		mutex_destroy(&sd_detach_mutex);
2435 		mutex_destroy(&sd_log_mutex);
2436 		mutex_destroy(&sd_label_mutex);
2437 
2438 		mutex_destroy(&sd_tr.srq_resv_reclaim_mutex);
2439 		cv_destroy(&sd_tr.srq_resv_reclaim_cv);
2440 		cv_destroy(&sd_tr.srq_inprocess_cv);
2441 
2442 		sd_scsi_probe_cache_fini();
2443 
2444 		sd_scsi_target_lun_fini();
2445 
2446 #ifndef XPV_HVM_DRIVER
2447 		ddi_soft_state_fini(&sd_state);
2448 #endif /* !XPV_HVM_DRIVER */
2449 		return (err);
2450 	}
2451 
2452 	return (err);
2453 }
2454 
2455 
2456 /*
2457  *    Function: _fini
2458  *
2459  * Description: This is the driver _fini(9E) entry point.
2460  *
2461  * Return Code: Returns the value from mod_remove(9F)
2462  *
2463  *     Context: Called when driver module is unloaded.
2464  */
2465 
2466 int
2467 _fini(void)
2468 {
2469 	int err;
2470 
2471 	if ((err = mod_remove(&modlinkage)) != 0) {
2472 		return (err);
2473 	}
2474 
2475 	sd_taskq_delete();
2476 
2477 	mutex_destroy(&sd_detach_mutex);
2478 	mutex_destroy(&sd_log_mutex);
2479 	mutex_destroy(&sd_label_mutex);
2480 	mutex_destroy(&sd_tr.srq_resv_reclaim_mutex);
2481 
2482 	sd_scsi_probe_cache_fini();
2483 
2484 	sd_scsi_target_lun_fini();
2485 
2486 	cv_destroy(&sd_tr.srq_resv_reclaim_cv);
2487 	cv_destroy(&sd_tr.srq_inprocess_cv);
2488 
2489 #ifndef XPV_HVM_DRIVER
2490 	ddi_soft_state_fini(&sd_state);
2491 #endif /* !XPV_HVM_DRIVER */
2492 
2493 	return (err);
2494 }
2495 
2496 
2497 /*
2498  *    Function: _info
2499  *
2500  * Description: This is the driver _info(9E) entry point.
2501  *
2502  *   Arguments: modinfop - pointer to the driver modinfo structure
2503  *
2504  * Return Code: Returns the value from mod_info(9F).
2505  *
2506  *     Context: Kernel thread context
2507  */
2508 
2509 int
2510 _info(struct modinfo *modinfop)
2511 {
2512 	return (mod_info(&modlinkage, modinfop));
2513 }
2514 
2515 
2516 /*
2517  * The following routines implement the driver message logging facility.
2518  * They provide component- and level- based debug output filtering.
2519  * Output may also be restricted to messages for a single instance by
2520  * specifying a soft state pointer in sd_debug_un. If sd_debug_un is set
2521  * to NULL, then messages for all instances are printed.
2522  *
2523  * These routines have been cloned from each other due to the language
2524  * constraints of macros and variable argument list processing.
2525  */
2526 
2527 
2528 /*
2529  *    Function: sd_log_err
2530  *
2531  * Description: This routine is called by the SD_ERROR macro for debug
2532  *		logging of error conditions.
2533  *
2534  *   Arguments: comp - driver component being logged
2535  *		dev  - pointer to driver info structure
2536  *		fmt  - error string and format to be logged
2537  */
2538 
2539 static void
2540 sd_log_err(uint_t comp, struct sd_lun *un, const char *fmt, ...)
2541 {
2542 	va_list		ap;
2543 	dev_info_t	*dev;
2544 
2545 	ASSERT(un != NULL);
2546 	dev = SD_DEVINFO(un);
2547 	ASSERT(dev != NULL);
2548 
2549 	/*
2550 	 * Filter messages based on the global component and level masks.
2551 	 * Also print if un matches the value of sd_debug_un, or if
2552 	 * sd_debug_un is set to NULL.
2553 	 */
2554 	if ((sd_component_mask & comp) && (sd_level_mask & SD_LOGMASK_ERROR) &&
2555 	    ((sd_debug_un == NULL) || (sd_debug_un == un))) {
2556 		mutex_enter(&sd_log_mutex);
2557 		va_start(ap, fmt);
2558 		(void) vsprintf(sd_log_buf, fmt, ap);
2559 		va_end(ap);
2560 		scsi_log(dev, sd_label, CE_CONT, "%s", sd_log_buf);
2561 		mutex_exit(&sd_log_mutex);
2562 	}
2563 #ifdef SD_FAULT_INJECTION
2564 	_NOTE(DATA_READABLE_WITHOUT_LOCK(sd_lun::sd_injection_mask));
2565 	if (un->sd_injection_mask & comp) {
2566 		mutex_enter(&sd_log_mutex);
2567 		va_start(ap, fmt);
2568 		(void) vsprintf(sd_log_buf, fmt, ap);
2569 		va_end(ap);
2570 		sd_injection_log(sd_log_buf, un);
2571 		mutex_exit(&sd_log_mutex);
2572 	}
2573 #endif
2574 }
2575 
2576 
2577 /*
2578  *    Function: sd_log_info
2579  *
2580  * Description: This routine is called by the SD_INFO macro for debug
2581  *		logging of general purpose informational conditions.
2582  *
2583  *   Arguments: comp - driver component being logged
2584  *		dev  - pointer to driver info structure
2585  *		fmt  - info string and format to be logged
2586  */
2587 
2588 static void
2589 sd_log_info(uint_t component, struct sd_lun *un, const char *fmt, ...)
2590 {
2591 	va_list		ap;
2592 	dev_info_t	*dev;
2593 
2594 	ASSERT(un != NULL);
2595 	dev = SD_DEVINFO(un);
2596 	ASSERT(dev != NULL);
2597 
2598 	/*
2599 	 * Filter messages based on the global component and level masks.
2600 	 * Also print if un matches the value of sd_debug_un, or if
2601 	 * sd_debug_un is set to NULL.
2602 	 */
2603 	if ((sd_component_mask & component) &&
2604 	    (sd_level_mask & SD_LOGMASK_INFO) &&
2605 	    ((sd_debug_un == NULL) || (sd_debug_un == un))) {
2606 		mutex_enter(&sd_log_mutex);
2607 		va_start(ap, fmt);
2608 		(void) vsprintf(sd_log_buf, fmt, ap);
2609 		va_end(ap);
2610 		scsi_log(dev, sd_label, CE_CONT, "%s", sd_log_buf);
2611 		mutex_exit(&sd_log_mutex);
2612 	}
2613 #ifdef SD_FAULT_INJECTION
2614 	_NOTE(DATA_READABLE_WITHOUT_LOCK(sd_lun::sd_injection_mask));
2615 	if (un->sd_injection_mask & component) {
2616 		mutex_enter(&sd_log_mutex);
2617 		va_start(ap, fmt);
2618 		(void) vsprintf(sd_log_buf, fmt, ap);
2619 		va_end(ap);
2620 		sd_injection_log(sd_log_buf, un);
2621 		mutex_exit(&sd_log_mutex);
2622 	}
2623 #endif
2624 }
2625 
2626 
2627 /*
2628  *    Function: sd_log_trace
2629  *
2630  * Description: This routine is called by the SD_TRACE macro for debug
2631  *		logging of trace conditions (i.e. function entry/exit).
2632  *
2633  *   Arguments: comp - driver component being logged
2634  *		dev  - pointer to driver info structure
2635  *		fmt  - trace string and format to be logged
2636  */
2637 
2638 static void
2639 sd_log_trace(uint_t component, struct sd_lun *un, const char *fmt, ...)
2640 {
2641 	va_list		ap;
2642 	dev_info_t	*dev;
2643 
2644 	ASSERT(un != NULL);
2645 	dev = SD_DEVINFO(un);
2646 	ASSERT(dev != NULL);
2647 
2648 	/*
2649 	 * Filter messages based on the global component and level masks.
2650 	 * Also print if un matches the value of sd_debug_un, or if
2651 	 * sd_debug_un is set to NULL.
2652 	 */
2653 	if ((sd_component_mask & component) &&
2654 	    (sd_level_mask & SD_LOGMASK_TRACE) &&
2655 	    ((sd_debug_un == NULL) || (sd_debug_un == un))) {
2656 		mutex_enter(&sd_log_mutex);
2657 		va_start(ap, fmt);
2658 		(void) vsprintf(sd_log_buf, fmt, ap);
2659 		va_end(ap);
2660 		scsi_log(dev, sd_label, CE_CONT, "%s", sd_log_buf);
2661 		mutex_exit(&sd_log_mutex);
2662 	}
2663 #ifdef SD_FAULT_INJECTION
2664 	_NOTE(DATA_READABLE_WITHOUT_LOCK(sd_lun::sd_injection_mask));
2665 	if (un->sd_injection_mask & component) {
2666 		mutex_enter(&sd_log_mutex);
2667 		va_start(ap, fmt);
2668 		(void) vsprintf(sd_log_buf, fmt, ap);
2669 		va_end(ap);
2670 		sd_injection_log(sd_log_buf, un);
2671 		mutex_exit(&sd_log_mutex);
2672 	}
2673 #endif
2674 }
2675 
2676 
2677 /*
2678  *    Function: sdprobe
2679  *
2680  * Description: This is the driver probe(9e) entry point function.
2681  *
2682  *   Arguments: devi - opaque device info handle
2683  *
2684  * Return Code: DDI_PROBE_SUCCESS: If the probe was successful.
2685  *              DDI_PROBE_FAILURE: If the probe failed.
2686  *              DDI_PROBE_PARTIAL: If the instance is not present now,
2687  *				   but may be present in the future.
2688  */
2689 
2690 static int
2691 sdprobe(dev_info_t *devi)
2692 {
2693 	struct scsi_device	*devp;
2694 	int			rval;
2695 #ifndef XPV_HVM_DRIVER
2696 	int			instance = ddi_get_instance(devi);
2697 #endif /* !XPV_HVM_DRIVER */
2698 
2699 	/*
2700 	 * if it wasn't for pln, sdprobe could actually be nulldev
2701 	 * in the "__fibre" case.
2702 	 */
2703 	if (ddi_dev_is_sid(devi) == DDI_SUCCESS) {
2704 		return (DDI_PROBE_DONTCARE);
2705 	}
2706 
2707 	devp = ddi_get_driver_private(devi);
2708 
2709 	if (devp == NULL) {
2710 		/* Ooops... nexus driver is mis-configured... */
2711 		return (DDI_PROBE_FAILURE);
2712 	}
2713 
2714 #ifndef XPV_HVM_DRIVER
2715 	if (ddi_get_soft_state(sd_state, instance) != NULL) {
2716 		return (DDI_PROBE_PARTIAL);
2717 	}
2718 #endif /* !XPV_HVM_DRIVER */
2719 
2720 	/*
2721 	 * Call the SCSA utility probe routine to see if we actually
2722 	 * have a target at this SCSI nexus.
2723 	 */
2724 	switch (sd_scsi_probe_with_cache(devp, NULL_FUNC)) {
2725 	case SCSIPROBE_EXISTS:
2726 		switch (devp->sd_inq->inq_dtype) {
2727 		case DTYPE_DIRECT:
2728 			rval = DDI_PROBE_SUCCESS;
2729 			break;
2730 		case DTYPE_RODIRECT:
2731 			/* CDs etc. Can be removable media */
2732 			rval = DDI_PROBE_SUCCESS;
2733 			break;
2734 		case DTYPE_OPTICAL:
2735 			/*
2736 			 * Rewritable optical driver HP115AA
2737 			 * Can also be removable media
2738 			 */
2739 
2740 			/*
2741 			 * Do not attempt to bind to  DTYPE_OPTICAL if
2742 			 * pre solaris 9 sparc sd behavior is required
2743 			 *
2744 			 * If first time through and sd_dtype_optical_bind
2745 			 * has not been set in /etc/system check properties
2746 			 */
2747 
2748 			if (sd_dtype_optical_bind  < 0) {
2749 				sd_dtype_optical_bind = ddi_prop_get_int
2750 				    (DDI_DEV_T_ANY, devi, 0,
2751 				    "optical-device-bind", 1);
2752 			}
2753 
2754 			if (sd_dtype_optical_bind == 0) {
2755 				rval = DDI_PROBE_FAILURE;
2756 			} else {
2757 				rval = DDI_PROBE_SUCCESS;
2758 			}
2759 			break;
2760 
2761 		case DTYPE_NOTPRESENT:
2762 		default:
2763 			rval = DDI_PROBE_FAILURE;
2764 			break;
2765 		}
2766 		break;
2767 	default:
2768 		rval = DDI_PROBE_PARTIAL;
2769 		break;
2770 	}
2771 
2772 	/*
2773 	 * This routine checks for resource allocation prior to freeing,
2774 	 * so it will take care of the "smart probing" case where a
2775 	 * scsi_probe() may or may not have been issued and will *not*
2776 	 * free previously-freed resources.
2777 	 */
2778 	scsi_unprobe(devp);
2779 	return (rval);
2780 }
2781 
2782 
2783 /*
2784  *    Function: sdinfo
2785  *
2786  * Description: This is the driver getinfo(9e) entry point function.
2787  * 		Given the device number, return the devinfo pointer from
2788  *		the scsi_device structure or the instance number
2789  *		associated with the dev_t.
2790  *
2791  *   Arguments: dip     - pointer to device info structure
2792  *		infocmd - command argument (DDI_INFO_DEVT2DEVINFO,
2793  *			  DDI_INFO_DEVT2INSTANCE)
2794  *		arg     - driver dev_t
2795  *		resultp - user buffer for request response
2796  *
2797  * Return Code: DDI_SUCCESS
2798  *              DDI_FAILURE
2799  */
2800 /* ARGSUSED */
2801 static int
2802 sdinfo(dev_info_t *dip, ddi_info_cmd_t infocmd, void *arg, void **result)
2803 {
2804 	struct sd_lun	*un;
2805 	dev_t		dev;
2806 	int		instance;
2807 	int		error;
2808 
2809 	switch (infocmd) {
2810 	case DDI_INFO_DEVT2DEVINFO:
2811 		dev = (dev_t)arg;
2812 		instance = SDUNIT(dev);
2813 		if ((un = ddi_get_soft_state(sd_state, instance)) == NULL) {
2814 			return (DDI_FAILURE);
2815 		}
2816 		*result = (void *) SD_DEVINFO(un);
2817 		error = DDI_SUCCESS;
2818 		break;
2819 	case DDI_INFO_DEVT2INSTANCE:
2820 		dev = (dev_t)arg;
2821 		instance = SDUNIT(dev);
2822 		*result = (void *)(uintptr_t)instance;
2823 		error = DDI_SUCCESS;
2824 		break;
2825 	default:
2826 		error = DDI_FAILURE;
2827 	}
2828 	return (error);
2829 }
2830 
2831 /*
2832  *    Function: sd_prop_op
2833  *
2834  * Description: This is the driver prop_op(9e) entry point function.
2835  *		Return the number of blocks for the partition in question
2836  *		or forward the request to the property facilities.
2837  *
2838  *   Arguments: dev       - device number
2839  *		dip       - pointer to device info structure
2840  *		prop_op   - property operator
2841  *		mod_flags - DDI_PROP_DONTPASS, don't pass to parent
2842  *		name      - pointer to property name
2843  *		valuep    - pointer or address of the user buffer
2844  *		lengthp   - property length
2845  *
2846  * Return Code: DDI_PROP_SUCCESS
2847  *              DDI_PROP_NOT_FOUND
2848  *              DDI_PROP_UNDEFINED
2849  *              DDI_PROP_NO_MEMORY
2850  *              DDI_PROP_BUF_TOO_SMALL
2851  */
2852 
2853 static int
2854 sd_prop_op(dev_t dev, dev_info_t *dip, ddi_prop_op_t prop_op, int mod_flags,
2855 	char *name, caddr_t valuep, int *lengthp)
2856 {
2857 	struct sd_lun	*un;
2858 
2859 	if ((un = ddi_get_soft_state(sd_state, ddi_get_instance(dip))) == NULL)
2860 		return (ddi_prop_op(dev, dip, prop_op, mod_flags,
2861 		    name, valuep, lengthp));
2862 
2863 	return (cmlb_prop_op(un->un_cmlbhandle,
2864 	    dev, dip, prop_op, mod_flags, name, valuep, lengthp,
2865 	    SDPART(dev), (void *)SD_PATH_DIRECT));
2866 }
2867 
2868 /*
2869  * The following functions are for smart probing:
2870  * sd_scsi_probe_cache_init()
2871  * sd_scsi_probe_cache_fini()
2872  * sd_scsi_clear_probe_cache()
2873  * sd_scsi_probe_with_cache()
2874  */
2875 
2876 /*
2877  *    Function: sd_scsi_probe_cache_init
2878  *
2879  * Description: Initializes the probe response cache mutex and head pointer.
2880  *
2881  *     Context: Kernel thread context
2882  */
2883 
2884 static void
2885 sd_scsi_probe_cache_init(void)
2886 {
2887 	mutex_init(&sd_scsi_probe_cache_mutex, NULL, MUTEX_DRIVER, NULL);
2888 	sd_scsi_probe_cache_head = NULL;
2889 }
2890 
2891 
2892 /*
2893  *    Function: sd_scsi_probe_cache_fini
2894  *
2895  * Description: Frees all resources associated with the probe response cache.
2896  *
2897  *     Context: Kernel thread context
2898  */
2899 
2900 static void
2901 sd_scsi_probe_cache_fini(void)
2902 {
2903 	struct sd_scsi_probe_cache *cp;
2904 	struct sd_scsi_probe_cache *ncp;
2905 
2906 	/* Clean up our smart probing linked list */
2907 	for (cp = sd_scsi_probe_cache_head; cp != NULL; cp = ncp) {
2908 		ncp = cp->next;
2909 		kmem_free(cp, sizeof (struct sd_scsi_probe_cache));
2910 	}
2911 	sd_scsi_probe_cache_head = NULL;
2912 	mutex_destroy(&sd_scsi_probe_cache_mutex);
2913 }
2914 
2915 
2916 /*
2917  *    Function: sd_scsi_clear_probe_cache
2918  *
2919  * Description: This routine clears the probe response cache. This is
2920  *		done when open() returns ENXIO so that when deferred
2921  *		attach is attempted (possibly after a device has been
2922  *		turned on) we will retry the probe. Since we don't know
2923  *		which target we failed to open, we just clear the
2924  *		entire cache.
2925  *
2926  *     Context: Kernel thread context
2927  */
2928 
2929 static void
2930 sd_scsi_clear_probe_cache(void)
2931 {
2932 	struct sd_scsi_probe_cache	*cp;
2933 	int				i;
2934 
2935 	mutex_enter(&sd_scsi_probe_cache_mutex);
2936 	for (cp = sd_scsi_probe_cache_head; cp != NULL; cp = cp->next) {
2937 		/*
2938 		 * Reset all entries to SCSIPROBE_EXISTS.  This will
2939 		 * force probing to be performed the next time
2940 		 * sd_scsi_probe_with_cache is called.
2941 		 */
2942 		for (i = 0; i < NTARGETS_WIDE; i++) {
2943 			cp->cache[i] = SCSIPROBE_EXISTS;
2944 		}
2945 	}
2946 	mutex_exit(&sd_scsi_probe_cache_mutex);
2947 }
2948 
2949 
2950 /*
2951  *    Function: sd_scsi_probe_with_cache
2952  *
2953  * Description: This routine implements support for a scsi device probe
2954  *		with cache. The driver maintains a cache of the target
2955  *		responses to scsi probes. If we get no response from a
2956  *		target during a probe inquiry, we remember that, and we
2957  *		avoid additional calls to scsi_probe on non-zero LUNs
2958  *		on the same target until the cache is cleared. By doing
2959  *		so we avoid the 1/4 sec selection timeout for nonzero
2960  *		LUNs. lun0 of a target is always probed.
2961  *
2962  *   Arguments: devp     - Pointer to a scsi_device(9S) structure
2963  *              waitfunc - indicates what the allocator routines should
2964  *			   do when resources are not available. This value
2965  *			   is passed on to scsi_probe() when that routine
2966  *			   is called.
2967  *
2968  * Return Code: SCSIPROBE_NORESP if a NORESP in probe response cache;
2969  *		otherwise the value returned by scsi_probe(9F).
2970  *
2971  *     Context: Kernel thread context
2972  */
2973 
2974 static int
2975 sd_scsi_probe_with_cache(struct scsi_device *devp, int (*waitfn)())
2976 {
2977 	struct sd_scsi_probe_cache	*cp;
2978 	dev_info_t	*pdip = ddi_get_parent(devp->sd_dev);
2979 	int		lun, tgt;
2980 
2981 	lun = ddi_prop_get_int(DDI_DEV_T_ANY, devp->sd_dev, DDI_PROP_DONTPASS,
2982 	    SCSI_ADDR_PROP_LUN, 0);
2983 	tgt = ddi_prop_get_int(DDI_DEV_T_ANY, devp->sd_dev, DDI_PROP_DONTPASS,
2984 	    SCSI_ADDR_PROP_TARGET, -1);
2985 
2986 	/* Make sure caching enabled and target in range */
2987 	if ((tgt < 0) || (tgt >= NTARGETS_WIDE)) {
2988 		/* do it the old way (no cache) */
2989 		return (scsi_probe(devp, waitfn));
2990 	}
2991 
2992 	mutex_enter(&sd_scsi_probe_cache_mutex);
2993 
2994 	/* Find the cache for this scsi bus instance */
2995 	for (cp = sd_scsi_probe_cache_head; cp != NULL; cp = cp->next) {
2996 		if (cp->pdip == pdip) {
2997 			break;
2998 		}
2999 	}
3000 
3001 	/* If we can't find a cache for this pdip, create one */
3002 	if (cp == NULL) {
3003 		int i;
3004 
3005 		cp = kmem_zalloc(sizeof (struct sd_scsi_probe_cache),
3006 		    KM_SLEEP);
3007 		cp->pdip = pdip;
3008 		cp->next = sd_scsi_probe_cache_head;
3009 		sd_scsi_probe_cache_head = cp;
3010 		for (i = 0; i < NTARGETS_WIDE; i++) {
3011 			cp->cache[i] = SCSIPROBE_EXISTS;
3012 		}
3013 	}
3014 
3015 	mutex_exit(&sd_scsi_probe_cache_mutex);
3016 
3017 	/* Recompute the cache for this target if LUN zero */
3018 	if (lun == 0) {
3019 		cp->cache[tgt] = SCSIPROBE_EXISTS;
3020 	}
3021 
3022 	/* Don't probe if cache remembers a NORESP from a previous LUN. */
3023 	if (cp->cache[tgt] != SCSIPROBE_EXISTS) {
3024 		return (SCSIPROBE_NORESP);
3025 	}
3026 
3027 	/* Do the actual probe; save & return the result */
3028 	return (cp->cache[tgt] = scsi_probe(devp, waitfn));
3029 }
3030 
3031 
3032 /*
3033  *    Function: sd_scsi_target_lun_init
3034  *
3035  * Description: Initializes the attached lun chain mutex and head pointer.
3036  *
3037  *     Context: Kernel thread context
3038  */
3039 
3040 static void
3041 sd_scsi_target_lun_init(void)
3042 {
3043 	mutex_init(&sd_scsi_target_lun_mutex, NULL, MUTEX_DRIVER, NULL);
3044 	sd_scsi_target_lun_head = NULL;
3045 }
3046 
3047 
3048 /*
3049  *    Function: sd_scsi_target_lun_fini
3050  *
3051  * Description: Frees all resources associated with the attached lun
3052  *              chain
3053  *
3054  *     Context: Kernel thread context
3055  */
3056 
3057 static void
3058 sd_scsi_target_lun_fini(void)
3059 {
3060 	struct sd_scsi_hba_tgt_lun	*cp;
3061 	struct sd_scsi_hba_tgt_lun	*ncp;
3062 
3063 	for (cp = sd_scsi_target_lun_head; cp != NULL; cp = ncp) {
3064 		ncp = cp->next;
3065 		kmem_free(cp, sizeof (struct sd_scsi_hba_tgt_lun));
3066 	}
3067 	sd_scsi_target_lun_head = NULL;
3068 	mutex_destroy(&sd_scsi_target_lun_mutex);
3069 }
3070 
3071 
3072 /*
3073  *    Function: sd_scsi_get_target_lun_count
3074  *
3075  * Description: This routine will check in the attached lun chain to see
3076  * 		how many luns are attached on the required SCSI controller
3077  * 		and target. Currently, some capabilities like tagged queue
3078  *		are supported per target based by HBA. So all luns in a
3079  *		target have the same capabilities. Based on this assumption,
3080  * 		sd should only set these capabilities once per target. This
3081  *		function is called when sd needs to decide how many luns
3082  *		already attached on a target.
3083  *
3084  *   Arguments: dip	- Pointer to the system's dev_info_t for the SCSI
3085  *			  controller device.
3086  *              target	- The target ID on the controller's SCSI bus.
3087  *
3088  * Return Code: The number of luns attached on the required target and
3089  *		controller.
3090  *		-1 if target ID is not in parallel SCSI scope or the given
3091  * 		dip is not in the chain.
3092  *
3093  *     Context: Kernel thread context
3094  */
3095 
3096 static int
3097 sd_scsi_get_target_lun_count(dev_info_t *dip, int target)
3098 {
3099 	struct sd_scsi_hba_tgt_lun	*cp;
3100 
3101 	if ((target < 0) || (target >= NTARGETS_WIDE)) {
3102 		return (-1);
3103 	}
3104 
3105 	mutex_enter(&sd_scsi_target_lun_mutex);
3106 
3107 	for (cp = sd_scsi_target_lun_head; cp != NULL; cp = cp->next) {
3108 		if (cp->pdip == dip) {
3109 			break;
3110 		}
3111 	}
3112 
3113 	mutex_exit(&sd_scsi_target_lun_mutex);
3114 
3115 	if (cp == NULL) {
3116 		return (-1);
3117 	}
3118 
3119 	return (cp->nlun[target]);
3120 }
3121 
3122 
3123 /*
3124  *    Function: sd_scsi_update_lun_on_target
3125  *
3126  * Description: This routine is used to update the attached lun chain when a
3127  *		lun is attached or detached on a target.
3128  *
3129  *   Arguments: dip     - Pointer to the system's dev_info_t for the SCSI
3130  *                        controller device.
3131  *              target  - The target ID on the controller's SCSI bus.
3132  *		flag	- Indicate the lun is attached or detached.
3133  *
3134  *     Context: Kernel thread context
3135  */
3136 
3137 static void
3138 sd_scsi_update_lun_on_target(dev_info_t *dip, int target, int flag)
3139 {
3140 	struct sd_scsi_hba_tgt_lun	*cp;
3141 
3142 	mutex_enter(&sd_scsi_target_lun_mutex);
3143 
3144 	for (cp = sd_scsi_target_lun_head; cp != NULL; cp = cp->next) {
3145 		if (cp->pdip == dip) {
3146 			break;
3147 		}
3148 	}
3149 
3150 	if ((cp == NULL) && (flag == SD_SCSI_LUN_ATTACH)) {
3151 		cp = kmem_zalloc(sizeof (struct sd_scsi_hba_tgt_lun),
3152 		    KM_SLEEP);
3153 		cp->pdip = dip;
3154 		cp->next = sd_scsi_target_lun_head;
3155 		sd_scsi_target_lun_head = cp;
3156 	}
3157 
3158 	mutex_exit(&sd_scsi_target_lun_mutex);
3159 
3160 	if (cp != NULL) {
3161 		if (flag == SD_SCSI_LUN_ATTACH) {
3162 			cp->nlun[target] ++;
3163 		} else {
3164 			cp->nlun[target] --;
3165 		}
3166 	}
3167 }
3168 
3169 
3170 /*
3171  *    Function: sd_spin_up_unit
3172  *
3173  * Description: Issues the following commands to spin-up the device:
3174  *		START STOP UNIT, and INQUIRY.
3175  *
3176  *   Arguments: ssc   - ssc contains pointer to driver soft state (unit)
3177  *                      structure for this target.
3178  *
3179  * Return Code: 0 - success
3180  *		EIO - failure
3181  *		EACCES - reservation conflict
3182  *
3183  *     Context: Kernel thread context
3184  */
3185 
3186 static int
3187 sd_spin_up_unit(sd_ssc_t *ssc)
3188 {
3189 	size_t	resid		= 0;
3190 	int	has_conflict	= FALSE;
3191 	uchar_t *bufaddr;
3192 	int 	status;
3193 	struct sd_lun	*un;
3194 
3195 	ASSERT(ssc != NULL);
3196 	un = ssc->ssc_un;
3197 	ASSERT(un != NULL);
3198 
3199 	/*
3200 	 * Send a throwaway START UNIT command.
3201 	 *
3202 	 * If we fail on this, we don't care presently what precisely
3203 	 * is wrong.  EMC's arrays will also fail this with a check
3204 	 * condition (0x2/0x4/0x3) if the device is "inactive," but
3205 	 * we don't want to fail the attach because it may become
3206 	 * "active" later.
3207 	 * We don't know if power condition is supported or not at
3208 	 * this stage, use START STOP bit.
3209 	 */
3210 	status = sd_send_scsi_START_STOP_UNIT(ssc, SD_START_STOP,
3211 	    SD_TARGET_START, SD_PATH_DIRECT);
3212 
3213 	if (status != 0) {
3214 		if (status == EACCES)
3215 			has_conflict = TRUE;
3216 		sd_ssc_assessment(ssc, SD_FMT_IGNORE);
3217 	}
3218 
3219 	/*
3220 	 * Send another INQUIRY command to the target. This is necessary for
3221 	 * non-removable media direct access devices because their INQUIRY data
3222 	 * may not be fully qualified until they are spun up (perhaps via the
3223 	 * START command above).  Note: This seems to be needed for some
3224 	 * legacy devices only.) The INQUIRY command should succeed even if a
3225 	 * Reservation Conflict is present.
3226 	 */
3227 	bufaddr = kmem_zalloc(SUN_INQSIZE, KM_SLEEP);
3228 
3229 	if (sd_send_scsi_INQUIRY(ssc, bufaddr, SUN_INQSIZE, 0, 0, &resid)
3230 	    != 0) {
3231 		kmem_free(bufaddr, SUN_INQSIZE);
3232 		sd_ssc_assessment(ssc, SD_FMT_STATUS_CHECK);
3233 		return (EIO);
3234 	}
3235 
3236 	/*
3237 	 * If we got enough INQUIRY data, copy it over the old INQUIRY data.
3238 	 * Note that this routine does not return a failure here even if the
3239 	 * INQUIRY command did not return any data.  This is a legacy behavior.
3240 	 */
3241 	if ((SUN_INQSIZE - resid) >= SUN_MIN_INQLEN) {
3242 		bcopy(bufaddr, SD_INQUIRY(un), SUN_INQSIZE);
3243 	}
3244 
3245 	kmem_free(bufaddr, SUN_INQSIZE);
3246 
3247 	/* If we hit a reservation conflict above, tell the caller. */
3248 	if (has_conflict == TRUE) {
3249 		return (EACCES);
3250 	}
3251 
3252 	return (0);
3253 }
3254 
3255 #ifdef _LP64
3256 /*
3257  *    Function: sd_enable_descr_sense
3258  *
3259  * Description: This routine attempts to select descriptor sense format
3260  *		using the Control mode page.  Devices that support 64 bit
3261  *		LBAs (for >2TB luns) should also implement descriptor
3262  *		sense data so we will call this function whenever we see
3263  *		a lun larger than 2TB.  If for some reason the device
3264  *		supports 64 bit LBAs but doesn't support descriptor sense
3265  *		presumably the mode select will fail.  Everything will
3266  *		continue to work normally except that we will not get
3267  *		complete sense data for commands that fail with an LBA
3268  *		larger than 32 bits.
3269  *
3270  *   Arguments: ssc   - ssc contains pointer to driver soft state (unit)
3271  *                      structure for this target.
3272  *
3273  *     Context: Kernel thread context only
3274  */
3275 
3276 static void
3277 sd_enable_descr_sense(sd_ssc_t *ssc)
3278 {
3279 	uchar_t			*header;
3280 	struct mode_control_scsi3 *ctrl_bufp;
3281 	size_t			buflen;
3282 	size_t			bd_len;
3283 	int			status;
3284 	struct sd_lun		*un;
3285 
3286 	ASSERT(ssc != NULL);
3287 	un = ssc->ssc_un;
3288 	ASSERT(un != NULL);
3289 
3290 	/*
3291 	 * Read MODE SENSE page 0xA, Control Mode Page
3292 	 */
3293 	buflen = MODE_HEADER_LENGTH + MODE_BLK_DESC_LENGTH +
3294 	    sizeof (struct mode_control_scsi3);
3295 	header = kmem_zalloc(buflen, KM_SLEEP);
3296 
3297 	status = sd_send_scsi_MODE_SENSE(ssc, CDB_GROUP0, header, buflen,
3298 	    MODEPAGE_CTRL_MODE, SD_PATH_DIRECT);
3299 
3300 	if (status != 0) {
3301 		SD_ERROR(SD_LOG_COMMON, un,
3302 		    "sd_enable_descr_sense: mode sense ctrl page failed\n");
3303 		goto eds_exit;
3304 	}
3305 
3306 	/*
3307 	 * Determine size of Block Descriptors in order to locate
3308 	 * the mode page data. ATAPI devices return 0, SCSI devices
3309 	 * should return MODE_BLK_DESC_LENGTH.
3310 	 */
3311 	bd_len  = ((struct mode_header *)header)->bdesc_length;
3312 
3313 	/* Clear the mode data length field for MODE SELECT */
3314 	((struct mode_header *)header)->length = 0;
3315 
3316 	ctrl_bufp = (struct mode_control_scsi3 *)
3317 	    (header + MODE_HEADER_LENGTH + bd_len);
3318 
3319 	/*
3320 	 * If the page length is smaller than the expected value,
3321 	 * the target device doesn't support D_SENSE. Bail out here.
3322 	 */
3323 	if (ctrl_bufp->mode_page.length <
3324 	    sizeof (struct mode_control_scsi3) - 2) {
3325 		SD_ERROR(SD_LOG_COMMON, un,
3326 		    "sd_enable_descr_sense: enable D_SENSE failed\n");
3327 		goto eds_exit;
3328 	}
3329 
3330 	/*
3331 	 * Clear PS bit for MODE SELECT
3332 	 */
3333 	ctrl_bufp->mode_page.ps = 0;
3334 
3335 	/*
3336 	 * Set D_SENSE to enable descriptor sense format.
3337 	 */
3338 	ctrl_bufp->d_sense = 1;
3339 
3340 	sd_ssc_assessment(ssc, SD_FMT_IGNORE);
3341 
3342 	/*
3343 	 * Use MODE SELECT to commit the change to the D_SENSE bit
3344 	 */
3345 	status = sd_send_scsi_MODE_SELECT(ssc, CDB_GROUP0, header,
3346 	    buflen, SD_DONTSAVE_PAGE, SD_PATH_DIRECT);
3347 
3348 	if (status != 0) {
3349 		SD_INFO(SD_LOG_COMMON, un,
3350 		    "sd_enable_descr_sense: mode select ctrl page failed\n");
3351 	} else {
3352 		kmem_free(header, buflen);
3353 		return;
3354 	}
3355 
3356 eds_exit:
3357 	sd_ssc_assessment(ssc, SD_FMT_IGNORE);
3358 	kmem_free(header, buflen);
3359 }
3360 
3361 /*
3362  *    Function: sd_reenable_dsense_task
3363  *
3364  * Description: Re-enable descriptor sense after device or bus reset
3365  *
3366  *     Context: Executes in a taskq() thread context
3367  */
3368 static void
3369 sd_reenable_dsense_task(void *arg)
3370 {
3371 	struct	sd_lun	*un = arg;
3372 	sd_ssc_t	*ssc;
3373 
3374 	ASSERT(un != NULL);
3375 
3376 	ssc = sd_ssc_init(un);
3377 	sd_enable_descr_sense(ssc);
3378 	sd_ssc_fini(ssc);
3379 }
3380 #endif /* _LP64 */
3381 
3382 /*
3383  *    Function: sd_set_mmc_caps
3384  *
3385  * Description: This routine determines if the device is MMC compliant and if
3386  *		the device supports CDDA via a mode sense of the CDVD
3387  *		capabilities mode page. Also checks if the device is a
3388  *		dvdram writable device.
3389  *
3390  *   Arguments: ssc   - ssc contains pointer to driver soft state (unit)
3391  *                      structure for this target.
3392  *
3393  *     Context: Kernel thread context only
3394  */
3395 
3396 static void
3397 sd_set_mmc_caps(sd_ssc_t *ssc)
3398 {
3399 	struct mode_header_grp2		*sense_mhp;
3400 	uchar_t				*sense_page;
3401 	caddr_t				buf;
3402 	int				bd_len;
3403 	int				status;
3404 	struct uscsi_cmd		com;
3405 	int				rtn;
3406 	uchar_t				*out_data_rw, *out_data_hd;
3407 	uchar_t				*rqbuf_rw, *rqbuf_hd;
3408 	struct sd_lun			*un;
3409 
3410 	ASSERT(ssc != NULL);
3411 	un = ssc->ssc_un;
3412 	ASSERT(un != NULL);
3413 
3414 	/*
3415 	 * The flags which will be set in this function are - mmc compliant,
3416 	 * dvdram writable device, cdda support. Initialize them to FALSE
3417 	 * and if a capability is detected - it will be set to TRUE.
3418 	 */
3419 	un->un_f_mmc_cap = FALSE;
3420 	un->un_f_dvdram_writable_device = FALSE;
3421 	un->un_f_cfg_cdda = FALSE;
3422 
3423 	buf = kmem_zalloc(BUFLEN_MODE_CDROM_CAP, KM_SLEEP);
3424 	status = sd_send_scsi_MODE_SENSE(ssc, CDB_GROUP1, (uchar_t *)buf,
3425 	    BUFLEN_MODE_CDROM_CAP, MODEPAGE_CDROM_CAP, SD_PATH_DIRECT);
3426 
3427 	sd_ssc_assessment(ssc, SD_FMT_IGNORE);
3428 
3429 	if (status != 0) {
3430 		/* command failed; just return */
3431 		kmem_free(buf, BUFLEN_MODE_CDROM_CAP);
3432 		return;
3433 	}
3434 	/*
3435 	 * If the mode sense request for the CDROM CAPABILITIES
3436 	 * page (0x2A) succeeds the device is assumed to be MMC.
3437 	 */
3438 	un->un_f_mmc_cap = TRUE;
3439 
3440 	/* Get to the page data */
3441 	sense_mhp = (struct mode_header_grp2 *)buf;
3442 	bd_len = (sense_mhp->bdesc_length_hi << 8) |
3443 	    sense_mhp->bdesc_length_lo;
3444 	if (bd_len > MODE_BLK_DESC_LENGTH) {
3445 		/*
3446 		 * We did not get back the expected block descriptor
3447 		 * length so we cannot determine if the device supports
3448 		 * CDDA. However, we still indicate the device is MMC
3449 		 * according to the successful response to the page
3450 		 * 0x2A mode sense request.
3451 		 */
3452 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
3453 		    "sd_set_mmc_caps: Mode Sense returned "
3454 		    "invalid block descriptor length\n");
3455 		kmem_free(buf, BUFLEN_MODE_CDROM_CAP);
3456 		return;
3457 	}
3458 
3459 	/* See if read CDDA is supported */
3460 	sense_page = (uchar_t *)(buf + MODE_HEADER_LENGTH_GRP2 +
3461 	    bd_len);
3462 	un->un_f_cfg_cdda = (sense_page[5] & 0x01) ? TRUE : FALSE;
3463 
3464 	/* See if writing DVD RAM is supported. */
3465 	un->un_f_dvdram_writable_device = (sense_page[3] & 0x20) ? TRUE : FALSE;
3466 	if (un->un_f_dvdram_writable_device == TRUE) {
3467 		kmem_free(buf, BUFLEN_MODE_CDROM_CAP);
3468 		return;
3469 	}
3470 
3471 	/*
3472 	 * If the device presents DVD or CD capabilities in the mode
3473 	 * page, we can return here since a RRD will not have
3474 	 * these capabilities.
3475 	 */
3476 	if ((sense_page[2] & 0x3f) || (sense_page[3] & 0x3f)) {
3477 		kmem_free(buf, BUFLEN_MODE_CDROM_CAP);
3478 		return;
3479 	}
3480 	kmem_free(buf, BUFLEN_MODE_CDROM_CAP);
3481 
3482 	/*
3483 	 * If un->un_f_dvdram_writable_device is still FALSE,
3484 	 * check for a Removable Rigid Disk (RRD).  A RRD
3485 	 * device is identified by the features RANDOM_WRITABLE and
3486 	 * HARDWARE_DEFECT_MANAGEMENT.
3487 	 */
3488 	out_data_rw = kmem_zalloc(SD_CURRENT_FEATURE_LEN, KM_SLEEP);
3489 	rqbuf_rw = kmem_zalloc(SENSE_LENGTH, KM_SLEEP);
3490 
3491 	rtn = sd_send_scsi_feature_GET_CONFIGURATION(ssc, &com, rqbuf_rw,
3492 	    SENSE_LENGTH, out_data_rw, SD_CURRENT_FEATURE_LEN,
3493 	    RANDOM_WRITABLE, SD_PATH_STANDARD);
3494 
3495 	sd_ssc_assessment(ssc, SD_FMT_IGNORE);
3496 
3497 	if (rtn != 0) {
3498 		kmem_free(out_data_rw, SD_CURRENT_FEATURE_LEN);
3499 		kmem_free(rqbuf_rw, SENSE_LENGTH);
3500 		return;
3501 	}
3502 
3503 	out_data_hd = kmem_zalloc(SD_CURRENT_FEATURE_LEN, KM_SLEEP);
3504 	rqbuf_hd = kmem_zalloc(SENSE_LENGTH, KM_SLEEP);
3505 
3506 	rtn = sd_send_scsi_feature_GET_CONFIGURATION(ssc, &com, rqbuf_hd,
3507 	    SENSE_LENGTH, out_data_hd, SD_CURRENT_FEATURE_LEN,
3508 	    HARDWARE_DEFECT_MANAGEMENT, SD_PATH_STANDARD);
3509 
3510 	sd_ssc_assessment(ssc, SD_FMT_IGNORE);
3511 
3512 	if (rtn == 0) {
3513 		/*
3514 		 * We have good information, check for random writable
3515 		 * and hardware defect features.
3516 		 */
3517 		if ((out_data_rw[9] & RANDOM_WRITABLE) &&
3518 		    (out_data_hd[9] & HARDWARE_DEFECT_MANAGEMENT)) {
3519 			un->un_f_dvdram_writable_device = TRUE;
3520 		}
3521 	}
3522 
3523 	kmem_free(out_data_rw, SD_CURRENT_FEATURE_LEN);
3524 	kmem_free(rqbuf_rw, SENSE_LENGTH);
3525 	kmem_free(out_data_hd, SD_CURRENT_FEATURE_LEN);
3526 	kmem_free(rqbuf_hd, SENSE_LENGTH);
3527 }
3528 
3529 /*
3530  *    Function: sd_check_for_writable_cd
3531  *
3532  * Description: This routine determines if the media in the device is
3533  *		writable or not. It uses the get configuration command (0x46)
3534  *		to determine if the media is writable
3535  *
3536  *   Arguments: un - driver soft state (unit) structure
3537  *              path_flag - SD_PATH_DIRECT to use the USCSI "direct"
3538  *                           chain and the normal command waitq, or
3539  *                           SD_PATH_DIRECT_PRIORITY to use the USCSI
3540  *                           "direct" chain and bypass the normal command
3541  *                           waitq.
3542  *
3543  *     Context: Never called at interrupt context.
3544  */
3545 
3546 static void
3547 sd_check_for_writable_cd(sd_ssc_t *ssc, int path_flag)
3548 {
3549 	struct uscsi_cmd		com;
3550 	uchar_t				*out_data;
3551 	uchar_t				*rqbuf;
3552 	int				rtn;
3553 	uchar_t				*out_data_rw, *out_data_hd;
3554 	uchar_t				*rqbuf_rw, *rqbuf_hd;
3555 	struct mode_header_grp2		*sense_mhp;
3556 	uchar_t				*sense_page;
3557 	caddr_t				buf;
3558 	int				bd_len;
3559 	int				status;
3560 	struct sd_lun			*un;
3561 
3562 	ASSERT(ssc != NULL);
3563 	un = ssc->ssc_un;
3564 	ASSERT(un != NULL);
3565 	ASSERT(mutex_owned(SD_MUTEX(un)));
3566 
3567 	/*
3568 	 * Initialize the writable media to false, if configuration info.
3569 	 * tells us otherwise then only we will set it.
3570 	 */
3571 	un->un_f_mmc_writable_media = FALSE;
3572 	mutex_exit(SD_MUTEX(un));
3573 
3574 	out_data = kmem_zalloc(SD_PROFILE_HEADER_LEN, KM_SLEEP);
3575 	rqbuf = kmem_zalloc(SENSE_LENGTH, KM_SLEEP);
3576 
3577 	rtn = sd_send_scsi_GET_CONFIGURATION(ssc, &com, rqbuf, SENSE_LENGTH,
3578 	    out_data, SD_PROFILE_HEADER_LEN, path_flag);
3579 
3580 	if (rtn != 0)
3581 		sd_ssc_assessment(ssc, SD_FMT_IGNORE);
3582 
3583 	mutex_enter(SD_MUTEX(un));
3584 	if (rtn == 0) {
3585 		/*
3586 		 * We have good information, check for writable DVD.
3587 		 */
3588 		if ((out_data[6] == 0) && (out_data[7] == 0x12)) {
3589 			un->un_f_mmc_writable_media = TRUE;
3590 			kmem_free(out_data, SD_PROFILE_HEADER_LEN);
3591 			kmem_free(rqbuf, SENSE_LENGTH);
3592 			return;
3593 		}
3594 	}
3595 
3596 	kmem_free(out_data, SD_PROFILE_HEADER_LEN);
3597 	kmem_free(rqbuf, SENSE_LENGTH);
3598 
3599 	/*
3600 	 * Determine if this is a RRD type device.
3601 	 */
3602 	mutex_exit(SD_MUTEX(un));
3603 	buf = kmem_zalloc(BUFLEN_MODE_CDROM_CAP, KM_SLEEP);
3604 	status = sd_send_scsi_MODE_SENSE(ssc, CDB_GROUP1, (uchar_t *)buf,
3605 	    BUFLEN_MODE_CDROM_CAP, MODEPAGE_CDROM_CAP, path_flag);
3606 
3607 	sd_ssc_assessment(ssc, SD_FMT_IGNORE);
3608 
3609 	mutex_enter(SD_MUTEX(un));
3610 	if (status != 0) {
3611 		/* command failed; just return */
3612 		kmem_free(buf, BUFLEN_MODE_CDROM_CAP);
3613 		return;
3614 	}
3615 
3616 	/* Get to the page data */
3617 	sense_mhp = (struct mode_header_grp2 *)buf;
3618 	bd_len = (sense_mhp->bdesc_length_hi << 8) | sense_mhp->bdesc_length_lo;
3619 	if (bd_len > MODE_BLK_DESC_LENGTH) {
3620 		/*
3621 		 * We did not get back the expected block descriptor length so
3622 		 * we cannot check the mode page.
3623 		 */
3624 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
3625 		    "sd_check_for_writable_cd: Mode Sense returned "
3626 		    "invalid block descriptor length\n");
3627 		kmem_free(buf, BUFLEN_MODE_CDROM_CAP);
3628 		return;
3629 	}
3630 
3631 	/*
3632 	 * If the device presents DVD or CD capabilities in the mode
3633 	 * page, we can return here since a RRD device will not have
3634 	 * these capabilities.
3635 	 */
3636 	sense_page = (uchar_t *)(buf + MODE_HEADER_LENGTH_GRP2 + bd_len);
3637 	if ((sense_page[2] & 0x3f) || (sense_page[3] & 0x3f)) {
3638 		kmem_free(buf, BUFLEN_MODE_CDROM_CAP);
3639 		return;
3640 	}
3641 	kmem_free(buf, BUFLEN_MODE_CDROM_CAP);
3642 
3643 	/*
3644 	 * If un->un_f_mmc_writable_media is still FALSE,
3645 	 * check for RRD type media.  A RRD device is identified
3646 	 * by the features RANDOM_WRITABLE and HARDWARE_DEFECT_MANAGEMENT.
3647 	 */
3648 	mutex_exit(SD_MUTEX(un));
3649 	out_data_rw = kmem_zalloc(SD_CURRENT_FEATURE_LEN, KM_SLEEP);
3650 	rqbuf_rw = kmem_zalloc(SENSE_LENGTH, KM_SLEEP);
3651 
3652 	rtn = sd_send_scsi_feature_GET_CONFIGURATION(ssc, &com, rqbuf_rw,
3653 	    SENSE_LENGTH, out_data_rw, SD_CURRENT_FEATURE_LEN,
3654 	    RANDOM_WRITABLE, path_flag);
3655 
3656 	sd_ssc_assessment(ssc, SD_FMT_IGNORE);
3657 	if (rtn != 0) {
3658 		kmem_free(out_data_rw, SD_CURRENT_FEATURE_LEN);
3659 		kmem_free(rqbuf_rw, SENSE_LENGTH);
3660 		mutex_enter(SD_MUTEX(un));
3661 		return;
3662 	}
3663 
3664 	out_data_hd = kmem_zalloc(SD_CURRENT_FEATURE_LEN, KM_SLEEP);
3665 	rqbuf_hd = kmem_zalloc(SENSE_LENGTH, KM_SLEEP);
3666 
3667 	rtn = sd_send_scsi_feature_GET_CONFIGURATION(ssc, &com, rqbuf_hd,
3668 	    SENSE_LENGTH, out_data_hd, SD_CURRENT_FEATURE_LEN,
3669 	    HARDWARE_DEFECT_MANAGEMENT, path_flag);
3670 
3671 	sd_ssc_assessment(ssc, SD_FMT_IGNORE);
3672 	mutex_enter(SD_MUTEX(un));
3673 	if (rtn == 0) {
3674 		/*
3675 		 * We have good information, check for random writable
3676 		 * and hardware defect features as current.
3677 		 */
3678 		if ((out_data_rw[9] & RANDOM_WRITABLE) &&
3679 		    (out_data_rw[10] & 0x1) &&
3680 		    (out_data_hd[9] & HARDWARE_DEFECT_MANAGEMENT) &&
3681 		    (out_data_hd[10] & 0x1)) {
3682 			un->un_f_mmc_writable_media = TRUE;
3683 		}
3684 	}
3685 
3686 	kmem_free(out_data_rw, SD_CURRENT_FEATURE_LEN);
3687 	kmem_free(rqbuf_rw, SENSE_LENGTH);
3688 	kmem_free(out_data_hd, SD_CURRENT_FEATURE_LEN);
3689 	kmem_free(rqbuf_hd, SENSE_LENGTH);
3690 }
3691 
3692 /*
3693  *    Function: sd_read_unit_properties
3694  *
3695  * Description: The following implements a property lookup mechanism.
3696  *		Properties for particular disks (keyed on vendor, model
3697  *		and rev numbers) are sought in the sd.conf file via
3698  *		sd_process_sdconf_file(), and if not found there, are
3699  *		looked for in a list hardcoded in this driver via
3700  *		sd_process_sdconf_table() Once located the properties
3701  *		are used to update the driver unit structure.
3702  *
3703  *   Arguments: un - driver soft state (unit) structure
3704  */
3705 
3706 static void
3707 sd_read_unit_properties(struct sd_lun *un)
3708 {
3709 	/*
3710 	 * sd_process_sdconf_file returns SD_FAILURE if it cannot find
3711 	 * the "sd-config-list" property (from the sd.conf file) or if
3712 	 * there was not a match for the inquiry vid/pid. If this event
3713 	 * occurs the static driver configuration table is searched for
3714 	 * a match.
3715 	 */
3716 	ASSERT(un != NULL);
3717 	if (sd_process_sdconf_file(un) == SD_FAILURE) {
3718 		sd_process_sdconf_table(un);
3719 	}
3720 
3721 	/* check for LSI device */
3722 	sd_is_lsi(un);
3723 
3724 
3725 }
3726 
3727 
3728 /*
3729  *    Function: sd_process_sdconf_file
3730  *
3731  * Description: Use ddi_prop_lookup(9F) to obtain the properties from the
3732  *		driver's config file (ie, sd.conf) and update the driver
3733  *		soft state structure accordingly.
3734  *
3735  *   Arguments: un - driver soft state (unit) structure
3736  *
3737  * Return Code: SD_SUCCESS - The properties were successfully set according
3738  *			     to the driver configuration file.
3739  *		SD_FAILURE - The driver config list was not obtained or
3740  *			     there was no vid/pid match. This indicates that
3741  *			     the static config table should be used.
3742  *
3743  * The config file has a property, "sd-config-list". Currently we support
3744  * two kinds of formats. For both formats, the value of this property
3745  * is a list of duplets:
3746  *
3747  *  sd-config-list=
3748  *	<duplet>,
3749  *	[,<duplet>]*;
3750  *
3751  * For the improved format, where
3752  *
3753  *     <duplet>:= "<vid+pid>","<tunable-list>"
3754  *
3755  * and
3756  *
3757  *     <tunable-list>:=   <tunable> [, <tunable> ]*;
3758  *     <tunable> =        <name> : <value>
3759  *
3760  * The <vid+pid> is the string that is returned by the target device on a
3761  * SCSI inquiry command, the <tunable-list> contains one or more tunables
3762  * to apply to all target devices with the specified <vid+pid>.
3763  *
3764  * Each <tunable> is a "<name> : <value>" pair.
3765  *
3766  * For the old format, the structure of each duplet is as follows:
3767  *
3768  *  <duplet>:= "<vid+pid>","<data-property-name_list>"
3769  *
3770  * The first entry of the duplet is the device ID string (the concatenated
3771  * vid & pid; not to be confused with a device_id).  This is defined in
3772  * the same way as in the sd_disk_table.
3773  *
3774  * The second part of the duplet is a string that identifies a
3775  * data-property-name-list. The data-property-name-list is defined as
3776  * follows:
3777  *
3778  *  <data-property-name-list>:=<data-property-name> [<data-property-name>]
3779  *
3780  * The syntax of <data-property-name> depends on the <version> field.
3781  *
3782  * If version = SD_CONF_VERSION_1 we have the following syntax:
3783  *
3784  * 	<data-property-name>:=<version>,<flags>,<prop0>,<prop1>,.....<propN>
3785  *
3786  * where the prop0 value will be used to set prop0 if bit0 set in the
3787  * flags, prop1 if bit1 set, etc. and N = SD_CONF_MAX_ITEMS -1
3788  *
3789  */
3790 
3791 static int
3792 sd_process_sdconf_file(struct sd_lun *un)
3793 {
3794 	char	**config_list = NULL;
3795 	uint_t	nelements;
3796 	char	*vidptr;
3797 	int	vidlen;
3798 	char	*dnlist_ptr;
3799 	char	*dataname_ptr;
3800 	char	*dataname_lasts;
3801 	int	*data_list = NULL;
3802 	uint_t	data_list_len;
3803 	int	rval = SD_FAILURE;
3804 	int	i;
3805 
3806 	ASSERT(un != NULL);
3807 
3808 	/* Obtain the configuration list associated with the .conf file */
3809 	if (ddi_prop_lookup_string_array(DDI_DEV_T_ANY, SD_DEVINFO(un),
3810 	    DDI_PROP_DONTPASS | DDI_PROP_NOTPROM, sd_config_list,
3811 	    &config_list, &nelements) != DDI_PROP_SUCCESS) {
3812 		return (SD_FAILURE);
3813 	}
3814 
3815 	/*
3816 	 * Compare vids in each duplet to the inquiry vid - if a match is
3817 	 * made, get the data value and update the soft state structure
3818 	 * accordingly.
3819 	 *
3820 	 * Each duplet should show as a pair of strings, return SD_FAILURE
3821 	 * otherwise.
3822 	 */
3823 	if (nelements & 1) {
3824 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
3825 		    "sd-config-list should show as pairs of strings.\n");
3826 		if (config_list)
3827 			ddi_prop_free(config_list);
3828 		return (SD_FAILURE);
3829 	}
3830 
3831 	for (i = 0; i < nelements; i += 2) {
3832 		/*
3833 		 * Note: The assumption here is that each vid entry is on
3834 		 * a unique line from its associated duplet.
3835 		 */
3836 		vidptr = config_list[i];
3837 		vidlen = (int)strlen(vidptr);
3838 		if ((vidlen == 0) ||
3839 		    (sd_sdconf_id_match(un, vidptr, vidlen) != SD_SUCCESS)) {
3840 			continue;
3841 		}
3842 
3843 		/*
3844 		 * dnlist contains 1 or more blank separated
3845 		 * data-property-name entries
3846 		 */
3847 		dnlist_ptr = config_list[i + 1];
3848 
3849 		if (strchr(dnlist_ptr, ':') != NULL) {
3850 			/*
3851 			 * Decode the improved format sd-config-list.
3852 			 */
3853 			sd_nvpair_str_decode(un, dnlist_ptr);
3854 		} else {
3855 			/*
3856 			 * The old format sd-config-list, loop through all
3857 			 * data-property-name entries in the
3858 			 * data-property-name-list
3859 			 * setting the properties for each.
3860 			 */
3861 			for (dataname_ptr = sd_strtok_r(dnlist_ptr, " \t",
3862 			    &dataname_lasts); dataname_ptr != NULL;
3863 			    dataname_ptr = sd_strtok_r(NULL, " \t",
3864 			    &dataname_lasts)) {
3865 				int version;
3866 
3867 				SD_INFO(SD_LOG_ATTACH_DETACH, un,
3868 				    "sd_process_sdconf_file: disk:%s, "
3869 				    "data:%s\n", vidptr, dataname_ptr);
3870 
3871 				/* Get the data list */
3872 				if (ddi_prop_lookup_int_array(DDI_DEV_T_ANY,
3873 				    SD_DEVINFO(un), 0, dataname_ptr, &data_list,
3874 				    &data_list_len) != DDI_PROP_SUCCESS) {
3875 					SD_INFO(SD_LOG_ATTACH_DETACH, un,
3876 					    "sd_process_sdconf_file: data "
3877 					    "property (%s) has no value\n",
3878 					    dataname_ptr);
3879 					continue;
3880 				}
3881 
3882 				version = data_list[0];
3883 
3884 				if (version == SD_CONF_VERSION_1) {
3885 					sd_tunables values;
3886 
3887 					/* Set the properties */
3888 					if (sd_chk_vers1_data(un, data_list[1],
3889 					    &data_list[2], data_list_len,
3890 					    dataname_ptr) == SD_SUCCESS) {
3891 						sd_get_tunables_from_conf(un,
3892 						    data_list[1], &data_list[2],
3893 						    &values);
3894 						sd_set_vers1_properties(un,
3895 						    data_list[1], &values);
3896 						rval = SD_SUCCESS;
3897 					} else {
3898 						rval = SD_FAILURE;
3899 					}
3900 				} else {
3901 					scsi_log(SD_DEVINFO(un), sd_label,
3902 					    CE_WARN, "data property %s version "
3903 					    "0x%x is invalid.",
3904 					    dataname_ptr, version);
3905 					rval = SD_FAILURE;
3906 				}
3907 				if (data_list)
3908 					ddi_prop_free(data_list);
3909 			}
3910 		}
3911 	}
3912 
3913 	/* free up the memory allocated by ddi_prop_lookup_string_array(). */
3914 	if (config_list) {
3915 		ddi_prop_free(config_list);
3916 	}
3917 
3918 	return (rval);
3919 }
3920 
3921 /*
3922  *    Function: sd_nvpair_str_decode()
3923  *
3924  * Description: Parse the improved format sd-config-list to get
3925  *    each entry of tunable, which includes a name-value pair.
3926  *    Then call sd_set_properties() to set the property.
3927  *
3928  *   Arguments: un - driver soft state (unit) structure
3929  *    nvpair_str - the tunable list
3930  */
3931 static void
3932 sd_nvpair_str_decode(struct sd_lun *un, char *nvpair_str)
3933 {
3934 	char	*nv, *name, *value, *token;
3935 	char	*nv_lasts, *v_lasts, *x_lasts;
3936 
3937 	for (nv = sd_strtok_r(nvpair_str, ",", &nv_lasts); nv != NULL;
3938 	    nv = sd_strtok_r(NULL, ",", &nv_lasts)) {
3939 		token = sd_strtok_r(nv, ":", &v_lasts);
3940 		name  = sd_strtok_r(token, " \t", &x_lasts);
3941 		token = sd_strtok_r(NULL, ":", &v_lasts);
3942 		value = sd_strtok_r(token, " \t", &x_lasts);
3943 		if (name == NULL || value == NULL) {
3944 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
3945 			    "sd_nvpair_str_decode: "
3946 			    "name or value is not valid!\n");
3947 		} else {
3948 			sd_set_properties(un, name, value);
3949 		}
3950 	}
3951 }
3952 
3953 /*
3954  *    Function: sd_strtok_r()
3955  *
3956  * Description: This function uses strpbrk and strspn to break
3957  *    string into tokens on sequentially subsequent calls. Return
3958  *    NULL when no non-separator characters remain. The first
3959  *    argument is NULL for subsequent calls.
3960  */
3961 static char *
3962 sd_strtok_r(char *string, const char *sepset, char **lasts)
3963 {
3964 	char	*q, *r;
3965 
3966 	/* First or subsequent call */
3967 	if (string == NULL)
3968 		string = *lasts;
3969 
3970 	if (string == NULL)
3971 		return (NULL);
3972 
3973 	/* Skip leading separators */
3974 	q = string + strspn(string, sepset);
3975 
3976 	if (*q == '\0')
3977 		return (NULL);
3978 
3979 	if ((r = strpbrk(q, sepset)) == NULL)
3980 		*lasts = NULL;
3981 	else {
3982 		*r = '\0';
3983 		*lasts = r + 1;
3984 	}
3985 	return (q);
3986 }
3987 
3988 /*
3989  *    Function: sd_set_properties()
3990  *
3991  * Description: Set device properties based on the improved
3992  *    format sd-config-list.
3993  *
3994  *   Arguments: un - driver soft state (unit) structure
3995  *    name  - supported tunable name
3996  *    value - tunable value
3997  */
3998 static void
3999 sd_set_properties(struct sd_lun *un, char *name, char *value)
4000 {
4001 	char	*endptr = NULL;
4002 	long	val = 0;
4003 
4004 	if (strcasecmp(name, "cache-nonvolatile") == 0) {
4005 		if (strcasecmp(value, "true") == 0) {
4006 			un->un_f_suppress_cache_flush = TRUE;
4007 		} else if (strcasecmp(value, "false") == 0) {
4008 			un->un_f_suppress_cache_flush = FALSE;
4009 		} else {
4010 			goto value_invalid;
4011 		}
4012 		SD_INFO(SD_LOG_ATTACH_DETACH, un, "sd_set_properties: "
4013 		    "suppress_cache_flush flag set to %d\n",
4014 		    un->un_f_suppress_cache_flush);
4015 		return;
4016 	}
4017 
4018 	if (strcasecmp(name, "controller-type") == 0) {
4019 		if (ddi_strtol(value, &endptr, 0, &val) == 0) {
4020 			un->un_ctype = val;
4021 		} else {
4022 			goto value_invalid;
4023 		}
4024 		SD_INFO(SD_LOG_ATTACH_DETACH, un, "sd_set_properties: "
4025 		    "ctype set to %d\n", un->un_ctype);
4026 		return;
4027 	}
4028 
4029 	if (strcasecmp(name, "delay-busy") == 0) {
4030 		if (ddi_strtol(value, &endptr, 0, &val) == 0) {
4031 			un->un_busy_timeout = drv_usectohz(val / 1000);
4032 		} else {
4033 			goto value_invalid;
4034 		}
4035 		SD_INFO(SD_LOG_ATTACH_DETACH, un, "sd_set_properties: "
4036 		    "busy_timeout set to %d\n", un->un_busy_timeout);
4037 		return;
4038 	}
4039 
4040 	if (strcasecmp(name, "disksort") == 0) {
4041 		if (strcasecmp(value, "true") == 0) {
4042 			un->un_f_disksort_disabled = FALSE;
4043 		} else if (strcasecmp(value, "false") == 0) {
4044 			un->un_f_disksort_disabled = TRUE;
4045 		} else {
4046 			goto value_invalid;
4047 		}
4048 		SD_INFO(SD_LOG_ATTACH_DETACH, un, "sd_set_properties: "
4049 		    "disksort disabled flag set to %d\n",
4050 		    un->un_f_disksort_disabled);
4051 		return;
4052 	}
4053 
4054 	if (strcasecmp(name, "power-condition") == 0) {
4055 		if (strcasecmp(value, "true") == 0) {
4056 			un->un_f_power_condition_disabled = FALSE;
4057 		} else if (strcasecmp(value, "false") == 0) {
4058 			un->un_f_power_condition_disabled = TRUE;
4059 		} else {
4060 			goto value_invalid;
4061 		}
4062 		SD_INFO(SD_LOG_ATTACH_DETACH, un, "sd_set_properties: "
4063 		    "power condition disabled flag set to %d\n",
4064 		    un->un_f_power_condition_disabled);
4065 		return;
4066 	}
4067 
4068 	if (strcasecmp(name, "timeout-releasereservation") == 0) {
4069 		if (ddi_strtol(value, &endptr, 0, &val) == 0) {
4070 			un->un_reserve_release_time = val;
4071 		} else {
4072 			goto value_invalid;
4073 		}
4074 		SD_INFO(SD_LOG_ATTACH_DETACH, un, "sd_set_properties: "
4075 		    "reservation release timeout set to %d\n",
4076 		    un->un_reserve_release_time);
4077 		return;
4078 	}
4079 
4080 	if (strcasecmp(name, "reset-lun") == 0) {
4081 		if (strcasecmp(value, "true") == 0) {
4082 			un->un_f_lun_reset_enabled = TRUE;
4083 		} else if (strcasecmp(value, "false") == 0) {
4084 			un->un_f_lun_reset_enabled = FALSE;
4085 		} else {
4086 			goto value_invalid;
4087 		}
4088 		SD_INFO(SD_LOG_ATTACH_DETACH, un, "sd_set_properties: "
4089 		    "lun reset enabled flag set to %d\n",
4090 		    un->un_f_lun_reset_enabled);
4091 		return;
4092 	}
4093 
4094 	if (strcasecmp(name, "retries-busy") == 0) {
4095 		if (ddi_strtol(value, &endptr, 0, &val) == 0) {
4096 			un->un_busy_retry_count = val;
4097 		} else {
4098 			goto value_invalid;
4099 		}
4100 		SD_INFO(SD_LOG_ATTACH_DETACH, un, "sd_set_properties: "
4101 		    "busy retry count set to %d\n", un->un_busy_retry_count);
4102 		return;
4103 	}
4104 
4105 	if (strcasecmp(name, "retries-timeout") == 0) {
4106 		if (ddi_strtol(value, &endptr, 0, &val) == 0) {
4107 			un->un_retry_count = val;
4108 		} else {
4109 			goto value_invalid;
4110 		}
4111 		SD_INFO(SD_LOG_ATTACH_DETACH, un, "sd_set_properties: "
4112 		    "timeout retry count set to %d\n", un->un_retry_count);
4113 		return;
4114 	}
4115 
4116 	if (strcasecmp(name, "retries-notready") == 0) {
4117 		if (ddi_strtol(value, &endptr, 0, &val) == 0) {
4118 			un->un_notready_retry_count = val;
4119 		} else {
4120 			goto value_invalid;
4121 		}
4122 		SD_INFO(SD_LOG_ATTACH_DETACH, un, "sd_set_properties: "
4123 		    "notready retry count set to %d\n",
4124 		    un->un_notready_retry_count);
4125 		return;
4126 	}
4127 
4128 	if (strcasecmp(name, "retries-reset") == 0) {
4129 		if (ddi_strtol(value, &endptr, 0, &val) == 0) {
4130 			un->un_reset_retry_count = val;
4131 		} else {
4132 			goto value_invalid;
4133 		}
4134 		SD_INFO(SD_LOG_ATTACH_DETACH, un, "sd_set_properties: "
4135 		    "reset retry count set to %d\n",
4136 		    un->un_reset_retry_count);
4137 		return;
4138 	}
4139 
4140 	if (strcasecmp(name, "throttle-max") == 0) {
4141 		if (ddi_strtol(value, &endptr, 0, &val) == 0) {
4142 			un->un_saved_throttle = un->un_throttle = val;
4143 		} else {
4144 			goto value_invalid;
4145 		}
4146 		SD_INFO(SD_LOG_ATTACH_DETACH, un, "sd_set_properties: "
4147 		    "throttle set to %d\n", un->un_throttle);
4148 	}
4149 
4150 	if (strcasecmp(name, "throttle-min") == 0) {
4151 		if (ddi_strtol(value, &endptr, 0, &val) == 0) {
4152 			un->un_min_throttle = val;
4153 		} else {
4154 			goto value_invalid;
4155 		}
4156 		SD_INFO(SD_LOG_ATTACH_DETACH, un, "sd_set_properties: "
4157 		    "min throttle set to %d\n", un->un_min_throttle);
4158 	}
4159 
4160 	if (strcasecmp(name, "rmw-type") == 0) {
4161 		if (ddi_strtol(value, &endptr, 0, &val) == 0) {
4162 			un->un_f_rmw_type = val;
4163 		} else {
4164 			goto value_invalid;
4165 		}
4166 		SD_INFO(SD_LOG_ATTACH_DETACH, un, "sd_set_properties: "
4167 		    "RMW type set to %d\n", un->un_f_rmw_type);
4168 	}
4169 
4170 	/*
4171 	 * Validate the throttle values.
4172 	 * If any of the numbers are invalid, set everything to defaults.
4173 	 */
4174 	if ((un->un_throttle < SD_LOWEST_VALID_THROTTLE) ||
4175 	    (un->un_min_throttle < SD_LOWEST_VALID_THROTTLE) ||
4176 	    (un->un_min_throttle > un->un_throttle)) {
4177 		un->un_saved_throttle = un->un_throttle = sd_max_throttle;
4178 		un->un_min_throttle = sd_min_throttle;
4179 	}
4180 	return;
4181 
4182 value_invalid:
4183 	SD_INFO(SD_LOG_ATTACH_DETACH, un, "sd_set_properties: "
4184 	    "value of prop %s is invalid\n", name);
4185 }
4186 
4187 /*
4188  *    Function: sd_get_tunables_from_conf()
4189  *
4190  *
4191  *    This function reads the data list from the sd.conf file and pulls
4192  *    the values that can have numeric values as arguments and places
4193  *    the values in the appropriate sd_tunables member.
4194  *    Since the order of the data list members varies across platforms
4195  *    This function reads them from the data list in a platform specific
4196  *    order and places them into the correct sd_tunable member that is
4197  *    consistent across all platforms.
4198  */
4199 static void
4200 sd_get_tunables_from_conf(struct sd_lun *un, int flags, int *data_list,
4201     sd_tunables *values)
4202 {
4203 	int i;
4204 	int mask;
4205 
4206 	bzero(values, sizeof (sd_tunables));
4207 
4208 	for (i = 0; i < SD_CONF_MAX_ITEMS; i++) {
4209 
4210 		mask = 1 << i;
4211 		if (mask > flags) {
4212 			break;
4213 		}
4214 
4215 		switch (mask & flags) {
4216 		case 0:	/* This mask bit not set in flags */
4217 			continue;
4218 		case SD_CONF_BSET_THROTTLE:
4219 			values->sdt_throttle = data_list[i];
4220 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
4221 			    "sd_get_tunables_from_conf: throttle = %d\n",
4222 			    values->sdt_throttle);
4223 			break;
4224 		case SD_CONF_BSET_CTYPE:
4225 			values->sdt_ctype = data_list[i];
4226 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
4227 			    "sd_get_tunables_from_conf: ctype = %d\n",
4228 			    values->sdt_ctype);
4229 			break;
4230 		case SD_CONF_BSET_NRR_COUNT:
4231 			values->sdt_not_rdy_retries = data_list[i];
4232 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
4233 			    "sd_get_tunables_from_conf: not_rdy_retries = %d\n",
4234 			    values->sdt_not_rdy_retries);
4235 			break;
4236 		case SD_CONF_BSET_BSY_RETRY_COUNT:
4237 			values->sdt_busy_retries = data_list[i];
4238 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
4239 			    "sd_get_tunables_from_conf: busy_retries = %d\n",
4240 			    values->sdt_busy_retries);
4241 			break;
4242 		case SD_CONF_BSET_RST_RETRIES:
4243 			values->sdt_reset_retries = data_list[i];
4244 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
4245 			    "sd_get_tunables_from_conf: reset_retries = %d\n",
4246 			    values->sdt_reset_retries);
4247 			break;
4248 		case SD_CONF_BSET_RSV_REL_TIME:
4249 			values->sdt_reserv_rel_time = data_list[i];
4250 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
4251 			    "sd_get_tunables_from_conf: reserv_rel_time = %d\n",
4252 			    values->sdt_reserv_rel_time);
4253 			break;
4254 		case SD_CONF_BSET_MIN_THROTTLE:
4255 			values->sdt_min_throttle = data_list[i];
4256 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
4257 			    "sd_get_tunables_from_conf: min_throttle = %d\n",
4258 			    values->sdt_min_throttle);
4259 			break;
4260 		case SD_CONF_BSET_DISKSORT_DISABLED:
4261 			values->sdt_disk_sort_dis = data_list[i];
4262 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
4263 			    "sd_get_tunables_from_conf: disk_sort_dis = %d\n",
4264 			    values->sdt_disk_sort_dis);
4265 			break;
4266 		case SD_CONF_BSET_LUN_RESET_ENABLED:
4267 			values->sdt_lun_reset_enable = data_list[i];
4268 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
4269 			    "sd_get_tunables_from_conf: lun_reset_enable = %d"
4270 			    "\n", values->sdt_lun_reset_enable);
4271 			break;
4272 		case SD_CONF_BSET_CACHE_IS_NV:
4273 			values->sdt_suppress_cache_flush = data_list[i];
4274 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
4275 			    "sd_get_tunables_from_conf: \
4276 			    suppress_cache_flush = %d"
4277 			    "\n", values->sdt_suppress_cache_flush);
4278 			break;
4279 		case SD_CONF_BSET_PC_DISABLED:
4280 			values->sdt_disk_sort_dis = data_list[i];
4281 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
4282 			    "sd_get_tunables_from_conf: power_condition_dis = "
4283 			    "%d\n", values->sdt_power_condition_dis);
4284 			break;
4285 		}
4286 	}
4287 }
4288 
4289 /*
4290  *    Function: sd_process_sdconf_table
4291  *
4292  * Description: Search the static configuration table for a match on the
4293  *		inquiry vid/pid and update the driver soft state structure
4294  *		according to the table property values for the device.
4295  *
4296  *		The form of a configuration table entry is:
4297  *		  <vid+pid>,<flags>,<property-data>
4298  *		  "SEAGATE ST42400N",1,0x40000,
4299  *		  0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1;
4300  *
4301  *   Arguments: un - driver soft state (unit) structure
4302  */
4303 
4304 static void
4305 sd_process_sdconf_table(struct sd_lun *un)
4306 {
4307 	char	*id = NULL;
4308 	int	table_index;
4309 	int	idlen;
4310 
4311 	ASSERT(un != NULL);
4312 	for (table_index = 0; table_index < sd_disk_table_size;
4313 	    table_index++) {
4314 		id = sd_disk_table[table_index].device_id;
4315 		idlen = strlen(id);
4316 		if (idlen == 0) {
4317 			continue;
4318 		}
4319 
4320 		/*
4321 		 * The static configuration table currently does not
4322 		 * implement version 10 properties. Additionally,
4323 		 * multiple data-property-name entries are not
4324 		 * implemented in the static configuration table.
4325 		 */
4326 		if (sd_sdconf_id_match(un, id, idlen) == SD_SUCCESS) {
4327 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
4328 			    "sd_process_sdconf_table: disk %s\n", id);
4329 			sd_set_vers1_properties(un,
4330 			    sd_disk_table[table_index].flags,
4331 			    sd_disk_table[table_index].properties);
4332 			break;
4333 		}
4334 	}
4335 }
4336 
4337 
4338 /*
4339  *    Function: sd_sdconf_id_match
4340  *
4341  * Description: This local function implements a case sensitive vid/pid
4342  *		comparison as well as the boundary cases of wild card and
4343  *		multiple blanks.
4344  *
4345  *		Note: An implicit assumption made here is that the scsi
4346  *		inquiry structure will always keep the vid, pid and
4347  *		revision strings in consecutive sequence, so they can be
4348  *		read as a single string. If this assumption is not the
4349  *		case, a separate string, to be used for the check, needs
4350  *		to be built with these strings concatenated.
4351  *
4352  *   Arguments: un - driver soft state (unit) structure
4353  *		id - table or config file vid/pid
4354  *		idlen  - length of the vid/pid (bytes)
4355  *
4356  * Return Code: SD_SUCCESS - Indicates a match with the inquiry vid/pid
4357  *		SD_FAILURE - Indicates no match with the inquiry vid/pid
4358  */
4359 
4360 static int
4361 sd_sdconf_id_match(struct sd_lun *un, char *id, int idlen)
4362 {
4363 	struct scsi_inquiry	*sd_inq;
4364 	int 			rval = SD_SUCCESS;
4365 
4366 	ASSERT(un != NULL);
4367 	sd_inq = un->un_sd->sd_inq;
4368 	ASSERT(id != NULL);
4369 
4370 	/*
4371 	 * We use the inq_vid as a pointer to a buffer containing the
4372 	 * vid and pid and use the entire vid/pid length of the table
4373 	 * entry for the comparison. This works because the inq_pid
4374 	 * data member follows inq_vid in the scsi_inquiry structure.
4375 	 */
4376 	if (strncasecmp(sd_inq->inq_vid, id, idlen) != 0) {
4377 		/*
4378 		 * The user id string is compared to the inquiry vid/pid
4379 		 * using a case insensitive comparison and ignoring
4380 		 * multiple spaces.
4381 		 */
4382 		rval = sd_blank_cmp(un, id, idlen);
4383 		if (rval != SD_SUCCESS) {
4384 			/*
4385 			 * User id strings that start and end with a "*"
4386 			 * are a special case. These do not have a
4387 			 * specific vendor, and the product string can
4388 			 * appear anywhere in the 16 byte PID portion of
4389 			 * the inquiry data. This is a simple strstr()
4390 			 * type search for the user id in the inquiry data.
4391 			 */
4392 			if ((id[0] == '*') && (id[idlen - 1] == '*')) {
4393 				char	*pidptr = &id[1];
4394 				int	i;
4395 				int	j;
4396 				int	pidstrlen = idlen - 2;
4397 				j = sizeof (SD_INQUIRY(un)->inq_pid) -
4398 				    pidstrlen;
4399 
4400 				if (j < 0) {
4401 					return (SD_FAILURE);
4402 				}
4403 				for (i = 0; i < j; i++) {
4404 					if (bcmp(&SD_INQUIRY(un)->inq_pid[i],
4405 					    pidptr, pidstrlen) == 0) {
4406 						rval = SD_SUCCESS;
4407 						break;
4408 					}
4409 				}
4410 			}
4411 		}
4412 	}
4413 	return (rval);
4414 }
4415 
4416 
4417 /*
4418  *    Function: sd_blank_cmp
4419  *
4420  * Description: If the id string starts and ends with a space, treat
4421  *		multiple consecutive spaces as equivalent to a single
4422  *		space. For example, this causes a sd_disk_table entry
4423  *		of " NEC CDROM " to match a device's id string of
4424  *		"NEC       CDROM".
4425  *
4426  *		Note: The success exit condition for this routine is if
4427  *		the pointer to the table entry is '\0' and the cnt of
4428  *		the inquiry length is zero. This will happen if the inquiry
4429  *		string returned by the device is padded with spaces to be
4430  *		exactly 24 bytes in length (8 byte vid + 16 byte pid). The
4431  *		SCSI spec states that the inquiry string is to be padded with
4432  *		spaces.
4433  *
4434  *   Arguments: un - driver soft state (unit) structure
4435  *		id - table or config file vid/pid
4436  *		idlen  - length of the vid/pid (bytes)
4437  *
4438  * Return Code: SD_SUCCESS - Indicates a match with the inquiry vid/pid
4439  *		SD_FAILURE - Indicates no match with the inquiry vid/pid
4440  */
4441 
4442 static int
4443 sd_blank_cmp(struct sd_lun *un, char *id, int idlen)
4444 {
4445 	char		*p1;
4446 	char		*p2;
4447 	int		cnt;
4448 	cnt = sizeof (SD_INQUIRY(un)->inq_vid) +
4449 	    sizeof (SD_INQUIRY(un)->inq_pid);
4450 
4451 	ASSERT(un != NULL);
4452 	p2 = un->un_sd->sd_inq->inq_vid;
4453 	ASSERT(id != NULL);
4454 	p1 = id;
4455 
4456 	if ((id[0] == ' ') && (id[idlen - 1] == ' ')) {
4457 		/*
4458 		 * Note: string p1 is terminated by a NUL but string p2
4459 		 * isn't.  The end of p2 is determined by cnt.
4460 		 */
4461 		for (;;) {
4462 			/* skip over any extra blanks in both strings */
4463 			while ((*p1 != '\0') && (*p1 == ' ')) {
4464 				p1++;
4465 			}
4466 			while ((cnt != 0) && (*p2 == ' ')) {
4467 				p2++;
4468 				cnt--;
4469 			}
4470 
4471 			/* compare the two strings */
4472 			if ((cnt == 0) ||
4473 			    (SD_TOUPPER(*p1) != SD_TOUPPER(*p2))) {
4474 				break;
4475 			}
4476 			while ((cnt > 0) &&
4477 			    (SD_TOUPPER(*p1) == SD_TOUPPER(*p2))) {
4478 				p1++;
4479 				p2++;
4480 				cnt--;
4481 			}
4482 		}
4483 	}
4484 
4485 	/* return SD_SUCCESS if both strings match */
4486 	return (((*p1 == '\0') && (cnt == 0)) ? SD_SUCCESS : SD_FAILURE);
4487 }
4488 
4489 
4490 /*
4491  *    Function: sd_chk_vers1_data
4492  *
4493  * Description: Verify the version 1 device properties provided by the
4494  *		user via the configuration file
4495  *
4496  *   Arguments: un	     - driver soft state (unit) structure
4497  *		flags	     - integer mask indicating properties to be set
4498  *		prop_list    - integer list of property values
4499  *		list_len     - number of the elements
4500  *
4501  * Return Code: SD_SUCCESS - Indicates the user provided data is valid
4502  *		SD_FAILURE - Indicates the user provided data is invalid
4503  */
4504 
4505 static int
4506 sd_chk_vers1_data(struct sd_lun *un, int flags, int *prop_list,
4507     int list_len, char *dataname_ptr)
4508 {
4509 	int i;
4510 	int mask = 1;
4511 	int index = 0;
4512 
4513 	ASSERT(un != NULL);
4514 
4515 	/* Check for a NULL property name and list */
4516 	if (dataname_ptr == NULL) {
4517 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
4518 		    "sd_chk_vers1_data: NULL data property name.");
4519 		return (SD_FAILURE);
4520 	}
4521 	if (prop_list == NULL) {
4522 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
4523 		    "sd_chk_vers1_data: %s NULL data property list.",
4524 		    dataname_ptr);
4525 		return (SD_FAILURE);
4526 	}
4527 
4528 	/* Display a warning if undefined bits are set in the flags */
4529 	if (flags & ~SD_CONF_BIT_MASK) {
4530 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
4531 		    "sd_chk_vers1_data: invalid bits 0x%x in data list %s. "
4532 		    "Properties not set.",
4533 		    (flags & ~SD_CONF_BIT_MASK), dataname_ptr);
4534 		return (SD_FAILURE);
4535 	}
4536 
4537 	/*
4538 	 * Verify the length of the list by identifying the highest bit set
4539 	 * in the flags and validating that the property list has a length
4540 	 * up to the index of this bit.
4541 	 */
4542 	for (i = 0; i < SD_CONF_MAX_ITEMS; i++) {
4543 		if (flags & mask) {
4544 			index++;
4545 		}
4546 		mask = 1 << i;
4547 	}
4548 	if (list_len < (index + 2)) {
4549 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
4550 		    "sd_chk_vers1_data: "
4551 		    "Data property list %s size is incorrect. "
4552 		    "Properties not set.", dataname_ptr);
4553 		scsi_log(SD_DEVINFO(un), sd_label, CE_CONT, "Size expected: "
4554 		    "version + 1 flagword + %d properties", SD_CONF_MAX_ITEMS);
4555 		return (SD_FAILURE);
4556 	}
4557 	return (SD_SUCCESS);
4558 }
4559 
4560 
4561 /*
4562  *    Function: sd_set_vers1_properties
4563  *
4564  * Description: Set version 1 device properties based on a property list
4565  *		retrieved from the driver configuration file or static
4566  *		configuration table. Version 1 properties have the format:
4567  *
4568  * 	<data-property-name>:=<version>,<flags>,<prop0>,<prop1>,.....<propN>
4569  *
4570  *		where the prop0 value will be used to set prop0 if bit0
4571  *		is set in the flags
4572  *
4573  *   Arguments: un	     - driver soft state (unit) structure
4574  *		flags	     - integer mask indicating properties to be set
4575  *		prop_list    - integer list of property values
4576  */
4577 
4578 static void
4579 sd_set_vers1_properties(struct sd_lun *un, int flags, sd_tunables *prop_list)
4580 {
4581 	ASSERT(un != NULL);
4582 
4583 	/*
4584 	 * Set the flag to indicate cache is to be disabled. An attempt
4585 	 * to disable the cache via sd_cache_control() will be made
4586 	 * later during attach once the basic initialization is complete.
4587 	 */
4588 	if (flags & SD_CONF_BSET_NOCACHE) {
4589 		un->un_f_opt_disable_cache = TRUE;
4590 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
4591 		    "sd_set_vers1_properties: caching disabled flag set\n");
4592 	}
4593 
4594 	/* CD-specific configuration parameters */
4595 	if (flags & SD_CONF_BSET_PLAYMSF_BCD) {
4596 		un->un_f_cfg_playmsf_bcd = TRUE;
4597 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
4598 		    "sd_set_vers1_properties: playmsf_bcd set\n");
4599 	}
4600 	if (flags & SD_CONF_BSET_READSUB_BCD) {
4601 		un->un_f_cfg_readsub_bcd = TRUE;
4602 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
4603 		    "sd_set_vers1_properties: readsub_bcd set\n");
4604 	}
4605 	if (flags & SD_CONF_BSET_READ_TOC_TRK_BCD) {
4606 		un->un_f_cfg_read_toc_trk_bcd = TRUE;
4607 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
4608 		    "sd_set_vers1_properties: read_toc_trk_bcd set\n");
4609 	}
4610 	if (flags & SD_CONF_BSET_READ_TOC_ADDR_BCD) {
4611 		un->un_f_cfg_read_toc_addr_bcd = TRUE;
4612 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
4613 		    "sd_set_vers1_properties: read_toc_addr_bcd set\n");
4614 	}
4615 	if (flags & SD_CONF_BSET_NO_READ_HEADER) {
4616 		un->un_f_cfg_no_read_header = TRUE;
4617 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
4618 		    "sd_set_vers1_properties: no_read_header set\n");
4619 	}
4620 	if (flags & SD_CONF_BSET_READ_CD_XD4) {
4621 		un->un_f_cfg_read_cd_xd4 = TRUE;
4622 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
4623 		    "sd_set_vers1_properties: read_cd_xd4 set\n");
4624 	}
4625 
4626 	/* Support for devices which do not have valid/unique serial numbers */
4627 	if (flags & SD_CONF_BSET_FAB_DEVID) {
4628 		un->un_f_opt_fab_devid = TRUE;
4629 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
4630 		    "sd_set_vers1_properties: fab_devid bit set\n");
4631 	}
4632 
4633 	/* Support for user throttle configuration */
4634 	if (flags & SD_CONF_BSET_THROTTLE) {
4635 		ASSERT(prop_list != NULL);
4636 		un->un_saved_throttle = un->un_throttle =
4637 		    prop_list->sdt_throttle;
4638 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
4639 		    "sd_set_vers1_properties: throttle set to %d\n",
4640 		    prop_list->sdt_throttle);
4641 	}
4642 
4643 	/* Set the per disk retry count according to the conf file or table. */
4644 	if (flags & SD_CONF_BSET_NRR_COUNT) {
4645 		ASSERT(prop_list != NULL);
4646 		if (prop_list->sdt_not_rdy_retries) {
4647 			un->un_notready_retry_count =
4648 			    prop_list->sdt_not_rdy_retries;
4649 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
4650 			    "sd_set_vers1_properties: not ready retry count"
4651 			    " set to %d\n", un->un_notready_retry_count);
4652 		}
4653 	}
4654 
4655 	/* The controller type is reported for generic disk driver ioctls */
4656 	if (flags & SD_CONF_BSET_CTYPE) {
4657 		ASSERT(prop_list != NULL);
4658 		switch (prop_list->sdt_ctype) {
4659 		case CTYPE_CDROM:
4660 			un->un_ctype = prop_list->sdt_ctype;
4661 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
4662 			    "sd_set_vers1_properties: ctype set to "
4663 			    "CTYPE_CDROM\n");
4664 			break;
4665 		case CTYPE_CCS:
4666 			un->un_ctype = prop_list->sdt_ctype;
4667 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
4668 			    "sd_set_vers1_properties: ctype set to "
4669 			    "CTYPE_CCS\n");
4670 			break;
4671 		case CTYPE_ROD:		/* RW optical */
4672 			un->un_ctype = prop_list->sdt_ctype;
4673 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
4674 			    "sd_set_vers1_properties: ctype set to "
4675 			    "CTYPE_ROD\n");
4676 			break;
4677 		default:
4678 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
4679 			    "sd_set_vers1_properties: Could not set "
4680 			    "invalid ctype value (%d)",
4681 			    prop_list->sdt_ctype);
4682 		}
4683 	}
4684 
4685 	/* Purple failover timeout */
4686 	if (flags & SD_CONF_BSET_BSY_RETRY_COUNT) {
4687 		ASSERT(prop_list != NULL);
4688 		un->un_busy_retry_count =
4689 		    prop_list->sdt_busy_retries;
4690 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
4691 		    "sd_set_vers1_properties: "
4692 		    "busy retry count set to %d\n",
4693 		    un->un_busy_retry_count);
4694 	}
4695 
4696 	/* Purple reset retry count */
4697 	if (flags & SD_CONF_BSET_RST_RETRIES) {
4698 		ASSERT(prop_list != NULL);
4699 		un->un_reset_retry_count =
4700 		    prop_list->sdt_reset_retries;
4701 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
4702 		    "sd_set_vers1_properties: "
4703 		    "reset retry count set to %d\n",
4704 		    un->un_reset_retry_count);
4705 	}
4706 
4707 	/* Purple reservation release timeout */
4708 	if (flags & SD_CONF_BSET_RSV_REL_TIME) {
4709 		ASSERT(prop_list != NULL);
4710 		un->un_reserve_release_time =
4711 		    prop_list->sdt_reserv_rel_time;
4712 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
4713 		    "sd_set_vers1_properties: "
4714 		    "reservation release timeout set to %d\n",
4715 		    un->un_reserve_release_time);
4716 	}
4717 
4718 	/*
4719 	 * Driver flag telling the driver to verify that no commands are pending
4720 	 * for a device before issuing a Test Unit Ready. This is a workaround
4721 	 * for a firmware bug in some Seagate eliteI drives.
4722 	 */
4723 	if (flags & SD_CONF_BSET_TUR_CHECK) {
4724 		un->un_f_cfg_tur_check = TRUE;
4725 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
4726 		    "sd_set_vers1_properties: tur queue check set\n");
4727 	}
4728 
4729 	if (flags & SD_CONF_BSET_MIN_THROTTLE) {
4730 		un->un_min_throttle = prop_list->sdt_min_throttle;
4731 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
4732 		    "sd_set_vers1_properties: min throttle set to %d\n",
4733 		    un->un_min_throttle);
4734 	}
4735 
4736 	if (flags & SD_CONF_BSET_DISKSORT_DISABLED) {
4737 		un->un_f_disksort_disabled =
4738 		    (prop_list->sdt_disk_sort_dis != 0) ?
4739 		    TRUE : FALSE;
4740 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
4741 		    "sd_set_vers1_properties: disksort disabled "
4742 		    "flag set to %d\n",
4743 		    prop_list->sdt_disk_sort_dis);
4744 	}
4745 
4746 	if (flags & SD_CONF_BSET_LUN_RESET_ENABLED) {
4747 		un->un_f_lun_reset_enabled =
4748 		    (prop_list->sdt_lun_reset_enable != 0) ?
4749 		    TRUE : FALSE;
4750 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
4751 		    "sd_set_vers1_properties: lun reset enabled "
4752 		    "flag set to %d\n",
4753 		    prop_list->sdt_lun_reset_enable);
4754 	}
4755 
4756 	if (flags & SD_CONF_BSET_CACHE_IS_NV) {
4757 		un->un_f_suppress_cache_flush =
4758 		    (prop_list->sdt_suppress_cache_flush != 0) ?
4759 		    TRUE : FALSE;
4760 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
4761 		    "sd_set_vers1_properties: suppress_cache_flush "
4762 		    "flag set to %d\n",
4763 		    prop_list->sdt_suppress_cache_flush);
4764 	}
4765 
4766 	if (flags & SD_CONF_BSET_PC_DISABLED) {
4767 		un->un_f_power_condition_disabled =
4768 		    (prop_list->sdt_power_condition_dis != 0) ?
4769 		    TRUE : FALSE;
4770 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
4771 		    "sd_set_vers1_properties: power_condition_disabled "
4772 		    "flag set to %d\n",
4773 		    prop_list->sdt_power_condition_dis);
4774 	}
4775 
4776 	/*
4777 	 * Validate the throttle values.
4778 	 * If any of the numbers are invalid, set everything to defaults.
4779 	 */
4780 	if ((un->un_throttle < SD_LOWEST_VALID_THROTTLE) ||
4781 	    (un->un_min_throttle < SD_LOWEST_VALID_THROTTLE) ||
4782 	    (un->un_min_throttle > un->un_throttle)) {
4783 		un->un_saved_throttle = un->un_throttle = sd_max_throttle;
4784 		un->un_min_throttle = sd_min_throttle;
4785 	}
4786 }
4787 
4788 /*
4789  *   Function: sd_is_lsi()
4790  *
4791  *   Description: Check for lsi devices, step through the static device
4792  *	table to match vid/pid.
4793  *
4794  *   Args: un - ptr to sd_lun
4795  *
4796  *   Notes:  When creating new LSI property, need to add the new LSI property
4797  *		to this function.
4798  */
4799 static void
4800 sd_is_lsi(struct sd_lun *un)
4801 {
4802 	char	*id = NULL;
4803 	int	table_index;
4804 	int	idlen;
4805 	void	*prop;
4806 
4807 	ASSERT(un != NULL);
4808 	for (table_index = 0; table_index < sd_disk_table_size;
4809 	    table_index++) {
4810 		id = sd_disk_table[table_index].device_id;
4811 		idlen = strlen(id);
4812 		if (idlen == 0) {
4813 			continue;
4814 		}
4815 
4816 		if (sd_sdconf_id_match(un, id, idlen) == SD_SUCCESS) {
4817 			prop = sd_disk_table[table_index].properties;
4818 			if (prop == &lsi_properties ||
4819 			    prop == &lsi_oem_properties ||
4820 			    prop == &lsi_properties_scsi ||
4821 			    prop == &symbios_properties) {
4822 				un->un_f_cfg_is_lsi = TRUE;
4823 			}
4824 			break;
4825 		}
4826 	}
4827 }
4828 
4829 /*
4830  *    Function: sd_get_physical_geometry
4831  *
4832  * Description: Retrieve the MODE SENSE page 3 (Format Device Page) and
4833  *		MODE SENSE page 4 (Rigid Disk Drive Geometry Page) from the
4834  *		target, and use this information to initialize the physical
4835  *		geometry cache specified by pgeom_p.
4836  *
4837  *		MODE SENSE is an optional command, so failure in this case
4838  *		does not necessarily denote an error. We want to use the
4839  *		MODE SENSE commands to derive the physical geometry of the
4840  *		device, but if either command fails, the logical geometry is
4841  *		used as the fallback for disk label geometry in cmlb.
4842  *
4843  *		This requires that un->un_blockcount and un->un_tgt_blocksize
4844  *		have already been initialized for the current target and
4845  *		that the current values be passed as args so that we don't
4846  *		end up ever trying to use -1 as a valid value. This could
4847  *		happen if either value is reset while we're not holding
4848  *		the mutex.
4849  *
4850  *   Arguments: un - driver soft state (unit) structure
4851  *		path_flag - SD_PATH_DIRECT to use the USCSI "direct" chain and
4852  *			the normal command waitq, or SD_PATH_DIRECT_PRIORITY
4853  *			to use the USCSI "direct" chain and bypass the normal
4854  *			command waitq.
4855  *
4856  *     Context: Kernel thread only (can sleep).
4857  */
4858 
4859 static int
4860 sd_get_physical_geometry(struct sd_lun *un, cmlb_geom_t *pgeom_p,
4861 	diskaddr_t capacity, int lbasize, int path_flag)
4862 {
4863 	struct	mode_format	*page3p;
4864 	struct	mode_geometry	*page4p;
4865 	struct	mode_header	*headerp;
4866 	int	sector_size;
4867 	int	nsect;
4868 	int	nhead;
4869 	int	ncyl;
4870 	int	intrlv;
4871 	int	spc;
4872 	diskaddr_t	modesense_capacity;
4873 	int	rpm;
4874 	int	bd_len;
4875 	int	mode_header_length;
4876 	uchar_t	*p3bufp;
4877 	uchar_t	*p4bufp;
4878 	int	cdbsize;
4879 	int 	ret = EIO;
4880 	sd_ssc_t *ssc;
4881 	int	status;
4882 
4883 	ASSERT(un != NULL);
4884 
4885 	if (lbasize == 0) {
4886 		if (ISCD(un)) {
4887 			lbasize = 2048;
4888 		} else {
4889 			lbasize = un->un_sys_blocksize;
4890 		}
4891 	}
4892 	pgeom_p->g_secsize = (unsigned short)lbasize;
4893 
4894 	/*
4895 	 * If the unit is a cd/dvd drive MODE SENSE page three
4896 	 * and MODE SENSE page four are reserved (see SBC spec
4897 	 * and MMC spec). To prevent soft errors just return
4898 	 * using the default LBA size.
4899 	 */
4900 	if (ISCD(un))
4901 		return (ret);
4902 
4903 	cdbsize = (un->un_f_cfg_is_atapi == TRUE) ? CDB_GROUP2 : CDB_GROUP0;
4904 
4905 	/*
4906 	 * Retrieve MODE SENSE page 3 - Format Device Page
4907 	 */
4908 	p3bufp = kmem_zalloc(SD_MODE_SENSE_PAGE3_LENGTH, KM_SLEEP);
4909 	ssc = sd_ssc_init(un);
4910 	status = sd_send_scsi_MODE_SENSE(ssc, cdbsize, p3bufp,
4911 	    SD_MODE_SENSE_PAGE3_LENGTH, SD_MODE_SENSE_PAGE3_CODE, path_flag);
4912 	if (status != 0) {
4913 		SD_ERROR(SD_LOG_COMMON, un,
4914 		    "sd_get_physical_geometry: mode sense page 3 failed\n");
4915 		goto page3_exit;
4916 	}
4917 
4918 	/*
4919 	 * Determine size of Block Descriptors in order to locate the mode
4920 	 * page data.  ATAPI devices return 0, SCSI devices should return
4921 	 * MODE_BLK_DESC_LENGTH.
4922 	 */
4923 	headerp = (struct mode_header *)p3bufp;
4924 	if (un->un_f_cfg_is_atapi == TRUE) {
4925 		struct mode_header_grp2 *mhp =
4926 		    (struct mode_header_grp2 *)headerp;
4927 		mode_header_length = MODE_HEADER_LENGTH_GRP2;
4928 		bd_len = (mhp->bdesc_length_hi << 8) | mhp->bdesc_length_lo;
4929 	} else {
4930 		mode_header_length = MODE_HEADER_LENGTH;
4931 		bd_len = ((struct mode_header *)headerp)->bdesc_length;
4932 	}
4933 
4934 	if (bd_len > MODE_BLK_DESC_LENGTH) {
4935 		sd_ssc_set_info(ssc, SSC_FLAGS_INVALID_DATA, SD_LOG_COMMON,
4936 		    "sd_get_physical_geometry: received unexpected bd_len "
4937 		    "of %d, page3\n", bd_len);
4938 		status = EIO;
4939 		goto page3_exit;
4940 	}
4941 
4942 	page3p = (struct mode_format *)
4943 	    ((caddr_t)headerp + mode_header_length + bd_len);
4944 
4945 	if (page3p->mode_page.code != SD_MODE_SENSE_PAGE3_CODE) {
4946 		sd_ssc_set_info(ssc, SSC_FLAGS_INVALID_DATA, SD_LOG_COMMON,
4947 		    "sd_get_physical_geometry: mode sense pg3 code mismatch "
4948 		    "%d\n", page3p->mode_page.code);
4949 		status = EIO;
4950 		goto page3_exit;
4951 	}
4952 
4953 	/*
4954 	 * Use this physical geometry data only if BOTH MODE SENSE commands
4955 	 * complete successfully; otherwise, revert to the logical geometry.
4956 	 * So, we need to save everything in temporary variables.
4957 	 */
4958 	sector_size = BE_16(page3p->data_bytes_sect);
4959 
4960 	/*
4961 	 * 1243403: The NEC D38x7 drives do not support MODE SENSE sector size
4962 	 */
4963 	if (sector_size == 0) {
4964 		sector_size = un->un_sys_blocksize;
4965 	} else {
4966 		sector_size &= ~(un->un_sys_blocksize - 1);
4967 	}
4968 
4969 	nsect  = BE_16(page3p->sect_track);
4970 	intrlv = BE_16(page3p->interleave);
4971 
4972 	SD_INFO(SD_LOG_COMMON, un,
4973 	    "sd_get_physical_geometry: Format Parameters (page 3)\n");
4974 	SD_INFO(SD_LOG_COMMON, un,
4975 	    "   mode page: %d; nsect: %d; sector size: %d;\n",
4976 	    page3p->mode_page.code, nsect, sector_size);
4977 	SD_INFO(SD_LOG_COMMON, un,
4978 	    "   interleave: %d; track skew: %d; cylinder skew: %d;\n", intrlv,
4979 	    BE_16(page3p->track_skew),
4980 	    BE_16(page3p->cylinder_skew));
4981 
4982 	sd_ssc_assessment(ssc, SD_FMT_STANDARD);
4983 
4984 	/*
4985 	 * Retrieve MODE SENSE page 4 - Rigid Disk Drive Geometry Page
4986 	 */
4987 	p4bufp = kmem_zalloc(SD_MODE_SENSE_PAGE4_LENGTH, KM_SLEEP);
4988 	status = sd_send_scsi_MODE_SENSE(ssc, cdbsize, p4bufp,
4989 	    SD_MODE_SENSE_PAGE4_LENGTH, SD_MODE_SENSE_PAGE4_CODE, path_flag);
4990 	if (status != 0) {
4991 		SD_ERROR(SD_LOG_COMMON, un,
4992 		    "sd_get_physical_geometry: mode sense page 4 failed\n");
4993 		goto page4_exit;
4994 	}
4995 
4996 	/*
4997 	 * Determine size of Block Descriptors in order to locate the mode
4998 	 * page data.  ATAPI devices return 0, SCSI devices should return
4999 	 * MODE_BLK_DESC_LENGTH.
5000 	 */
5001 	headerp = (struct mode_header *)p4bufp;
5002 	if (un->un_f_cfg_is_atapi == TRUE) {
5003 		struct mode_header_grp2 *mhp =
5004 		    (struct mode_header_grp2 *)headerp;
5005 		bd_len = (mhp->bdesc_length_hi << 8) | mhp->bdesc_length_lo;
5006 	} else {
5007 		bd_len = ((struct mode_header *)headerp)->bdesc_length;
5008 	}
5009 
5010 	if (bd_len > MODE_BLK_DESC_LENGTH) {
5011 		sd_ssc_set_info(ssc, SSC_FLAGS_INVALID_DATA, SD_LOG_COMMON,
5012 		    "sd_get_physical_geometry: received unexpected bd_len of "
5013 		    "%d, page4\n", bd_len);
5014 		status = EIO;
5015 		goto page4_exit;
5016 	}
5017 
5018 	page4p = (struct mode_geometry *)
5019 	    ((caddr_t)headerp + mode_header_length + bd_len);
5020 
5021 	if (page4p->mode_page.code != SD_MODE_SENSE_PAGE4_CODE) {
5022 		sd_ssc_set_info(ssc, SSC_FLAGS_INVALID_DATA, SD_LOG_COMMON,
5023 		    "sd_get_physical_geometry: mode sense pg4 code mismatch "
5024 		    "%d\n", page4p->mode_page.code);
5025 		status = EIO;
5026 		goto page4_exit;
5027 	}
5028 
5029 	/*
5030 	 * Stash the data now, after we know that both commands completed.
5031 	 */
5032 
5033 
5034 	nhead = (int)page4p->heads;	/* uchar, so no conversion needed */
5035 	spc   = nhead * nsect;
5036 	ncyl  = (page4p->cyl_ub << 16) + (page4p->cyl_mb << 8) + page4p->cyl_lb;
5037 	rpm   = BE_16(page4p->rpm);
5038 
5039 	modesense_capacity = spc * ncyl;
5040 
5041 	SD_INFO(SD_LOG_COMMON, un,
5042 	    "sd_get_physical_geometry: Geometry Parameters (page 4)\n");
5043 	SD_INFO(SD_LOG_COMMON, un,
5044 	    "   cylinders: %d; heads: %d; rpm: %d;\n", ncyl, nhead, rpm);
5045 	SD_INFO(SD_LOG_COMMON, un,
5046 	    "   computed capacity(h*s*c): %d;\n", modesense_capacity);
5047 	SD_INFO(SD_LOG_COMMON, un, "   pgeom_p: %p; read cap: %d\n",
5048 	    (void *)pgeom_p, capacity);
5049 
5050 	/*
5051 	 * Compensate if the drive's geometry is not rectangular, i.e.,
5052 	 * the product of C * H * S returned by MODE SENSE >= that returned
5053 	 * by read capacity. This is an idiosyncrasy of the original x86
5054 	 * disk subsystem.
5055 	 */
5056 	if (modesense_capacity >= capacity) {
5057 		SD_INFO(SD_LOG_COMMON, un,
5058 		    "sd_get_physical_geometry: adjusting acyl; "
5059 		    "old: %d; new: %d\n", pgeom_p->g_acyl,
5060 		    (modesense_capacity - capacity + spc - 1) / spc);
5061 		if (sector_size != 0) {
5062 			/* 1243403: NEC D38x7 drives don't support sec size */
5063 			pgeom_p->g_secsize = (unsigned short)sector_size;
5064 		}
5065 		pgeom_p->g_nsect    = (unsigned short)nsect;
5066 		pgeom_p->g_nhead    = (unsigned short)nhead;
5067 		pgeom_p->g_capacity = capacity;
5068 		pgeom_p->g_acyl	    =
5069 		    (modesense_capacity - pgeom_p->g_capacity + spc - 1) / spc;
5070 		pgeom_p->g_ncyl	    = ncyl - pgeom_p->g_acyl;
5071 	}
5072 
5073 	pgeom_p->g_rpm    = (unsigned short)rpm;
5074 	pgeom_p->g_intrlv = (unsigned short)intrlv;
5075 	ret = 0;
5076 
5077 	SD_INFO(SD_LOG_COMMON, un,
5078 	    "sd_get_physical_geometry: mode sense geometry:\n");
5079 	SD_INFO(SD_LOG_COMMON, un,
5080 	    "   nsect: %d; sector size: %d; interlv: %d\n",
5081 	    nsect, sector_size, intrlv);
5082 	SD_INFO(SD_LOG_COMMON, un,
5083 	    "   nhead: %d; ncyl: %d; rpm: %d; capacity(ms): %d\n",
5084 	    nhead, ncyl, rpm, modesense_capacity);
5085 	SD_INFO(SD_LOG_COMMON, un,
5086 	    "sd_get_physical_geometry: (cached)\n");
5087 	SD_INFO(SD_LOG_COMMON, un,
5088 	    "   ncyl: %ld; acyl: %d; nhead: %d; nsect: %d\n",
5089 	    pgeom_p->g_ncyl,  pgeom_p->g_acyl,
5090 	    pgeom_p->g_nhead, pgeom_p->g_nsect);
5091 	SD_INFO(SD_LOG_COMMON, un,
5092 	    "   lbasize: %d; capacity: %ld; intrlv: %d; rpm: %d\n",
5093 	    pgeom_p->g_secsize, pgeom_p->g_capacity,
5094 	    pgeom_p->g_intrlv, pgeom_p->g_rpm);
5095 	sd_ssc_assessment(ssc, SD_FMT_STANDARD);
5096 
5097 page4_exit:
5098 	kmem_free(p4bufp, SD_MODE_SENSE_PAGE4_LENGTH);
5099 
5100 page3_exit:
5101 	kmem_free(p3bufp, SD_MODE_SENSE_PAGE3_LENGTH);
5102 
5103 	if (status != 0) {
5104 		if (status == EIO) {
5105 			/*
5106 			 * Some disks do not support mode sense(6), we
5107 			 * should ignore this kind of error(sense key is
5108 			 * 0x5 - illegal request).
5109 			 */
5110 			uint8_t *sensep;
5111 			int senlen;
5112 
5113 			sensep = (uint8_t *)ssc->ssc_uscsi_cmd->uscsi_rqbuf;
5114 			senlen = (int)(ssc->ssc_uscsi_cmd->uscsi_rqlen -
5115 			    ssc->ssc_uscsi_cmd->uscsi_rqresid);
5116 
5117 			if (senlen > 0 &&
5118 			    scsi_sense_key(sensep) == KEY_ILLEGAL_REQUEST) {
5119 				sd_ssc_assessment(ssc,
5120 				    SD_FMT_IGNORE_COMPROMISE);
5121 			} else {
5122 				sd_ssc_assessment(ssc, SD_FMT_STATUS_CHECK);
5123 			}
5124 		} else {
5125 			sd_ssc_assessment(ssc, SD_FMT_IGNORE);
5126 		}
5127 	}
5128 	sd_ssc_fini(ssc);
5129 	return (ret);
5130 }
5131 
5132 /*
5133  *    Function: sd_get_virtual_geometry
5134  *
5135  * Description: Ask the controller to tell us about the target device.
5136  *
5137  *   Arguments: un - pointer to softstate
5138  *		capacity - disk capacity in #blocks
5139  *		lbasize - disk block size in bytes
5140  *
5141  *     Context: Kernel thread only
5142  */
5143 
5144 static int
5145 sd_get_virtual_geometry(struct sd_lun *un, cmlb_geom_t *lgeom_p,
5146     diskaddr_t capacity, int lbasize)
5147 {
5148 	uint_t	geombuf;
5149 	int	spc;
5150 
5151 	ASSERT(un != NULL);
5152 
5153 	/* Set sector size, and total number of sectors */
5154 	(void) scsi_ifsetcap(SD_ADDRESS(un), "sector-size",   lbasize,  1);
5155 	(void) scsi_ifsetcap(SD_ADDRESS(un), "total-sectors", capacity, 1);
5156 
5157 	/* Let the HBA tell us its geometry */
5158 	geombuf = (uint_t)scsi_ifgetcap(SD_ADDRESS(un), "geometry", 1);
5159 
5160 	/* A value of -1 indicates an undefined "geometry" property */
5161 	if (geombuf == (-1)) {
5162 		return (EINVAL);
5163 	}
5164 
5165 	/* Initialize the logical geometry cache. */
5166 	lgeom_p->g_nhead   = (geombuf >> 16) & 0xffff;
5167 	lgeom_p->g_nsect   = geombuf & 0xffff;
5168 	lgeom_p->g_secsize = un->un_sys_blocksize;
5169 
5170 	spc = lgeom_p->g_nhead * lgeom_p->g_nsect;
5171 
5172 	/*
5173 	 * Note: The driver originally converted the capacity value from
5174 	 * target blocks to system blocks. However, the capacity value passed
5175 	 * to this routine is already in terms of system blocks (this scaling
5176 	 * is done when the READ CAPACITY command is issued and processed).
5177 	 * This 'error' may have gone undetected because the usage of g_ncyl
5178 	 * (which is based upon g_capacity) is very limited within the driver
5179 	 */
5180 	lgeom_p->g_capacity = capacity;
5181 
5182 	/*
5183 	 * Set ncyl to zero if the hba returned a zero nhead or nsect value. The
5184 	 * hba may return zero values if the device has been removed.
5185 	 */
5186 	if (spc == 0) {
5187 		lgeom_p->g_ncyl = 0;
5188 	} else {
5189 		lgeom_p->g_ncyl = lgeom_p->g_capacity / spc;
5190 	}
5191 	lgeom_p->g_acyl = 0;
5192 
5193 	SD_INFO(SD_LOG_COMMON, un, "sd_get_virtual_geometry: (cached)\n");
5194 	return (0);
5195 
5196 }
5197 /*
5198  *    Function: sd_update_block_info
5199  *
5200  * Description: Calculate a byte count to sector count bitshift value
5201  *		from sector size.
5202  *
5203  *   Arguments: un: unit struct.
5204  *		lbasize: new target sector size
5205  *		capacity: new target capacity, ie. block count
5206  *
5207  *     Context: Kernel thread context
5208  */
5209 
5210 static void
5211 sd_update_block_info(struct sd_lun *un, uint32_t lbasize, uint64_t capacity)
5212 {
5213 	if (lbasize != 0) {
5214 		un->un_tgt_blocksize = lbasize;
5215 		un->un_f_tgt_blocksize_is_valid = TRUE;
5216 		if (!un->un_f_has_removable_media) {
5217 			un->un_sys_blocksize = lbasize;
5218 		}
5219 	}
5220 
5221 	if (capacity != 0) {
5222 		un->un_blockcount		= capacity;
5223 		un->un_f_blockcount_is_valid	= TRUE;
5224 	}
5225 }
5226 
5227 
5228 /*
5229  *    Function: sd_register_devid
5230  *
5231  * Description: This routine will obtain the device id information from the
5232  *		target, obtain the serial number, and register the device
5233  *		id with the ddi framework.
5234  *
5235  *   Arguments: devi - the system's dev_info_t for the device.
5236  *		un - driver soft state (unit) structure
5237  *		reservation_flag - indicates if a reservation conflict
5238  *		occurred during attach
5239  *
5240  *     Context: Kernel Thread
5241  */
5242 static void
5243 sd_register_devid(sd_ssc_t *ssc, dev_info_t *devi, int reservation_flag)
5244 {
5245 	int		rval		= 0;
5246 	uchar_t		*inq80		= NULL;
5247 	size_t		inq80_len	= MAX_INQUIRY_SIZE;
5248 	size_t		inq80_resid	= 0;
5249 	uchar_t		*inq83		= NULL;
5250 	size_t		inq83_len	= MAX_INQUIRY_SIZE;
5251 	size_t		inq83_resid	= 0;
5252 	int		dlen, len;
5253 	char		*sn;
5254 	struct sd_lun	*un;
5255 
5256 	ASSERT(ssc != NULL);
5257 	un = ssc->ssc_un;
5258 	ASSERT(un != NULL);
5259 	ASSERT(mutex_owned(SD_MUTEX(un)));
5260 	ASSERT((SD_DEVINFO(un)) == devi);
5261 
5262 
5263 	/*
5264 	 * We check the availability of the World Wide Name (0x83) and Unit
5265 	 * Serial Number (0x80) pages in sd_check_vpd_page_support(), and using
5266 	 * un_vpd_page_mask from them, we decide which way to get the WWN.  If
5267 	 * 0x83 is available, that is the best choice.  Our next choice is
5268 	 * 0x80.  If neither are available, we munge the devid from the device
5269 	 * vid/pid/serial # for Sun qualified disks, or use the ddi framework
5270 	 * to fabricate a devid for non-Sun qualified disks.
5271 	 */
5272 	if (sd_check_vpd_page_support(ssc) == 0) {
5273 		/* collect page 80 data if available */
5274 		if (un->un_vpd_page_mask & SD_VPD_UNIT_SERIAL_PG) {
5275 
5276 			mutex_exit(SD_MUTEX(un));
5277 			inq80 = kmem_zalloc(inq80_len, KM_SLEEP);
5278 
5279 			rval = sd_send_scsi_INQUIRY(ssc, inq80, inq80_len,
5280 			    0x01, 0x80, &inq80_resid);
5281 
5282 			if (rval != 0) {
5283 				sd_ssc_assessment(ssc, SD_FMT_IGNORE);
5284 				kmem_free(inq80, inq80_len);
5285 				inq80 = NULL;
5286 				inq80_len = 0;
5287 			} else if (ddi_prop_exists(
5288 			    DDI_DEV_T_NONE, SD_DEVINFO(un),
5289 			    DDI_PROP_NOTPROM | DDI_PROP_DONTPASS,
5290 			    INQUIRY_SERIAL_NO) == 0) {
5291 				/*
5292 				 * If we don't already have a serial number
5293 				 * property, do quick verify of data returned
5294 				 * and define property.
5295 				 */
5296 				dlen = inq80_len - inq80_resid;
5297 				len = (size_t)inq80[3];
5298 				if ((dlen >= 4) && ((len + 4) <= dlen)) {
5299 					/*
5300 					 * Ensure sn termination, skip leading
5301 					 * blanks, and create property
5302 					 * 'inquiry-serial-no'.
5303 					 */
5304 					sn = (char *)&inq80[4];
5305 					sn[len] = 0;
5306 					while (*sn && (*sn == ' '))
5307 						sn++;
5308 					if (*sn) {
5309 						(void) ddi_prop_update_string(
5310 						    DDI_DEV_T_NONE,
5311 						    SD_DEVINFO(un),
5312 						    INQUIRY_SERIAL_NO, sn);
5313 					}
5314 				}
5315 			}
5316 			mutex_enter(SD_MUTEX(un));
5317 		}
5318 
5319 		/* collect page 83 data if available */
5320 		if (un->un_vpd_page_mask & SD_VPD_DEVID_WWN_PG) {
5321 			mutex_exit(SD_MUTEX(un));
5322 			inq83 = kmem_zalloc(inq83_len, KM_SLEEP);
5323 
5324 			rval = sd_send_scsi_INQUIRY(ssc, inq83, inq83_len,
5325 			    0x01, 0x83, &inq83_resid);
5326 
5327 			if (rval != 0) {
5328 				sd_ssc_assessment(ssc, SD_FMT_IGNORE);
5329 				kmem_free(inq83, inq83_len);
5330 				inq83 = NULL;
5331 				inq83_len = 0;
5332 			}
5333 			mutex_enter(SD_MUTEX(un));
5334 		}
5335 	}
5336 
5337 	/*
5338 	 * If transport has already registered a devid for this target
5339 	 * then that takes precedence over the driver's determination
5340 	 * of the devid.
5341 	 *
5342 	 * NOTE: The reason this check is done here instead of at the beginning
5343 	 * of the function is to allow the code above to create the
5344 	 * 'inquiry-serial-no' property.
5345 	 */
5346 	if (ddi_devid_get(SD_DEVINFO(un), &un->un_devid) == DDI_SUCCESS) {
5347 		ASSERT(un->un_devid);
5348 		un->un_f_devid_transport_defined = TRUE;
5349 		goto cleanup; /* use devid registered by the transport */
5350 	}
5351 
5352 	/*
5353 	 * This is the case of antiquated Sun disk drives that have the
5354 	 * FAB_DEVID property set in the disk_table.  These drives
5355 	 * manage the devid's by storing them in last 2 available sectors
5356 	 * on the drive and have them fabricated by the ddi layer by calling
5357 	 * ddi_devid_init and passing the DEVID_FAB flag.
5358 	 */
5359 	if (un->un_f_opt_fab_devid == TRUE) {
5360 		/*
5361 		 * Depending on EINVAL isn't reliable, since a reserved disk
5362 		 * may result in invalid geometry, so check to make sure a
5363 		 * reservation conflict did not occur during attach.
5364 		 */
5365 		if ((sd_get_devid(ssc) == EINVAL) &&
5366 		    (reservation_flag != SD_TARGET_IS_RESERVED)) {
5367 			/*
5368 			 * The devid is invalid AND there is no reservation
5369 			 * conflict.  Fabricate a new devid.
5370 			 */
5371 			(void) sd_create_devid(ssc);
5372 		}
5373 
5374 		/* Register the devid if it exists */
5375 		if (un->un_devid != NULL) {
5376 			(void) ddi_devid_register(SD_DEVINFO(un),
5377 			    un->un_devid);
5378 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
5379 			    "sd_register_devid: Devid Fabricated\n");
5380 		}
5381 		goto cleanup;
5382 	}
5383 
5384 	/* encode best devid possible based on data available */
5385 	if (ddi_devid_scsi_encode(DEVID_SCSI_ENCODE_VERSION_LATEST,
5386 	    (char *)ddi_driver_name(SD_DEVINFO(un)),
5387 	    (uchar_t *)SD_INQUIRY(un), sizeof (*SD_INQUIRY(un)),
5388 	    inq80, inq80_len - inq80_resid, inq83, inq83_len -
5389 	    inq83_resid, &un->un_devid) == DDI_SUCCESS) {
5390 
5391 		/* devid successfully encoded, register devid */
5392 		(void) ddi_devid_register(SD_DEVINFO(un), un->un_devid);
5393 
5394 	} else {
5395 		/*
5396 		 * Unable to encode a devid based on data available.
5397 		 * This is not a Sun qualified disk.  Older Sun disk
5398 		 * drives that have the SD_FAB_DEVID property
5399 		 * set in the disk_table and non Sun qualified
5400 		 * disks are treated in the same manner.  These
5401 		 * drives manage the devid's by storing them in
5402 		 * last 2 available sectors on the drive and
5403 		 * have them fabricated by the ddi layer by
5404 		 * calling ddi_devid_init and passing the
5405 		 * DEVID_FAB flag.
5406 		 * Create a fabricate devid only if there's no
5407 		 * fabricate devid existed.
5408 		 */
5409 		if (sd_get_devid(ssc) == EINVAL) {
5410 			(void) sd_create_devid(ssc);
5411 		}
5412 		un->un_f_opt_fab_devid = TRUE;
5413 
5414 		/* Register the devid if it exists */
5415 		if (un->un_devid != NULL) {
5416 			(void) ddi_devid_register(SD_DEVINFO(un),
5417 			    un->un_devid);
5418 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
5419 			    "sd_register_devid: devid fabricated using "
5420 			    "ddi framework\n");
5421 		}
5422 	}
5423 
5424 cleanup:
5425 	/* clean up resources */
5426 	if (inq80 != NULL) {
5427 		kmem_free(inq80, inq80_len);
5428 	}
5429 	if (inq83 != NULL) {
5430 		kmem_free(inq83, inq83_len);
5431 	}
5432 }
5433 
5434 
5435 
5436 /*
5437  *    Function: sd_get_devid
5438  *
5439  * Description: This routine will return 0 if a valid device id has been
5440  *		obtained from the target and stored in the soft state. If a
5441  *		valid device id has not been previously read and stored, a
5442  *		read attempt will be made.
5443  *
5444  *   Arguments: un - driver soft state (unit) structure
5445  *
5446  * Return Code: 0 if we successfully get the device id
5447  *
5448  *     Context: Kernel Thread
5449  */
5450 
5451 static int
5452 sd_get_devid(sd_ssc_t *ssc)
5453 {
5454 	struct dk_devid		*dkdevid;
5455 	ddi_devid_t		tmpid;
5456 	uint_t			*ip;
5457 	size_t			sz;
5458 	diskaddr_t		blk;
5459 	int			status;
5460 	int			chksum;
5461 	int			i;
5462 	size_t			buffer_size;
5463 	struct sd_lun		*un;
5464 
5465 	ASSERT(ssc != NULL);
5466 	un = ssc->ssc_un;
5467 	ASSERT(un != NULL);
5468 	ASSERT(mutex_owned(SD_MUTEX(un)));
5469 
5470 	SD_TRACE(SD_LOG_ATTACH_DETACH, un, "sd_get_devid: entry: un: 0x%p\n",
5471 	    un);
5472 
5473 	if (un->un_devid != NULL) {
5474 		return (0);
5475 	}
5476 
5477 	mutex_exit(SD_MUTEX(un));
5478 	if (cmlb_get_devid_block(un->un_cmlbhandle, &blk,
5479 	    (void *)SD_PATH_DIRECT) != 0) {
5480 		mutex_enter(SD_MUTEX(un));
5481 		return (EINVAL);
5482 	}
5483 
5484 	/*
5485 	 * Read and verify device id, stored in the reserved cylinders at the
5486 	 * end of the disk. Backup label is on the odd sectors of the last
5487 	 * track of the last cylinder. Device id will be on track of the next
5488 	 * to last cylinder.
5489 	 */
5490 	mutex_enter(SD_MUTEX(un));
5491 	buffer_size = SD_REQBYTES2TGTBYTES(un, sizeof (struct dk_devid));
5492 	mutex_exit(SD_MUTEX(un));
5493 	dkdevid = kmem_alloc(buffer_size, KM_SLEEP);
5494 	status = sd_send_scsi_READ(ssc, dkdevid, buffer_size, blk,
5495 	    SD_PATH_DIRECT);
5496 
5497 	if (status != 0) {
5498 		sd_ssc_assessment(ssc, SD_FMT_IGNORE);
5499 		goto error;
5500 	}
5501 
5502 	/* Validate the revision */
5503 	if ((dkdevid->dkd_rev_hi != DK_DEVID_REV_MSB) ||
5504 	    (dkdevid->dkd_rev_lo != DK_DEVID_REV_LSB)) {
5505 		status = EINVAL;
5506 		goto error;
5507 	}
5508 
5509 	/* Calculate the checksum */
5510 	chksum = 0;
5511 	ip = (uint_t *)dkdevid;
5512 	for (i = 0; i < ((DEV_BSIZE - sizeof (int)) / sizeof (int));
5513 	    i++) {
5514 		chksum ^= ip[i];
5515 	}
5516 
5517 	/* Compare the checksums */
5518 	if (DKD_GETCHKSUM(dkdevid) != chksum) {
5519 		status = EINVAL;
5520 		goto error;
5521 	}
5522 
5523 	/* Validate the device id */
5524 	if (ddi_devid_valid((ddi_devid_t)&dkdevid->dkd_devid) != DDI_SUCCESS) {
5525 		status = EINVAL;
5526 		goto error;
5527 	}
5528 
5529 	/*
5530 	 * Store the device id in the driver soft state
5531 	 */
5532 	sz = ddi_devid_sizeof((ddi_devid_t)&dkdevid->dkd_devid);
5533 	tmpid = kmem_alloc(sz, KM_SLEEP);
5534 
5535 	mutex_enter(SD_MUTEX(un));
5536 
5537 	un->un_devid = tmpid;
5538 	bcopy(&dkdevid->dkd_devid, un->un_devid, sz);
5539 
5540 	kmem_free(dkdevid, buffer_size);
5541 
5542 	SD_TRACE(SD_LOG_ATTACH_DETACH, un, "sd_get_devid: exit: un:0x%p\n", un);
5543 
5544 	return (status);
5545 error:
5546 	mutex_enter(SD_MUTEX(un));
5547 	kmem_free(dkdevid, buffer_size);
5548 	return (status);
5549 }
5550 
5551 
5552 /*
5553  *    Function: sd_create_devid
5554  *
5555  * Description: This routine will fabricate the device id and write it
5556  *		to the disk.
5557  *
5558  *   Arguments: un - driver soft state (unit) structure
5559  *
5560  * Return Code: value of the fabricated device id
5561  *
5562  *     Context: Kernel Thread
5563  */
5564 
5565 static ddi_devid_t
5566 sd_create_devid(sd_ssc_t *ssc)
5567 {
5568 	struct sd_lun	*un;
5569 
5570 	ASSERT(ssc != NULL);
5571 	un = ssc->ssc_un;
5572 	ASSERT(un != NULL);
5573 
5574 	/* Fabricate the devid */
5575 	if (ddi_devid_init(SD_DEVINFO(un), DEVID_FAB, 0, NULL, &un->un_devid)
5576 	    == DDI_FAILURE) {
5577 		return (NULL);
5578 	}
5579 
5580 	/* Write the devid to disk */
5581 	if (sd_write_deviceid(ssc) != 0) {
5582 		ddi_devid_free(un->un_devid);
5583 		un->un_devid = NULL;
5584 	}
5585 
5586 	return (un->un_devid);
5587 }
5588 
5589 
5590 /*
5591  *    Function: sd_write_deviceid
5592  *
5593  * Description: This routine will write the device id to the disk
5594  *		reserved sector.
5595  *
5596  *   Arguments: un - driver soft state (unit) structure
5597  *
5598  * Return Code: EINVAL
5599  *		value returned by sd_send_scsi_cmd
5600  *
5601  *     Context: Kernel Thread
5602  */
5603 
5604 static int
5605 sd_write_deviceid(sd_ssc_t *ssc)
5606 {
5607 	struct dk_devid		*dkdevid;
5608 	uchar_t			*buf;
5609 	diskaddr_t		blk;
5610 	uint_t			*ip, chksum;
5611 	int			status;
5612 	int			i;
5613 	struct sd_lun		*un;
5614 
5615 	ASSERT(ssc != NULL);
5616 	un = ssc->ssc_un;
5617 	ASSERT(un != NULL);
5618 	ASSERT(mutex_owned(SD_MUTEX(un)));
5619 
5620 	mutex_exit(SD_MUTEX(un));
5621 	if (cmlb_get_devid_block(un->un_cmlbhandle, &blk,
5622 	    (void *)SD_PATH_DIRECT) != 0) {
5623 		mutex_enter(SD_MUTEX(un));
5624 		return (-1);
5625 	}
5626 
5627 
5628 	/* Allocate the buffer */
5629 	buf = kmem_zalloc(un->un_sys_blocksize, KM_SLEEP);
5630 	dkdevid = (struct dk_devid *)buf;
5631 
5632 	/* Fill in the revision */
5633 	dkdevid->dkd_rev_hi = DK_DEVID_REV_MSB;
5634 	dkdevid->dkd_rev_lo = DK_DEVID_REV_LSB;
5635 
5636 	/* Copy in the device id */
5637 	mutex_enter(SD_MUTEX(un));
5638 	bcopy(un->un_devid, &dkdevid->dkd_devid,
5639 	    ddi_devid_sizeof(un->un_devid));
5640 	mutex_exit(SD_MUTEX(un));
5641 
5642 	/* Calculate the checksum */
5643 	chksum = 0;
5644 	ip = (uint_t *)dkdevid;
5645 	for (i = 0; i < ((DEV_BSIZE - sizeof (int)) / sizeof (int));
5646 	    i++) {
5647 		chksum ^= ip[i];
5648 	}
5649 
5650 	/* Fill-in checksum */
5651 	DKD_FORMCHKSUM(chksum, dkdevid);
5652 
5653 	/* Write the reserved sector */
5654 	status = sd_send_scsi_WRITE(ssc, buf, un->un_sys_blocksize, blk,
5655 	    SD_PATH_DIRECT);
5656 	if (status != 0)
5657 		sd_ssc_assessment(ssc, SD_FMT_IGNORE);
5658 
5659 	kmem_free(buf, un->un_sys_blocksize);
5660 
5661 	mutex_enter(SD_MUTEX(un));
5662 	return (status);
5663 }
5664 
5665 
5666 /*
5667  *    Function: sd_check_vpd_page_support
5668  *
5669  * Description: This routine sends an inquiry command with the EVPD bit set and
5670  *		a page code of 0x00 to the device. It is used to determine which
5671  *		vital product pages are available to find the devid. We are
5672  *		looking for pages 0x83 0x80 or 0xB1.  If we return a negative 1,
5673  *		the device does not support that command.
5674  *
5675  *   Arguments: un  - driver soft state (unit) structure
5676  *
5677  * Return Code: 0 - success
5678  *		1 - check condition
5679  *
5680  *     Context: This routine can sleep.
5681  */
5682 
5683 static int
5684 sd_check_vpd_page_support(sd_ssc_t *ssc)
5685 {
5686 	uchar_t	*page_list	= NULL;
5687 	uchar_t	page_length	= 0xff;	/* Use max possible length */
5688 	uchar_t	evpd		= 0x01;	/* Set the EVPD bit */
5689 	uchar_t	page_code	= 0x00;	/* Supported VPD Pages */
5690 	int    	rval		= 0;
5691 	int	counter;
5692 	struct sd_lun		*un;
5693 
5694 	ASSERT(ssc != NULL);
5695 	un = ssc->ssc_un;
5696 	ASSERT(un != NULL);
5697 	ASSERT(mutex_owned(SD_MUTEX(un)));
5698 
5699 	mutex_exit(SD_MUTEX(un));
5700 
5701 	/*
5702 	 * We'll set the page length to the maximum to save figuring it out
5703 	 * with an additional call.
5704 	 */
5705 	page_list =  kmem_zalloc(page_length, KM_SLEEP);
5706 
5707 	rval = sd_send_scsi_INQUIRY(ssc, page_list, page_length, evpd,
5708 	    page_code, NULL);
5709 
5710 	if (rval != 0)
5711 		sd_ssc_assessment(ssc, SD_FMT_IGNORE);
5712 
5713 	mutex_enter(SD_MUTEX(un));
5714 
5715 	/*
5716 	 * Now we must validate that the device accepted the command, as some
5717 	 * drives do not support it.  If the drive does support it, we will
5718 	 * return 0, and the supported pages will be in un_vpd_page_mask.  If
5719 	 * not, we return -1.
5720 	 */
5721 	if ((rval == 0) && (page_list[VPD_MODE_PAGE] == 0x00)) {
5722 		/* Loop to find one of the 2 pages we need */
5723 		counter = 4;  /* Supported pages start at byte 4, with 0x00 */
5724 
5725 		/*
5726 		 * Pages are returned in ascending order, and 0x83 is what we
5727 		 * are hoping for.
5728 		 */
5729 		while ((page_list[counter] <= 0xB1) &&
5730 		    (counter <= (page_list[VPD_PAGE_LENGTH] +
5731 		    VPD_HEAD_OFFSET))) {
5732 			/*
5733 			 * Add 3 because page_list[3] is the number of
5734 			 * pages minus 3
5735 			 */
5736 
5737 			switch (page_list[counter]) {
5738 			case 0x00:
5739 				un->un_vpd_page_mask |= SD_VPD_SUPPORTED_PG;
5740 				break;
5741 			case 0x80:
5742 				un->un_vpd_page_mask |= SD_VPD_UNIT_SERIAL_PG;
5743 				break;
5744 			case 0x81:
5745 				un->un_vpd_page_mask |= SD_VPD_OPERATING_PG;
5746 				break;
5747 			case 0x82:
5748 				un->un_vpd_page_mask |= SD_VPD_ASCII_OP_PG;
5749 				break;
5750 			case 0x83:
5751 				un->un_vpd_page_mask |= SD_VPD_DEVID_WWN_PG;
5752 				break;
5753 			case 0x86:
5754 				un->un_vpd_page_mask |= SD_VPD_EXTENDED_DATA_PG;
5755 				break;
5756 			case 0xB1:
5757 				un->un_vpd_page_mask |= SD_VPD_DEV_CHARACTER_PG;
5758 				break;
5759 			}
5760 			counter++;
5761 		}
5762 
5763 	} else {
5764 		rval = -1;
5765 
5766 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
5767 		    "sd_check_vpd_page_support: This drive does not implement "
5768 		    "VPD pages.\n");
5769 	}
5770 
5771 	kmem_free(page_list, page_length);
5772 
5773 	return (rval);
5774 }
5775 
5776 
5777 /*
5778  *    Function: sd_setup_pm
5779  *
5780  * Description: Initialize Power Management on the device
5781  *
5782  *     Context: Kernel Thread
5783  */
5784 
5785 static void
5786 sd_setup_pm(sd_ssc_t *ssc, dev_info_t *devi)
5787 {
5788 	uint_t		log_page_size;
5789 	uchar_t		*log_page_data;
5790 	int		rval = 0;
5791 	struct sd_lun	*un;
5792 
5793 	ASSERT(ssc != NULL);
5794 	un = ssc->ssc_un;
5795 	ASSERT(un != NULL);
5796 
5797 	/*
5798 	 * Since we are called from attach, holding a mutex for
5799 	 * un is unnecessary. Because some of the routines called
5800 	 * from here require SD_MUTEX to not be held, assert this
5801 	 * right up front.
5802 	 */
5803 	ASSERT(!mutex_owned(SD_MUTEX(un)));
5804 	/*
5805 	 * Since the sd device does not have the 'reg' property,
5806 	 * cpr will not call its DDI_SUSPEND/DDI_RESUME entries.
5807 	 * The following code is to tell cpr that this device
5808 	 * DOES need to be suspended and resumed.
5809 	 */
5810 	(void) ddi_prop_update_string(DDI_DEV_T_NONE, devi,
5811 	    "pm-hardware-state", "needs-suspend-resume");
5812 
5813 	/*
5814 	 * This complies with the new power management framework
5815 	 * for certain desktop machines. Create the pm_components
5816 	 * property as a string array property.
5817 	 * If un_f_pm_supported is TRUE, that means the disk
5818 	 * attached HBA has set the "pm-capable" property and
5819 	 * the value of this property is bigger than 0.
5820 	 */
5821 	if (un->un_f_pm_supported) {
5822 		/*
5823 		 * not all devices have a motor, try it first.
5824 		 * some devices may return ILLEGAL REQUEST, some
5825 		 * will hang
5826 		 * The following START_STOP_UNIT is used to check if target
5827 		 * device has a motor.
5828 		 */
5829 		un->un_f_start_stop_supported = TRUE;
5830 
5831 		if (un->un_f_power_condition_supported) {
5832 			rval = sd_send_scsi_START_STOP_UNIT(ssc,
5833 			    SD_POWER_CONDITION, SD_TARGET_ACTIVE,
5834 			    SD_PATH_DIRECT);
5835 			if (rval != 0) {
5836 				un->un_f_power_condition_supported = FALSE;
5837 			}
5838 		}
5839 		if (!un->un_f_power_condition_supported) {
5840 			rval = sd_send_scsi_START_STOP_UNIT(ssc,
5841 			    SD_START_STOP, SD_TARGET_START, SD_PATH_DIRECT);
5842 		}
5843 		if (rval != 0) {
5844 			sd_ssc_assessment(ssc, SD_FMT_IGNORE);
5845 			un->un_f_start_stop_supported = FALSE;
5846 		}
5847 
5848 		/*
5849 		 * create pm properties anyways otherwise the parent can't
5850 		 * go to sleep
5851 		 */
5852 		un->un_f_pm_is_enabled = TRUE;
5853 		(void) sd_create_pm_components(devi, un);
5854 
5855 		/*
5856 		 * If it claims that log sense is supported, check it out.
5857 		 */
5858 		if (un->un_f_log_sense_supported) {
5859 			rval = sd_log_page_supported(ssc,
5860 			    START_STOP_CYCLE_PAGE);
5861 			if (rval == 1) {
5862 				/* Page found, use it. */
5863 				un->un_start_stop_cycle_page =
5864 				    START_STOP_CYCLE_PAGE;
5865 			} else {
5866 				/*
5867 				 * Page not found or log sense is not
5868 				 * supported.
5869 				 * Notice we do not check the old style
5870 				 * START_STOP_CYCLE_VU_PAGE because this
5871 				 * code path does not apply to old disks.
5872 				 */
5873 				un->un_f_log_sense_supported = FALSE;
5874 				un->un_f_pm_log_sense_smart = FALSE;
5875 			}
5876 		}
5877 
5878 		return;
5879 	}
5880 
5881 	/*
5882 	 * For the disk whose attached HBA has not set the "pm-capable"
5883 	 * property, check if it supports the power management.
5884 	 */
5885 	if (!un->un_f_log_sense_supported) {
5886 		un->un_power_level = SD_SPINDLE_ON;
5887 		un->un_f_pm_is_enabled = FALSE;
5888 		return;
5889 	}
5890 
5891 	rval = sd_log_page_supported(ssc, START_STOP_CYCLE_PAGE);
5892 
5893 #ifdef	SDDEBUG
5894 	if (sd_force_pm_supported) {
5895 		/* Force a successful result */
5896 		rval = 1;
5897 	}
5898 #endif
5899 
5900 	/*
5901 	 * If the start-stop cycle counter log page is not supported
5902 	 * or if the pm-capable property is set to be false (0),
5903 	 * then we should not create the pm_components property.
5904 	 */
5905 	if (rval == -1) {
5906 		/*
5907 		 * Error.
5908 		 * Reading log sense failed, most likely this is
5909 		 * an older drive that does not support log sense.
5910 		 * If this fails auto-pm is not supported.
5911 		 */
5912 		un->un_power_level = SD_SPINDLE_ON;
5913 		un->un_f_pm_is_enabled = FALSE;
5914 
5915 	} else if (rval == 0) {
5916 		/*
5917 		 * Page not found.
5918 		 * The start stop cycle counter is implemented as page
5919 		 * START_STOP_CYCLE_PAGE_VU_PAGE (0x31) in older disks. For
5920 		 * newer disks it is implemented as START_STOP_CYCLE_PAGE (0xE).
5921 		 */
5922 		if (sd_log_page_supported(ssc, START_STOP_CYCLE_VU_PAGE) == 1) {
5923 			/*
5924 			 * Page found, use this one.
5925 			 */
5926 			un->un_start_stop_cycle_page = START_STOP_CYCLE_VU_PAGE;
5927 			un->un_f_pm_is_enabled = TRUE;
5928 		} else {
5929 			/*
5930 			 * Error or page not found.
5931 			 * auto-pm is not supported for this device.
5932 			 */
5933 			un->un_power_level = SD_SPINDLE_ON;
5934 			un->un_f_pm_is_enabled = FALSE;
5935 		}
5936 	} else {
5937 		/*
5938 		 * Page found, use it.
5939 		 */
5940 		un->un_start_stop_cycle_page = START_STOP_CYCLE_PAGE;
5941 		un->un_f_pm_is_enabled = TRUE;
5942 	}
5943 
5944 
5945 	if (un->un_f_pm_is_enabled == TRUE) {
5946 		log_page_size = START_STOP_CYCLE_COUNTER_PAGE_SIZE;
5947 		log_page_data = kmem_zalloc(log_page_size, KM_SLEEP);
5948 
5949 		rval = sd_send_scsi_LOG_SENSE(ssc, log_page_data,
5950 		    log_page_size, un->un_start_stop_cycle_page,
5951 		    0x01, 0, SD_PATH_DIRECT);
5952 
5953 		if (rval != 0) {
5954 			sd_ssc_assessment(ssc, SD_FMT_IGNORE);
5955 		}
5956 
5957 #ifdef	SDDEBUG
5958 		if (sd_force_pm_supported) {
5959 			/* Force a successful result */
5960 			rval = 0;
5961 		}
5962 #endif
5963 
5964 		/*
5965 		 * If the Log sense for Page( Start/stop cycle counter page)
5966 		 * succeeds, then power management is supported and we can
5967 		 * enable auto-pm.
5968 		 */
5969 		if (rval == 0)  {
5970 			(void) sd_create_pm_components(devi, un);
5971 		} else {
5972 			un->un_power_level = SD_SPINDLE_ON;
5973 			un->un_f_pm_is_enabled = FALSE;
5974 		}
5975 
5976 		kmem_free(log_page_data, log_page_size);
5977 	}
5978 }
5979 
5980 
5981 /*
5982  *    Function: sd_create_pm_components
5983  *
5984  * Description: Initialize PM property.
5985  *
5986  *     Context: Kernel thread context
5987  */
5988 
5989 static void
5990 sd_create_pm_components(dev_info_t *devi, struct sd_lun *un)
5991 {
5992 	ASSERT(!mutex_owned(SD_MUTEX(un)));
5993 
5994 	if (un->un_f_power_condition_supported) {
5995 		if (ddi_prop_update_string_array(DDI_DEV_T_NONE, devi,
5996 		    "pm-components", sd_pwr_pc.pm_comp, 5)
5997 		    != DDI_PROP_SUCCESS) {
5998 			un->un_power_level = SD_SPINDLE_ACTIVE;
5999 			un->un_f_pm_is_enabled = FALSE;
6000 			return;
6001 		}
6002 	} else {
6003 		if (ddi_prop_update_string_array(DDI_DEV_T_NONE, devi,
6004 		    "pm-components", sd_pwr_ss.pm_comp, 3)
6005 		    != DDI_PROP_SUCCESS) {
6006 			un->un_power_level = SD_SPINDLE_ON;
6007 			un->un_f_pm_is_enabled = FALSE;
6008 			return;
6009 		}
6010 	}
6011 	/*
6012 	 * When components are initially created they are idle,
6013 	 * power up any non-removables.
6014 	 * Note: the return value of pm_raise_power can't be used
6015 	 * for determining if PM should be enabled for this device.
6016 	 * Even if you check the return values and remove this
6017 	 * property created above, the PM framework will not honor the
6018 	 * change after the first call to pm_raise_power. Hence,
6019 	 * removal of that property does not help if pm_raise_power
6020 	 * fails. In the case of removable media, the start/stop
6021 	 * will fail if the media is not present.
6022 	 */
6023 	if (un->un_f_attach_spinup && (pm_raise_power(SD_DEVINFO(un), 0,
6024 	    SD_PM_STATE_ACTIVE(un)) == DDI_SUCCESS)) {
6025 		mutex_enter(SD_MUTEX(un));
6026 		un->un_power_level = SD_PM_STATE_ACTIVE(un);
6027 		mutex_enter(&un->un_pm_mutex);
6028 		/* Set to on and not busy. */
6029 		un->un_pm_count = 0;
6030 	} else {
6031 		mutex_enter(SD_MUTEX(un));
6032 		un->un_power_level = SD_PM_STATE_STOPPED(un);
6033 		mutex_enter(&un->un_pm_mutex);
6034 		/* Set to off. */
6035 		un->un_pm_count = -1;
6036 	}
6037 	mutex_exit(&un->un_pm_mutex);
6038 	mutex_exit(SD_MUTEX(un));
6039 }
6040 
6041 
6042 /*
6043  *    Function: sd_ddi_suspend
6044  *
6045  * Description: Performs system power-down operations. This includes
6046  *		setting the drive state to indicate its suspended so
6047  *		that no new commands will be accepted. Also, wait for
6048  *		all commands that are in transport or queued to a timer
6049  *		for retry to complete. All timeout threads are cancelled.
6050  *
6051  * Return Code: DDI_FAILURE or DDI_SUCCESS
6052  *
6053  *     Context: Kernel thread context
6054  */
6055 
6056 static int
6057 sd_ddi_suspend(dev_info_t *devi)
6058 {
6059 	struct	sd_lun	*un;
6060 	clock_t		wait_cmds_complete;
6061 
6062 	un = ddi_get_soft_state(sd_state, ddi_get_instance(devi));
6063 	if (un == NULL) {
6064 		return (DDI_FAILURE);
6065 	}
6066 
6067 	SD_TRACE(SD_LOG_IO_PM, un, "sd_ddi_suspend: entry\n");
6068 
6069 	mutex_enter(SD_MUTEX(un));
6070 
6071 	/* Return success if the device is already suspended. */
6072 	if (un->un_state == SD_STATE_SUSPENDED) {
6073 		mutex_exit(SD_MUTEX(un));
6074 		SD_TRACE(SD_LOG_IO_PM, un, "sd_ddi_suspend: "
6075 		    "device already suspended, exiting\n");
6076 		return (DDI_SUCCESS);
6077 	}
6078 
6079 	/* Return failure if the device is being used by HA */
6080 	if (un->un_resvd_status &
6081 	    (SD_RESERVE | SD_WANT_RESERVE | SD_LOST_RESERVE)) {
6082 		mutex_exit(SD_MUTEX(un));
6083 		SD_TRACE(SD_LOG_IO_PM, un, "sd_ddi_suspend: "
6084 		    "device in use by HA, exiting\n");
6085 		return (DDI_FAILURE);
6086 	}
6087 
6088 	/*
6089 	 * Return failure if the device is in a resource wait
6090 	 * or power changing state.
6091 	 */
6092 	if ((un->un_state == SD_STATE_RWAIT) ||
6093 	    (un->un_state == SD_STATE_PM_CHANGING)) {
6094 		mutex_exit(SD_MUTEX(un));
6095 		SD_TRACE(SD_LOG_IO_PM, un, "sd_ddi_suspend: "
6096 		    "device in resource wait state, exiting\n");
6097 		return (DDI_FAILURE);
6098 	}
6099 
6100 
6101 	un->un_save_state = un->un_last_state;
6102 	New_state(un, SD_STATE_SUSPENDED);
6103 
6104 	/*
6105 	 * Wait for all commands that are in transport or queued to a timer
6106 	 * for retry to complete.
6107 	 *
6108 	 * While waiting, no new commands will be accepted or sent because of
6109 	 * the new state we set above.
6110 	 *
6111 	 * Wait till current operation has completed. If we are in the resource
6112 	 * wait state (with an intr outstanding) then we need to wait till the
6113 	 * intr completes and starts the next cmd. We want to wait for
6114 	 * SD_WAIT_CMDS_COMPLETE seconds before failing the DDI_SUSPEND.
6115 	 */
6116 	wait_cmds_complete = ddi_get_lbolt() +
6117 	    (sd_wait_cmds_complete * drv_usectohz(1000000));
6118 
6119 	while (un->un_ncmds_in_transport != 0) {
6120 		/*
6121 		 * Fail if commands do not finish in the specified time.
6122 		 */
6123 		if (cv_timedwait(&un->un_disk_busy_cv, SD_MUTEX(un),
6124 		    wait_cmds_complete) == -1) {
6125 			/*
6126 			 * Undo the state changes made above. Everything
6127 			 * must go back to it's original value.
6128 			 */
6129 			Restore_state(un);
6130 			un->un_last_state = un->un_save_state;
6131 			/* Wake up any threads that might be waiting. */
6132 			cv_broadcast(&un->un_suspend_cv);
6133 			mutex_exit(SD_MUTEX(un));
6134 			SD_ERROR(SD_LOG_IO_PM, un,
6135 			    "sd_ddi_suspend: failed due to outstanding cmds\n");
6136 			SD_TRACE(SD_LOG_IO_PM, un, "sd_ddi_suspend: exiting\n");
6137 			return (DDI_FAILURE);
6138 		}
6139 	}
6140 
6141 	/*
6142 	 * Cancel SCSI watch thread and timeouts, if any are active
6143 	 */
6144 
6145 	if (SD_OK_TO_SUSPEND_SCSI_WATCHER(un)) {
6146 		opaque_t temp_token = un->un_swr_token;
6147 		mutex_exit(SD_MUTEX(un));
6148 		scsi_watch_suspend(temp_token);
6149 		mutex_enter(SD_MUTEX(un));
6150 	}
6151 
6152 	if (un->un_reset_throttle_timeid != NULL) {
6153 		timeout_id_t temp_id = un->un_reset_throttle_timeid;
6154 		un->un_reset_throttle_timeid = NULL;
6155 		mutex_exit(SD_MUTEX(un));
6156 		(void) untimeout(temp_id);
6157 		mutex_enter(SD_MUTEX(un));
6158 	}
6159 
6160 	if (un->un_dcvb_timeid != NULL) {
6161 		timeout_id_t temp_id = un->un_dcvb_timeid;
6162 		un->un_dcvb_timeid = NULL;
6163 		mutex_exit(SD_MUTEX(un));
6164 		(void) untimeout(temp_id);
6165 		mutex_enter(SD_MUTEX(un));
6166 	}
6167 
6168 	mutex_enter(&un->un_pm_mutex);
6169 	if (un->un_pm_timeid != NULL) {
6170 		timeout_id_t temp_id = un->un_pm_timeid;
6171 		un->un_pm_timeid = NULL;
6172 		mutex_exit(&un->un_pm_mutex);
6173 		mutex_exit(SD_MUTEX(un));
6174 		(void) untimeout(temp_id);
6175 		mutex_enter(SD_MUTEX(un));
6176 	} else {
6177 		mutex_exit(&un->un_pm_mutex);
6178 	}
6179 
6180 	if (un->un_rmw_msg_timeid != NULL) {
6181 		timeout_id_t temp_id = un->un_rmw_msg_timeid;
6182 		un->un_rmw_msg_timeid = NULL;
6183 		mutex_exit(SD_MUTEX(un));
6184 		(void) untimeout(temp_id);
6185 		mutex_enter(SD_MUTEX(un));
6186 	}
6187 
6188 	if (un->un_retry_timeid != NULL) {
6189 		timeout_id_t temp_id = un->un_retry_timeid;
6190 		un->un_retry_timeid = NULL;
6191 		mutex_exit(SD_MUTEX(un));
6192 		(void) untimeout(temp_id);
6193 		mutex_enter(SD_MUTEX(un));
6194 
6195 		if (un->un_retry_bp != NULL) {
6196 			un->un_retry_bp->av_forw = un->un_waitq_headp;
6197 			un->un_waitq_headp = un->un_retry_bp;
6198 			if (un->un_waitq_tailp == NULL) {
6199 				un->un_waitq_tailp = un->un_retry_bp;
6200 			}
6201 			un->un_retry_bp = NULL;
6202 			un->un_retry_statp = NULL;
6203 		}
6204 	}
6205 
6206 	if (un->un_direct_priority_timeid != NULL) {
6207 		timeout_id_t temp_id = un->un_direct_priority_timeid;
6208 		un->un_direct_priority_timeid = NULL;
6209 		mutex_exit(SD_MUTEX(un));
6210 		(void) untimeout(temp_id);
6211 		mutex_enter(SD_MUTEX(un));
6212 	}
6213 
6214 	if (un->un_f_is_fibre == TRUE) {
6215 		/*
6216 		 * Remove callbacks for insert and remove events
6217 		 */
6218 		if (un->un_insert_event != NULL) {
6219 			mutex_exit(SD_MUTEX(un));
6220 			(void) ddi_remove_event_handler(un->un_insert_cb_id);
6221 			mutex_enter(SD_MUTEX(un));
6222 			un->un_insert_event = NULL;
6223 		}
6224 
6225 		if (un->un_remove_event != NULL) {
6226 			mutex_exit(SD_MUTEX(un));
6227 			(void) ddi_remove_event_handler(un->un_remove_cb_id);
6228 			mutex_enter(SD_MUTEX(un));
6229 			un->un_remove_event = NULL;
6230 		}
6231 	}
6232 
6233 	mutex_exit(SD_MUTEX(un));
6234 
6235 	SD_TRACE(SD_LOG_IO_PM, un, "sd_ddi_suspend: exit\n");
6236 
6237 	return (DDI_SUCCESS);
6238 }
6239 
6240 
6241 /*
6242  *    Function: sd_ddi_resume
6243  *
6244  * Description: Performs system power-up operations..
6245  *
6246  * Return Code: DDI_SUCCESS
6247  *		DDI_FAILURE
6248  *
6249  *     Context: Kernel thread context
6250  */
6251 
6252 static int
6253 sd_ddi_resume(dev_info_t *devi)
6254 {
6255 	struct	sd_lun	*un;
6256 
6257 	un = ddi_get_soft_state(sd_state, ddi_get_instance(devi));
6258 	if (un == NULL) {
6259 		return (DDI_FAILURE);
6260 	}
6261 
6262 	SD_TRACE(SD_LOG_IO_PM, un, "sd_ddi_resume: entry\n");
6263 
6264 	mutex_enter(SD_MUTEX(un));
6265 	Restore_state(un);
6266 
6267 	/*
6268 	 * Restore the state which was saved to give the
6269 	 * the right state in un_last_state
6270 	 */
6271 	un->un_last_state = un->un_save_state;
6272 	/*
6273 	 * Note: throttle comes back at full.
6274 	 * Also note: this MUST be done before calling pm_raise_power
6275 	 * otherwise the system can get hung in biowait. The scenario where
6276 	 * this'll happen is under cpr suspend. Writing of the system
6277 	 * state goes through sddump, which writes 0 to un_throttle. If
6278 	 * writing the system state then fails, example if the partition is
6279 	 * too small, then cpr attempts a resume. If throttle isn't restored
6280 	 * from the saved value until after calling pm_raise_power then
6281 	 * cmds sent in sdpower are not transported and sd_send_scsi_cmd hangs
6282 	 * in biowait.
6283 	 */
6284 	un->un_throttle = un->un_saved_throttle;
6285 
6286 	/*
6287 	 * The chance of failure is very rare as the only command done in power
6288 	 * entry point is START command when you transition from 0->1 or
6289 	 * unknown->1. Put it to SPINDLE ON state irrespective of the state at
6290 	 * which suspend was done. Ignore the return value as the resume should
6291 	 * not be failed. In the case of removable media the media need not be
6292 	 * inserted and hence there is a chance that raise power will fail with
6293 	 * media not present.
6294 	 */
6295 	if (un->un_f_attach_spinup) {
6296 		mutex_exit(SD_MUTEX(un));
6297 		(void) pm_raise_power(SD_DEVINFO(un), 0,
6298 		    SD_PM_STATE_ACTIVE(un));
6299 		mutex_enter(SD_MUTEX(un));
6300 	}
6301 
6302 	/*
6303 	 * Don't broadcast to the suspend cv and therefore possibly
6304 	 * start I/O until after power has been restored.
6305 	 */
6306 	cv_broadcast(&un->un_suspend_cv);
6307 	cv_broadcast(&un->un_state_cv);
6308 
6309 	/* restart thread */
6310 	if (SD_OK_TO_RESUME_SCSI_WATCHER(un)) {
6311 		scsi_watch_resume(un->un_swr_token);
6312 	}
6313 
6314 #if (defined(__fibre))
6315 	if (un->un_f_is_fibre == TRUE) {
6316 		/*
6317 		 * Add callbacks for insert and remove events
6318 		 */
6319 		if (strcmp(un->un_node_type, DDI_NT_BLOCK_CHAN)) {
6320 			sd_init_event_callbacks(un);
6321 		}
6322 	}
6323 #endif
6324 
6325 	/*
6326 	 * Transport any pending commands to the target.
6327 	 *
6328 	 * If this is a low-activity device commands in queue will have to wait
6329 	 * until new commands come in, which may take awhile. Also, we
6330 	 * specifically don't check un_ncmds_in_transport because we know that
6331 	 * there really are no commands in progress after the unit was
6332 	 * suspended and we could have reached the throttle level, been
6333 	 * suspended, and have no new commands coming in for awhile. Highly
6334 	 * unlikely, but so is the low-activity disk scenario.
6335 	 */
6336 	ddi_xbuf_dispatch(un->un_xbuf_attr);
6337 
6338 	sd_start_cmds(un, NULL);
6339 	mutex_exit(SD_MUTEX(un));
6340 
6341 	SD_TRACE(SD_LOG_IO_PM, un, "sd_ddi_resume: exit\n");
6342 
6343 	return (DDI_SUCCESS);
6344 }
6345 
6346 
6347 /*
6348  *    Function: sd_pm_state_change
6349  *
6350  * Description: Change the driver power state.
6351  * 		Someone else is required to actually change the driver
6352  * 		power level.
6353  *
6354  *   Arguments: un - driver soft state (unit) structure
6355  *              level - the power level that is changed to
6356  *              flag - to decide how to change the power state
6357  *
6358  * Return Code: DDI_SUCCESS
6359  *
6360  *     Context: Kernel thread context
6361  */
6362 static int
6363 sd_pm_state_change(struct sd_lun *un, int level, int flag)
6364 {
6365 	ASSERT(un != NULL);
6366 	SD_TRACE(SD_LOG_POWER, un, "sd_pm_state_change: entry\n");
6367 
6368 	ASSERT(!mutex_owned(SD_MUTEX(un)));
6369 	mutex_enter(SD_MUTEX(un));
6370 
6371 	if (flag == SD_PM_STATE_ROLLBACK || SD_PM_IS_IO_CAPABLE(un, level)) {
6372 		un->un_power_level = level;
6373 		ASSERT(!mutex_owned(&un->un_pm_mutex));
6374 		mutex_enter(&un->un_pm_mutex);
6375 		if (SD_DEVICE_IS_IN_LOW_POWER(un)) {
6376 			un->un_pm_count++;
6377 			ASSERT(un->un_pm_count == 0);
6378 		}
6379 		mutex_exit(&un->un_pm_mutex);
6380 	} else {
6381 		/*
6382 		 * Exit if power management is not enabled for this device,
6383 		 * or if the device is being used by HA.
6384 		 */
6385 		if ((un->un_f_pm_is_enabled == FALSE) || (un->un_resvd_status &
6386 		    (SD_RESERVE | SD_WANT_RESERVE | SD_LOST_RESERVE))) {
6387 			mutex_exit(SD_MUTEX(un));
6388 			SD_TRACE(SD_LOG_POWER, un,
6389 			    "sd_pm_state_change: exiting\n");
6390 			return (DDI_FAILURE);
6391 		}
6392 
6393 		SD_INFO(SD_LOG_POWER, un, "sd_pm_state_change: "
6394 		    "un_ncmds_in_driver=%ld\n", un->un_ncmds_in_driver);
6395 
6396 		/*
6397 		 * See if the device is not busy, ie.:
6398 		 *    - we have no commands in the driver for this device
6399 		 *    - not waiting for resources
6400 		 */
6401 		if ((un->un_ncmds_in_driver == 0) &&
6402 		    (un->un_state != SD_STATE_RWAIT)) {
6403 			/*
6404 			 * The device is not busy, so it is OK to go to low
6405 			 * power state. Indicate low power, but rely on someone
6406 			 * else to actually change it.
6407 			 */
6408 			mutex_enter(&un->un_pm_mutex);
6409 			un->un_pm_count = -1;
6410 			mutex_exit(&un->un_pm_mutex);
6411 			un->un_power_level = level;
6412 		}
6413 	}
6414 
6415 	mutex_exit(SD_MUTEX(un));
6416 
6417 	SD_TRACE(SD_LOG_POWER, un, "sd_pm_state_change: exit\n");
6418 
6419 	return (DDI_SUCCESS);
6420 }
6421 
6422 
6423 /*
6424  *    Function: sd_pm_idletimeout_handler
6425  *
6426  * Description: A timer routine that's active only while a device is busy.
6427  *		The purpose is to extend slightly the pm framework's busy
6428  *		view of the device to prevent busy/idle thrashing for
6429  *		back-to-back commands. Do this by comparing the current time
6430  *		to the time at which the last command completed and when the
6431  *		difference is greater than sd_pm_idletime, call
6432  *		pm_idle_component. In addition to indicating idle to the pm
6433  *		framework, update the chain type to again use the internal pm
6434  *		layers of the driver.
6435  *
6436  *   Arguments: arg - driver soft state (unit) structure
6437  *
6438  *     Context: Executes in a timeout(9F) thread context
6439  */
6440 
6441 static void
6442 sd_pm_idletimeout_handler(void *arg)
6443 {
6444 	struct sd_lun *un = arg;
6445 
6446 	time_t	now;
6447 
6448 	mutex_enter(&sd_detach_mutex);
6449 	if (un->un_detach_count != 0) {
6450 		/* Abort if the instance is detaching */
6451 		mutex_exit(&sd_detach_mutex);
6452 		return;
6453 	}
6454 	mutex_exit(&sd_detach_mutex);
6455 
6456 	now = ddi_get_time();
6457 	/*
6458 	 * Grab both mutexes, in the proper order, since we're accessing
6459 	 * both PM and softstate variables.
6460 	 */
6461 	mutex_enter(SD_MUTEX(un));
6462 	mutex_enter(&un->un_pm_mutex);
6463 	if (((now - un->un_pm_idle_time) > sd_pm_idletime) &&
6464 	    (un->un_ncmds_in_driver == 0) && (un->un_pm_count == 0)) {
6465 		/*
6466 		 * Update the chain types.
6467 		 * This takes affect on the next new command received.
6468 		 */
6469 		if (un->un_f_non_devbsize_supported) {
6470 			un->un_buf_chain_type = SD_CHAIN_INFO_RMMEDIA;
6471 		} else {
6472 			un->un_buf_chain_type = SD_CHAIN_INFO_DISK;
6473 		}
6474 		un->un_uscsi_chain_type = SD_CHAIN_INFO_USCSI_CMD;
6475 
6476 		SD_TRACE(SD_LOG_IO_PM, un,
6477 		    "sd_pm_idletimeout_handler: idling device\n");
6478 		(void) pm_idle_component(SD_DEVINFO(un), 0);
6479 		un->un_pm_idle_timeid = NULL;
6480 	} else {
6481 		un->un_pm_idle_timeid =
6482 		    timeout(sd_pm_idletimeout_handler, un,
6483 		    (drv_usectohz((clock_t)300000))); /* 300 ms. */
6484 	}
6485 	mutex_exit(&un->un_pm_mutex);
6486 	mutex_exit(SD_MUTEX(un));
6487 }
6488 
6489 
6490 /*
6491  *    Function: sd_pm_timeout_handler
6492  *
6493  * Description: Callback to tell framework we are idle.
6494  *
6495  *     Context: timeout(9f) thread context.
6496  */
6497 
6498 static void
6499 sd_pm_timeout_handler(void *arg)
6500 {
6501 	struct sd_lun *un = arg;
6502 
6503 	(void) pm_idle_component(SD_DEVINFO(un), 0);
6504 	mutex_enter(&un->un_pm_mutex);
6505 	un->un_pm_timeid = NULL;
6506 	mutex_exit(&un->un_pm_mutex);
6507 }
6508 
6509 
6510 /*
6511  *    Function: sdpower
6512  *
6513  * Description: PM entry point.
6514  *
6515  * Return Code: DDI_SUCCESS
6516  *		DDI_FAILURE
6517  *
6518  *     Context: Kernel thread context
6519  */
6520 
6521 static int
6522 sdpower(dev_info_t *devi, int component, int level)
6523 {
6524 	struct sd_lun	*un;
6525 	int		instance;
6526 	int		rval = DDI_SUCCESS;
6527 	uint_t		i, log_page_size, maxcycles, ncycles;
6528 	uchar_t		*log_page_data;
6529 	int		log_sense_page;
6530 	int		medium_present;
6531 	time_t		intvlp;
6532 	dev_t		dev;
6533 	struct pm_trans_data	sd_pm_tran_data;
6534 	uchar_t		save_state;
6535 	int		sval;
6536 	uchar_t		state_before_pm;
6537 	int		got_semaphore_here;
6538 	sd_ssc_t	*ssc;
6539 	int	last_power_level;
6540 
6541 	instance = ddi_get_instance(devi);
6542 
6543 	if (((un = ddi_get_soft_state(sd_state, instance)) == NULL) ||
6544 	    !SD_PM_IS_LEVEL_VALID(un, level) || component != 0) {
6545 		return (DDI_FAILURE);
6546 	}
6547 
6548 	dev = sd_make_device(SD_DEVINFO(un));
6549 	ssc = sd_ssc_init(un);
6550 
6551 	SD_TRACE(SD_LOG_IO_PM, un, "sdpower: entry, level = %d\n", level);
6552 
6553 	/*
6554 	 * Must synchronize power down with close.
6555 	 * Attempt to decrement/acquire the open/close semaphore,
6556 	 * but do NOT wait on it. If it's not greater than zero,
6557 	 * ie. it can't be decremented without waiting, then
6558 	 * someone else, either open or close, already has it
6559 	 * and the try returns 0. Use that knowledge here to determine
6560 	 * if it's OK to change the device power level.
6561 	 * Also, only increment it on exit if it was decremented, ie. gotten,
6562 	 * here.
6563 	 */
6564 	got_semaphore_here = sema_tryp(&un->un_semoclose);
6565 
6566 	mutex_enter(SD_MUTEX(un));
6567 
6568 	SD_INFO(SD_LOG_POWER, un, "sdpower: un_ncmds_in_driver = %ld\n",
6569 	    un->un_ncmds_in_driver);
6570 
6571 	/*
6572 	 * If un_ncmds_in_driver is non-zero it indicates commands are
6573 	 * already being processed in the driver, or if the semaphore was
6574 	 * not gotten here it indicates an open or close is being processed.
6575 	 * At the same time somebody is requesting to go to a lower power
6576 	 * that can't perform I/O, which can't happen, therefore we need to
6577 	 * return failure.
6578 	 */
6579 	if ((!SD_PM_IS_IO_CAPABLE(un, level)) &&
6580 	    ((un->un_ncmds_in_driver != 0) || (got_semaphore_here == 0))) {
6581 		mutex_exit(SD_MUTEX(un));
6582 
6583 		if (got_semaphore_here != 0) {
6584 			sema_v(&un->un_semoclose);
6585 		}
6586 		SD_TRACE(SD_LOG_IO_PM, un,
6587 		    "sdpower: exit, device has queued cmds.\n");
6588 
6589 		goto sdpower_failed;
6590 	}
6591 
6592 	/*
6593 	 * if it is OFFLINE that means the disk is completely dead
6594 	 * in our case we have to put the disk in on or off by sending commands
6595 	 * Of course that will fail anyway so return back here.
6596 	 *
6597 	 * Power changes to a device that's OFFLINE or SUSPENDED
6598 	 * are not allowed.
6599 	 */
6600 	if ((un->un_state == SD_STATE_OFFLINE) ||
6601 	    (un->un_state == SD_STATE_SUSPENDED)) {
6602 		mutex_exit(SD_MUTEX(un));
6603 
6604 		if (got_semaphore_here != 0) {
6605 			sema_v(&un->un_semoclose);
6606 		}
6607 		SD_TRACE(SD_LOG_IO_PM, un,
6608 		    "sdpower: exit, device is off-line.\n");
6609 
6610 		goto sdpower_failed;
6611 	}
6612 
6613 	/*
6614 	 * Change the device's state to indicate it's power level
6615 	 * is being changed. Do this to prevent a power off in the
6616 	 * middle of commands, which is especially bad on devices
6617 	 * that are really powered off instead of just spun down.
6618 	 */
6619 	state_before_pm = un->un_state;
6620 	un->un_state = SD_STATE_PM_CHANGING;
6621 
6622 	mutex_exit(SD_MUTEX(un));
6623 
6624 	/*
6625 	 * If log sense command is not supported, bypass the
6626 	 * following checking, otherwise, check the log sense
6627 	 * information for this device.
6628 	 */
6629 	if (SD_PM_STOP_MOTOR_NEEDED(un, level) &&
6630 	    un->un_f_log_sense_supported) {
6631 		/*
6632 		 * Get the log sense information to understand whether the
6633 		 * the powercycle counts have gone beyond the threshhold.
6634 		 */
6635 		log_page_size = START_STOP_CYCLE_COUNTER_PAGE_SIZE;
6636 		log_page_data = kmem_zalloc(log_page_size, KM_SLEEP);
6637 
6638 		mutex_enter(SD_MUTEX(un));
6639 		log_sense_page = un->un_start_stop_cycle_page;
6640 		mutex_exit(SD_MUTEX(un));
6641 
6642 		rval = sd_send_scsi_LOG_SENSE(ssc, log_page_data,
6643 		    log_page_size, log_sense_page, 0x01, 0, SD_PATH_DIRECT);
6644 
6645 		if (rval != 0) {
6646 			if (rval == EIO)
6647 				sd_ssc_assessment(ssc, SD_FMT_STATUS_CHECK);
6648 			else
6649 				sd_ssc_assessment(ssc, SD_FMT_IGNORE);
6650 		}
6651 
6652 #ifdef	SDDEBUG
6653 		if (sd_force_pm_supported) {
6654 			/* Force a successful result */
6655 			rval = 0;
6656 		}
6657 #endif
6658 		if (rval != 0) {
6659 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
6660 			    "Log Sense Failed\n");
6661 
6662 			kmem_free(log_page_data, log_page_size);
6663 			/* Cannot support power management on those drives */
6664 
6665 			if (got_semaphore_here != 0) {
6666 				sema_v(&un->un_semoclose);
6667 			}
6668 			/*
6669 			 * On exit put the state back to it's original value
6670 			 * and broadcast to anyone waiting for the power
6671 			 * change completion.
6672 			 */
6673 			mutex_enter(SD_MUTEX(un));
6674 			un->un_state = state_before_pm;
6675 			cv_broadcast(&un->un_suspend_cv);
6676 			mutex_exit(SD_MUTEX(un));
6677 			SD_TRACE(SD_LOG_IO_PM, un,
6678 			    "sdpower: exit, Log Sense Failed.\n");
6679 
6680 			goto sdpower_failed;
6681 		}
6682 
6683 		/*
6684 		 * From the page data - Convert the essential information to
6685 		 * pm_trans_data
6686 		 */
6687 		maxcycles =
6688 		    (log_page_data[0x1c] << 24) | (log_page_data[0x1d] << 16) |
6689 		    (log_page_data[0x1E] << 8)  | log_page_data[0x1F];
6690 
6691 		ncycles =
6692 		    (log_page_data[0x24] << 24) | (log_page_data[0x25] << 16) |
6693 		    (log_page_data[0x26] << 8)  | log_page_data[0x27];
6694 
6695 		if (un->un_f_pm_log_sense_smart) {
6696 			sd_pm_tran_data.un.smart_count.allowed = maxcycles;
6697 			sd_pm_tran_data.un.smart_count.consumed = ncycles;
6698 			sd_pm_tran_data.un.smart_count.flag = 0;
6699 			sd_pm_tran_data.format = DC_SMART_FORMAT;
6700 		} else {
6701 			sd_pm_tran_data.un.scsi_cycles.lifemax = maxcycles;
6702 			sd_pm_tran_data.un.scsi_cycles.ncycles = ncycles;
6703 			for (i = 0; i < DC_SCSI_MFR_LEN; i++) {
6704 				sd_pm_tran_data.un.scsi_cycles.svc_date[i] =
6705 				    log_page_data[8+i];
6706 			}
6707 			sd_pm_tran_data.un.scsi_cycles.flag = 0;
6708 			sd_pm_tran_data.format = DC_SCSI_FORMAT;
6709 		}
6710 
6711 		kmem_free(log_page_data, log_page_size);
6712 
6713 		/*
6714 		 * Call pm_trans_check routine to get the Ok from
6715 		 * the global policy
6716 		 */
6717 		rval = pm_trans_check(&sd_pm_tran_data, &intvlp);
6718 #ifdef	SDDEBUG
6719 		if (sd_force_pm_supported) {
6720 			/* Force a successful result */
6721 			rval = 1;
6722 		}
6723 #endif
6724 		switch (rval) {
6725 		case 0:
6726 			/*
6727 			 * Not Ok to Power cycle or error in parameters passed
6728 			 * Would have given the advised time to consider power
6729 			 * cycle. Based on the new intvlp parameter we are
6730 			 * supposed to pretend we are busy so that pm framework
6731 			 * will never call our power entry point. Because of
6732 			 * that install a timeout handler and wait for the
6733 			 * recommended time to elapse so that power management
6734 			 * can be effective again.
6735 			 *
6736 			 * To effect this behavior, call pm_busy_component to
6737 			 * indicate to the framework this device is busy.
6738 			 * By not adjusting un_pm_count the rest of PM in
6739 			 * the driver will function normally, and independent
6740 			 * of this but because the framework is told the device
6741 			 * is busy it won't attempt powering down until it gets
6742 			 * a matching idle. The timeout handler sends this.
6743 			 * Note: sd_pm_entry can't be called here to do this
6744 			 * because sdpower may have been called as a result
6745 			 * of a call to pm_raise_power from within sd_pm_entry.
6746 			 *
6747 			 * If a timeout handler is already active then
6748 			 * don't install another.
6749 			 */
6750 			mutex_enter(&un->un_pm_mutex);
6751 			if (un->un_pm_timeid == NULL) {
6752 				un->un_pm_timeid =
6753 				    timeout(sd_pm_timeout_handler,
6754 				    un, intvlp * drv_usectohz(1000000));
6755 				mutex_exit(&un->un_pm_mutex);
6756 				(void) pm_busy_component(SD_DEVINFO(un), 0);
6757 			} else {
6758 				mutex_exit(&un->un_pm_mutex);
6759 			}
6760 			if (got_semaphore_here != 0) {
6761 				sema_v(&un->un_semoclose);
6762 			}
6763 			/*
6764 			 * On exit put the state back to it's original value
6765 			 * and broadcast to anyone waiting for the power
6766 			 * change completion.
6767 			 */
6768 			mutex_enter(SD_MUTEX(un));
6769 			un->un_state = state_before_pm;
6770 			cv_broadcast(&un->un_suspend_cv);
6771 			mutex_exit(SD_MUTEX(un));
6772 
6773 			SD_TRACE(SD_LOG_IO_PM, un, "sdpower: exit, "
6774 			    "trans check Failed, not ok to power cycle.\n");
6775 
6776 			goto sdpower_failed;
6777 		case -1:
6778 			if (got_semaphore_here != 0) {
6779 				sema_v(&un->un_semoclose);
6780 			}
6781 			/*
6782 			 * On exit put the state back to it's original value
6783 			 * and broadcast to anyone waiting for the power
6784 			 * change completion.
6785 			 */
6786 			mutex_enter(SD_MUTEX(un));
6787 			un->un_state = state_before_pm;
6788 			cv_broadcast(&un->un_suspend_cv);
6789 			mutex_exit(SD_MUTEX(un));
6790 			SD_TRACE(SD_LOG_IO_PM, un,
6791 			    "sdpower: exit, trans check command Failed.\n");
6792 
6793 			goto sdpower_failed;
6794 		}
6795 	}
6796 
6797 	if (!SD_PM_IS_IO_CAPABLE(un, level)) {
6798 		/*
6799 		 * Save the last state... if the STOP FAILS we need it
6800 		 * for restoring
6801 		 */
6802 		mutex_enter(SD_MUTEX(un));
6803 		save_state = un->un_last_state;
6804 		last_power_level = un->un_power_level;
6805 		/*
6806 		 * There must not be any cmds. getting processed
6807 		 * in the driver when we get here. Power to the
6808 		 * device is potentially going off.
6809 		 */
6810 		ASSERT(un->un_ncmds_in_driver == 0);
6811 		mutex_exit(SD_MUTEX(un));
6812 
6813 		/*
6814 		 * For now PM suspend the device completely before spindle is
6815 		 * turned off
6816 		 */
6817 		if ((rval = sd_pm_state_change(un, level, SD_PM_STATE_CHANGE))
6818 		    == DDI_FAILURE) {
6819 			if (got_semaphore_here != 0) {
6820 				sema_v(&un->un_semoclose);
6821 			}
6822 			/*
6823 			 * On exit put the state back to it's original value
6824 			 * and broadcast to anyone waiting for the power
6825 			 * change completion.
6826 			 */
6827 			mutex_enter(SD_MUTEX(un));
6828 			un->un_state = state_before_pm;
6829 			un->un_power_level = last_power_level;
6830 			cv_broadcast(&un->un_suspend_cv);
6831 			mutex_exit(SD_MUTEX(un));
6832 			SD_TRACE(SD_LOG_IO_PM, un,
6833 			    "sdpower: exit, PM suspend Failed.\n");
6834 
6835 			goto sdpower_failed;
6836 		}
6837 	}
6838 
6839 	/*
6840 	 * The transition from SPINDLE_OFF to SPINDLE_ON can happen in open,
6841 	 * close, or strategy. Dump no long uses this routine, it uses it's
6842 	 * own code so it can be done in polled mode.
6843 	 */
6844 
6845 	medium_present = TRUE;
6846 
6847 	/*
6848 	 * When powering up, issue a TUR in case the device is at unit
6849 	 * attention.  Don't do retries. Bypass the PM layer, otherwise
6850 	 * a deadlock on un_pm_busy_cv will occur.
6851 	 */
6852 	if (SD_PM_IS_IO_CAPABLE(un, level)) {
6853 		sval = sd_send_scsi_TEST_UNIT_READY(ssc,
6854 		    SD_DONT_RETRY_TUR | SD_BYPASS_PM);
6855 		if (sval != 0)
6856 			sd_ssc_assessment(ssc, SD_FMT_IGNORE);
6857 	}
6858 
6859 	if (un->un_f_power_condition_supported) {
6860 		char *pm_condition_name[] = {"STOPPED", "STANDBY",
6861 		    "IDLE", "ACTIVE"};
6862 		SD_TRACE(SD_LOG_IO_PM, un,
6863 		    "sdpower: sending \'%s\' power condition",
6864 		    pm_condition_name[level]);
6865 		sval = sd_send_scsi_START_STOP_UNIT(ssc, SD_POWER_CONDITION,
6866 		    sd_pl2pc[level], SD_PATH_DIRECT);
6867 	} else {
6868 		SD_TRACE(SD_LOG_IO_PM, un, "sdpower: sending \'%s\' unit\n",
6869 		    ((level == SD_SPINDLE_ON) ? "START" : "STOP"));
6870 		sval = sd_send_scsi_START_STOP_UNIT(ssc, SD_START_STOP,
6871 		    ((level == SD_SPINDLE_ON) ? SD_TARGET_START :
6872 		    SD_TARGET_STOP), SD_PATH_DIRECT);
6873 	}
6874 	if (sval != 0) {
6875 		if (sval == EIO)
6876 			sd_ssc_assessment(ssc, SD_FMT_STATUS_CHECK);
6877 		else
6878 			sd_ssc_assessment(ssc, SD_FMT_IGNORE);
6879 	}
6880 
6881 	/* Command failed, check for media present. */
6882 	if ((sval == ENXIO) && un->un_f_has_removable_media) {
6883 		medium_present = FALSE;
6884 	}
6885 
6886 	/*
6887 	 * The conditions of interest here are:
6888 	 *   if a spindle off with media present fails,
6889 	 *	then restore the state and return an error.
6890 	 *   else if a spindle on fails,
6891 	 *	then return an error (there's no state to restore).
6892 	 * In all other cases we setup for the new state
6893 	 * and return success.
6894 	 */
6895 	if (!SD_PM_IS_IO_CAPABLE(un, level)) {
6896 		if ((medium_present == TRUE) && (sval != 0)) {
6897 			/* The stop command from above failed */
6898 			rval = DDI_FAILURE;
6899 			/*
6900 			 * The stop command failed, and we have media
6901 			 * present. Put the level back by calling the
6902 			 * sd_pm_resume() and set the state back to
6903 			 * it's previous value.
6904 			 */
6905 			(void) sd_pm_state_change(un, last_power_level,
6906 			    SD_PM_STATE_ROLLBACK);
6907 			mutex_enter(SD_MUTEX(un));
6908 			un->un_last_state = save_state;
6909 			mutex_exit(SD_MUTEX(un));
6910 		} else if (un->un_f_monitor_media_state) {
6911 			/*
6912 			 * The stop command from above succeeded.
6913 			 * Terminate watch thread in case of removable media
6914 			 * devices going into low power state. This is as per
6915 			 * the requirements of pm framework, otherwise commands
6916 			 * will be generated for the device (through watch
6917 			 * thread), even when the device is in low power state.
6918 			 */
6919 			mutex_enter(SD_MUTEX(un));
6920 			un->un_f_watcht_stopped = FALSE;
6921 			if (un->un_swr_token != NULL) {
6922 				opaque_t temp_token = un->un_swr_token;
6923 				un->un_f_watcht_stopped = TRUE;
6924 				un->un_swr_token = NULL;
6925 				mutex_exit(SD_MUTEX(un));
6926 				(void) scsi_watch_request_terminate(temp_token,
6927 				    SCSI_WATCH_TERMINATE_ALL_WAIT);
6928 			} else {
6929 				mutex_exit(SD_MUTEX(un));
6930 			}
6931 		}
6932 	} else {
6933 		/*
6934 		 * The level requested is I/O capable.
6935 		 * Legacy behavior: return success on a failed spinup
6936 		 * if there is no media in the drive.
6937 		 * Do this by looking at medium_present here.
6938 		 */
6939 		if ((sval != 0) && medium_present) {
6940 			/* The start command from above failed */
6941 			rval = DDI_FAILURE;
6942 		} else {
6943 			/*
6944 			 * The start command from above succeeded
6945 			 * PM resume the devices now that we have
6946 			 * started the disks
6947 			 */
6948 			(void) sd_pm_state_change(un, level,
6949 			    SD_PM_STATE_CHANGE);
6950 
6951 			/*
6952 			 * Resume the watch thread since it was suspended
6953 			 * when the device went into low power mode.
6954 			 */
6955 			if (un->un_f_monitor_media_state) {
6956 				mutex_enter(SD_MUTEX(un));
6957 				if (un->un_f_watcht_stopped == TRUE) {
6958 					opaque_t temp_token;
6959 
6960 					un->un_f_watcht_stopped = FALSE;
6961 					mutex_exit(SD_MUTEX(un));
6962 					temp_token = scsi_watch_request_submit(
6963 					    SD_SCSI_DEVP(un),
6964 					    sd_check_media_time,
6965 					    SENSE_LENGTH, sd_media_watch_cb,
6966 					    (caddr_t)dev);
6967 					mutex_enter(SD_MUTEX(un));
6968 					un->un_swr_token = temp_token;
6969 				}
6970 				mutex_exit(SD_MUTEX(un));
6971 			}
6972 		}
6973 	}
6974 
6975 	if (got_semaphore_here != 0) {
6976 		sema_v(&un->un_semoclose);
6977 	}
6978 	/*
6979 	 * On exit put the state back to it's original value
6980 	 * and broadcast to anyone waiting for the power
6981 	 * change completion.
6982 	 */
6983 	mutex_enter(SD_MUTEX(un));
6984 	un->un_state = state_before_pm;
6985 	cv_broadcast(&un->un_suspend_cv);
6986 	mutex_exit(SD_MUTEX(un));
6987 
6988 	SD_TRACE(SD_LOG_IO_PM, un, "sdpower: exit, status = 0x%x\n", rval);
6989 
6990 	sd_ssc_fini(ssc);
6991 	return (rval);
6992 
6993 sdpower_failed:
6994 
6995 	sd_ssc_fini(ssc);
6996 	return (DDI_FAILURE);
6997 }
6998 
6999 
7000 
7001 /*
7002  *    Function: sdattach
7003  *
7004  * Description: Driver's attach(9e) entry point function.
7005  *
7006  *   Arguments: devi - opaque device info handle
7007  *		cmd  - attach  type
7008  *
7009  * Return Code: DDI_SUCCESS
7010  *		DDI_FAILURE
7011  *
7012  *     Context: Kernel thread context
7013  */
7014 
7015 static int
7016 sdattach(dev_info_t *devi, ddi_attach_cmd_t cmd)
7017 {
7018 	switch (cmd) {
7019 	case DDI_ATTACH:
7020 		return (sd_unit_attach(devi));
7021 	case DDI_RESUME:
7022 		return (sd_ddi_resume(devi));
7023 	default:
7024 		break;
7025 	}
7026 	return (DDI_FAILURE);
7027 }
7028 
7029 
7030 /*
7031  *    Function: sddetach
7032  *
7033  * Description: Driver's detach(9E) entry point function.
7034  *
7035  *   Arguments: devi - opaque device info handle
7036  *		cmd  - detach  type
7037  *
7038  * Return Code: DDI_SUCCESS
7039  *		DDI_FAILURE
7040  *
7041  *     Context: Kernel thread context
7042  */
7043 
7044 static int
7045 sddetach(dev_info_t *devi, ddi_detach_cmd_t cmd)
7046 {
7047 	switch (cmd) {
7048 	case DDI_DETACH:
7049 		return (sd_unit_detach(devi));
7050 	case DDI_SUSPEND:
7051 		return (sd_ddi_suspend(devi));
7052 	default:
7053 		break;
7054 	}
7055 	return (DDI_FAILURE);
7056 }
7057 
7058 
7059 /*
7060  *     Function: sd_sync_with_callback
7061  *
7062  *  Description: Prevents sd_unit_attach or sd_unit_detach from freeing the soft
7063  *		 state while the callback routine is active.
7064  *
7065  *    Arguments: un: softstate structure for the instance
7066  *
7067  *	Context: Kernel thread context
7068  */
7069 
7070 static void
7071 sd_sync_with_callback(struct sd_lun *un)
7072 {
7073 	ASSERT(un != NULL);
7074 
7075 	mutex_enter(SD_MUTEX(un));
7076 
7077 	ASSERT(un->un_in_callback >= 0);
7078 
7079 	while (un->un_in_callback > 0) {
7080 		mutex_exit(SD_MUTEX(un));
7081 		delay(2);
7082 		mutex_enter(SD_MUTEX(un));
7083 	}
7084 
7085 	mutex_exit(SD_MUTEX(un));
7086 }
7087 
7088 /*
7089  *    Function: sd_unit_attach
7090  *
7091  * Description: Performs DDI_ATTACH processing for sdattach(). Allocates
7092  *		the soft state structure for the device and performs
7093  *		all necessary structure and device initializations.
7094  *
7095  *   Arguments: devi: the system's dev_info_t for the device.
7096  *
7097  * Return Code: DDI_SUCCESS if attach is successful.
7098  *		DDI_FAILURE if any part of the attach fails.
7099  *
7100  *     Context: Called at attach(9e) time for the DDI_ATTACH flag.
7101  *		Kernel thread context only.  Can sleep.
7102  */
7103 
7104 static int
7105 sd_unit_attach(dev_info_t *devi)
7106 {
7107 	struct	scsi_device	*devp;
7108 	struct	sd_lun		*un;
7109 	char			*variantp;
7110 	char			name_str[48];
7111 	int	reservation_flag = SD_TARGET_IS_UNRESERVED;
7112 	int	instance;
7113 	int	rval;
7114 	int	wc_enabled;
7115 	int	tgt;
7116 	uint64_t	capacity;
7117 	uint_t		lbasize = 0;
7118 	dev_info_t	*pdip = ddi_get_parent(devi);
7119 	int		offbyone = 0;
7120 	int		geom_label_valid = 0;
7121 	sd_ssc_t	*ssc;
7122 	int		status;
7123 	struct sd_fm_internal	*sfip = NULL;
7124 	int		max_xfer_size;
7125 
7126 	/*
7127 	 * Retrieve the target driver's private data area. This was set
7128 	 * up by the HBA.
7129 	 */
7130 	devp = ddi_get_driver_private(devi);
7131 
7132 	/*
7133 	 * Retrieve the target ID of the device.
7134 	 */
7135 	tgt = ddi_prop_get_int(DDI_DEV_T_ANY, devi, DDI_PROP_DONTPASS,
7136 	    SCSI_ADDR_PROP_TARGET, -1);
7137 
7138 	/*
7139 	 * Since we have no idea what state things were left in by the last
7140 	 * user of the device, set up some 'default' settings, ie. turn 'em
7141 	 * off. The scsi_ifsetcap calls force re-negotiations with the drive.
7142 	 * Do this before the scsi_probe, which sends an inquiry.
7143 	 * This is a fix for bug (4430280).
7144 	 * Of special importance is wide-xfer. The drive could have been left
7145 	 * in wide transfer mode by the last driver to communicate with it,
7146 	 * this includes us. If that's the case, and if the following is not
7147 	 * setup properly or we don't re-negotiate with the drive prior to
7148 	 * transferring data to/from the drive, it causes bus parity errors,
7149 	 * data overruns, and unexpected interrupts. This first occurred when
7150 	 * the fix for bug (4378686) was made.
7151 	 */
7152 	(void) scsi_ifsetcap(&devp->sd_address, "lun-reset", 0, 1);
7153 	(void) scsi_ifsetcap(&devp->sd_address, "wide-xfer", 0, 1);
7154 	(void) scsi_ifsetcap(&devp->sd_address, "auto-rqsense", 0, 1);
7155 
7156 	/*
7157 	 * Currently, scsi_ifsetcap sets tagged-qing capability for all LUNs
7158 	 * on a target. Setting it per lun instance actually sets the
7159 	 * capability of this target, which affects those luns already
7160 	 * attached on the same target. So during attach, we can only disable
7161 	 * this capability only when no other lun has been attached on this
7162 	 * target. By doing this, we assume a target has the same tagged-qing
7163 	 * capability for every lun. The condition can be removed when HBA
7164 	 * is changed to support per lun based tagged-qing capability.
7165 	 */
7166 	if (sd_scsi_get_target_lun_count(pdip, tgt) < 1) {
7167 		(void) scsi_ifsetcap(&devp->sd_address, "tagged-qing", 0, 1);
7168 	}
7169 
7170 	/*
7171 	 * Use scsi_probe() to issue an INQUIRY command to the device.
7172 	 * This call will allocate and fill in the scsi_inquiry structure
7173 	 * and point the sd_inq member of the scsi_device structure to it.
7174 	 * If the attach succeeds, then this memory will not be de-allocated
7175 	 * (via scsi_unprobe()) until the instance is detached.
7176 	 */
7177 	if (scsi_probe(devp, SLEEP_FUNC) != SCSIPROBE_EXISTS) {
7178 		goto probe_failed;
7179 	}
7180 
7181 	/*
7182 	 * Check the device type as specified in the inquiry data and
7183 	 * claim it if it is of a type that we support.
7184 	 */
7185 	switch (devp->sd_inq->inq_dtype) {
7186 	case DTYPE_DIRECT:
7187 		break;
7188 	case DTYPE_RODIRECT:
7189 		break;
7190 	case DTYPE_OPTICAL:
7191 		break;
7192 	case DTYPE_NOTPRESENT:
7193 	default:
7194 		/* Unsupported device type; fail the attach. */
7195 		goto probe_failed;
7196 	}
7197 
7198 	/*
7199 	 * Allocate the soft state structure for this unit.
7200 	 *
7201 	 * We rely upon this memory being set to all zeroes by
7202 	 * ddi_soft_state_zalloc().  We assume that any member of the
7203 	 * soft state structure that is not explicitly initialized by
7204 	 * this routine will have a value of zero.
7205 	 */
7206 	instance = ddi_get_instance(devp->sd_dev);
7207 #ifndef XPV_HVM_DRIVER
7208 	if (ddi_soft_state_zalloc(sd_state, instance) != DDI_SUCCESS) {
7209 		goto probe_failed;
7210 	}
7211 #endif /* !XPV_HVM_DRIVER */
7212 
7213 	/*
7214 	 * Retrieve a pointer to the newly-allocated soft state.
7215 	 *
7216 	 * This should NEVER fail if the ddi_soft_state_zalloc() call above
7217 	 * was successful, unless something has gone horribly wrong and the
7218 	 * ddi's soft state internals are corrupt (in which case it is
7219 	 * probably better to halt here than just fail the attach....)
7220 	 */
7221 	if ((un = ddi_get_soft_state(sd_state, instance)) == NULL) {
7222 		panic("sd_unit_attach: NULL soft state on instance:0x%x",
7223 		    instance);
7224 		/*NOTREACHED*/
7225 	}
7226 
7227 	/*
7228 	 * Link the back ptr of the driver soft state to the scsi_device
7229 	 * struct for this lun.
7230 	 * Save a pointer to the softstate in the driver-private area of
7231 	 * the scsi_device struct.
7232 	 * Note: We cannot call SD_INFO, SD_TRACE, SD_ERROR, or SD_DIAG until
7233 	 * we first set un->un_sd below.
7234 	 */
7235 	un->un_sd = devp;
7236 	devp->sd_private = (opaque_t)un;
7237 
7238 	/*
7239 	 * The following must be after devp is stored in the soft state struct.
7240 	 */
7241 #ifdef SDDEBUG
7242 	SD_TRACE(SD_LOG_ATTACH_DETACH, un,
7243 	    "%s_unit_attach: un:0x%p instance:%d\n",
7244 	    ddi_driver_name(devi), un, instance);
7245 #endif
7246 
7247 	/*
7248 	 * Set up the device type and node type (for the minor nodes).
7249 	 * By default we assume that the device can at least support the
7250 	 * Common Command Set. Call it a CD-ROM if it reports itself
7251 	 * as a RODIRECT device.
7252 	 */
7253 	switch (devp->sd_inq->inq_dtype) {
7254 	case DTYPE_RODIRECT:
7255 		un->un_node_type = DDI_NT_CD_CHAN;
7256 		un->un_ctype	 = CTYPE_CDROM;
7257 		break;
7258 	case DTYPE_OPTICAL:
7259 		un->un_node_type = DDI_NT_BLOCK_CHAN;
7260 		un->un_ctype	 = CTYPE_ROD;
7261 		break;
7262 	default:
7263 		un->un_node_type = DDI_NT_BLOCK_CHAN;
7264 		un->un_ctype	 = CTYPE_CCS;
7265 		break;
7266 	}
7267 
7268 	/*
7269 	 * Try to read the interconnect type from the HBA.
7270 	 *
7271 	 * Note: This driver is currently compiled as two binaries, a parallel
7272 	 * scsi version (sd) and a fibre channel version (ssd). All functional
7273 	 * differences are determined at compile time. In the future a single
7274 	 * binary will be provided and the interconnect type will be used to
7275 	 * differentiate between fibre and parallel scsi behaviors. At that time
7276 	 * it will be necessary for all fibre channel HBAs to support this
7277 	 * property.
7278 	 *
7279 	 * set un_f_is_fiber to TRUE ( default fiber )
7280 	 */
7281 	un->un_f_is_fibre = TRUE;
7282 	switch (scsi_ifgetcap(SD_ADDRESS(un), "interconnect-type", -1)) {
7283 	case INTERCONNECT_SSA:
7284 		un->un_interconnect_type = SD_INTERCONNECT_SSA;
7285 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
7286 		    "sd_unit_attach: un:0x%p SD_INTERCONNECT_SSA\n", un);
7287 		break;
7288 	case INTERCONNECT_PARALLEL:
7289 		un->un_f_is_fibre = FALSE;
7290 		un->un_interconnect_type = SD_INTERCONNECT_PARALLEL;
7291 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
7292 		    "sd_unit_attach: un:0x%p SD_INTERCONNECT_PARALLEL\n", un);
7293 		break;
7294 	case INTERCONNECT_SAS:
7295 		un->un_f_is_fibre = FALSE;
7296 		un->un_interconnect_type = SD_INTERCONNECT_SAS;
7297 		un->un_node_type = DDI_NT_BLOCK_SAS;
7298 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
7299 		    "sd_unit_attach: un:0x%p SD_INTERCONNECT_SAS\n", un);
7300 		break;
7301 	case INTERCONNECT_SATA:
7302 		un->un_f_is_fibre = FALSE;
7303 		un->un_interconnect_type = SD_INTERCONNECT_SATA;
7304 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
7305 		    "sd_unit_attach: un:0x%p SD_INTERCONNECT_SATA\n", un);
7306 		break;
7307 	case INTERCONNECT_FIBRE:
7308 		un->un_interconnect_type = SD_INTERCONNECT_FIBRE;
7309 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
7310 		    "sd_unit_attach: un:0x%p SD_INTERCONNECT_FIBRE\n", un);
7311 		break;
7312 	case INTERCONNECT_FABRIC:
7313 		un->un_interconnect_type = SD_INTERCONNECT_FABRIC;
7314 		un->un_node_type = DDI_NT_BLOCK_FABRIC;
7315 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
7316 		    "sd_unit_attach: un:0x%p SD_INTERCONNECT_FABRIC\n", un);
7317 		break;
7318 	default:
7319 #ifdef SD_DEFAULT_INTERCONNECT_TYPE
7320 		/*
7321 		 * The HBA does not support the "interconnect-type" property
7322 		 * (or did not provide a recognized type).
7323 		 *
7324 		 * Note: This will be obsoleted when a single fibre channel
7325 		 * and parallel scsi driver is delivered. In the meantime the
7326 		 * interconnect type will be set to the platform default.If that
7327 		 * type is not parallel SCSI, it means that we should be
7328 		 * assuming "ssd" semantics. However, here this also means that
7329 		 * the FC HBA is not supporting the "interconnect-type" property
7330 		 * like we expect it to, so log this occurrence.
7331 		 */
7332 		un->un_interconnect_type = SD_DEFAULT_INTERCONNECT_TYPE;
7333 		if (!SD_IS_PARALLEL_SCSI(un)) {
7334 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
7335 			    "sd_unit_attach: un:0x%p Assuming "
7336 			    "INTERCONNECT_FIBRE\n", un);
7337 		} else {
7338 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
7339 			    "sd_unit_attach: un:0x%p Assuming "
7340 			    "INTERCONNECT_PARALLEL\n", un);
7341 			un->un_f_is_fibre = FALSE;
7342 		}
7343 #else
7344 		/*
7345 		 * Note: This source will be implemented when a single fibre
7346 		 * channel and parallel scsi driver is delivered. The default
7347 		 * will be to assume that if a device does not support the
7348 		 * "interconnect-type" property it is a parallel SCSI HBA and
7349 		 * we will set the interconnect type for parallel scsi.
7350 		 */
7351 		un->un_interconnect_type = SD_INTERCONNECT_PARALLEL;
7352 		un->un_f_is_fibre = FALSE;
7353 #endif
7354 		break;
7355 	}
7356 
7357 	if (un->un_f_is_fibre == TRUE) {
7358 		if (scsi_ifgetcap(SD_ADDRESS(un), "scsi-version", 1) ==
7359 		    SCSI_VERSION_3) {
7360 			switch (un->un_interconnect_type) {
7361 			case SD_INTERCONNECT_FIBRE:
7362 			case SD_INTERCONNECT_SSA:
7363 				un->un_node_type = DDI_NT_BLOCK_WWN;
7364 				break;
7365 			default:
7366 				break;
7367 			}
7368 		}
7369 	}
7370 
7371 	/*
7372 	 * Initialize the Request Sense command for the target
7373 	 */
7374 	if (sd_alloc_rqs(devp, un) != DDI_SUCCESS) {
7375 		goto alloc_rqs_failed;
7376 	}
7377 
7378 	/*
7379 	 * Set un_retry_count with SD_RETRY_COUNT, this is ok for Sparc
7380 	 * with separate binary for sd and ssd.
7381 	 *
7382 	 * x86 has 1 binary, un_retry_count is set base on connection type.
7383 	 * The hardcoded values will go away when Sparc uses 1 binary
7384 	 * for sd and ssd.  This hardcoded values need to match
7385 	 * SD_RETRY_COUNT in sddef.h
7386 	 * The value used is base on interconnect type.
7387 	 * fibre = 3, parallel = 5
7388 	 */
7389 #if defined(__i386) || defined(__amd64)
7390 	un->un_retry_count = un->un_f_is_fibre ? 3 : 5;
7391 #else
7392 	un->un_retry_count = SD_RETRY_COUNT;
7393 #endif
7394 
7395 	/*
7396 	 * Set the per disk retry count to the default number of retries
7397 	 * for disks and CDROMs. This value can be overridden by the
7398 	 * disk property list or an entry in sd.conf.
7399 	 */
7400 	un->un_notready_retry_count =
7401 	    ISCD(un) ? CD_NOT_READY_RETRY_COUNT(un)
7402 	    : DISK_NOT_READY_RETRY_COUNT(un);
7403 
7404 	/*
7405 	 * Set the busy retry count to the default value of un_retry_count.
7406 	 * This can be overridden by entries in sd.conf or the device
7407 	 * config table.
7408 	 */
7409 	un->un_busy_retry_count = un->un_retry_count;
7410 
7411 	/*
7412 	 * Init the reset threshold for retries.  This number determines
7413 	 * how many retries must be performed before a reset can be issued
7414 	 * (for certain error conditions). This can be overridden by entries
7415 	 * in sd.conf or the device config table.
7416 	 */
7417 	un->un_reset_retry_count = (un->un_retry_count / 2);
7418 
7419 	/*
7420 	 * Set the victim_retry_count to the default un_retry_count
7421 	 */
7422 	un->un_victim_retry_count = (2 * un->un_retry_count);
7423 
7424 	/*
7425 	 * Set the reservation release timeout to the default value of
7426 	 * 5 seconds. This can be overridden by entries in ssd.conf or the
7427 	 * device config table.
7428 	 */
7429 	un->un_reserve_release_time = 5;
7430 
7431 	/*
7432 	 * Set up the default maximum transfer size. Note that this may
7433 	 * get updated later in the attach, when setting up default wide
7434 	 * operations for disks.
7435 	 */
7436 #if defined(__i386) || defined(__amd64)
7437 	un->un_max_xfer_size = (uint_t)SD_DEFAULT_MAX_XFER_SIZE;
7438 	un->un_partial_dma_supported = 1;
7439 #else
7440 	un->un_max_xfer_size = (uint_t)maxphys;
7441 #endif
7442 
7443 	/*
7444 	 * Get "allow bus device reset" property (defaults to "enabled" if
7445 	 * the property was not defined). This is to disable bus resets for
7446 	 * certain kinds of error recovery. Note: In the future when a run-time
7447 	 * fibre check is available the soft state flag should default to
7448 	 * enabled.
7449 	 */
7450 	if (un->un_f_is_fibre == TRUE) {
7451 		un->un_f_allow_bus_device_reset = TRUE;
7452 	} else {
7453 		if (ddi_getprop(DDI_DEV_T_ANY, devi, DDI_PROP_DONTPASS,
7454 		    "allow-bus-device-reset", 1) != 0) {
7455 			un->un_f_allow_bus_device_reset = TRUE;
7456 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
7457 			    "sd_unit_attach: un:0x%p Bus device reset "
7458 			    "enabled\n", un);
7459 		} else {
7460 			un->un_f_allow_bus_device_reset = FALSE;
7461 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
7462 			    "sd_unit_attach: un:0x%p Bus device reset "
7463 			    "disabled\n", un);
7464 		}
7465 	}
7466 
7467 	/*
7468 	 * Check if this is an ATAPI device. ATAPI devices use Group 1
7469 	 * Read/Write commands and Group 2 Mode Sense/Select commands.
7470 	 *
7471 	 * Note: The "obsolete" way of doing this is to check for the "atapi"
7472 	 * property. The new "variant" property with a value of "atapi" has been
7473 	 * introduced so that future 'variants' of standard SCSI behavior (like
7474 	 * atapi) could be specified by the underlying HBA drivers by supplying
7475 	 * a new value for the "variant" property, instead of having to define a
7476 	 * new property.
7477 	 */
7478 	if (ddi_prop_get_int(DDI_DEV_T_ANY, devi, 0, "atapi", -1) != -1) {
7479 		un->un_f_cfg_is_atapi = TRUE;
7480 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
7481 		    "sd_unit_attach: un:0x%p Atapi device\n", un);
7482 	}
7483 	if (ddi_prop_lookup_string(DDI_DEV_T_ANY, devi, 0, "variant",
7484 	    &variantp) == DDI_PROP_SUCCESS) {
7485 		if (strcmp(variantp, "atapi") == 0) {
7486 			un->un_f_cfg_is_atapi = TRUE;
7487 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
7488 			    "sd_unit_attach: un:0x%p Atapi device\n", un);
7489 		}
7490 		ddi_prop_free(variantp);
7491 	}
7492 
7493 	un->un_cmd_timeout	= SD_IO_TIME;
7494 
7495 	un->un_busy_timeout  = SD_BSY_TIMEOUT;
7496 
7497 	/* Info on current states, statuses, etc. (Updated frequently) */
7498 	un->un_state		= SD_STATE_NORMAL;
7499 	un->un_last_state	= SD_STATE_NORMAL;
7500 
7501 	/* Control & status info for command throttling */
7502 	un->un_throttle		= sd_max_throttle;
7503 	un->un_saved_throttle	= sd_max_throttle;
7504 	un->un_min_throttle	= sd_min_throttle;
7505 
7506 	if (un->un_f_is_fibre == TRUE) {
7507 		un->un_f_use_adaptive_throttle = TRUE;
7508 	} else {
7509 		un->un_f_use_adaptive_throttle = FALSE;
7510 	}
7511 
7512 	/* Removable media support. */
7513 	cv_init(&un->un_state_cv, NULL, CV_DRIVER, NULL);
7514 	un->un_mediastate		= DKIO_NONE;
7515 	un->un_specified_mediastate	= DKIO_NONE;
7516 
7517 	/* CVs for suspend/resume (PM or DR) */
7518 	cv_init(&un->un_suspend_cv,   NULL, CV_DRIVER, NULL);
7519 	cv_init(&un->un_disk_busy_cv, NULL, CV_DRIVER, NULL);
7520 
7521 	/* Power management support. */
7522 	un->un_power_level = SD_SPINDLE_UNINIT;
7523 
7524 	cv_init(&un->un_wcc_cv,   NULL, CV_DRIVER, NULL);
7525 	un->un_f_wcc_inprog = 0;
7526 
7527 	/*
7528 	 * The open/close semaphore is used to serialize threads executing
7529 	 * in the driver's open & close entry point routines for a given
7530 	 * instance.
7531 	 */
7532 	(void) sema_init(&un->un_semoclose, 1, NULL, SEMA_DRIVER, NULL);
7533 
7534 	/*
7535 	 * The conf file entry and softstate variable is a forceful override,
7536 	 * meaning a non-zero value must be entered to change the default.
7537 	 */
7538 	un->un_f_disksort_disabled = FALSE;
7539 	un->un_f_rmw_type = SD_RMW_TYPE_DEFAULT;
7540 
7541 	/*
7542 	 * Retrieve the properties from the static driver table or the driver
7543 	 * configuration file (.conf) for this unit and update the soft state
7544 	 * for the device as needed for the indicated properties.
7545 	 * Note: the property configuration needs to occur here as some of the
7546 	 * following routines may have dependencies on soft state flags set
7547 	 * as part of the driver property configuration.
7548 	 */
7549 	sd_read_unit_properties(un);
7550 	SD_TRACE(SD_LOG_ATTACH_DETACH, un,
7551 	    "sd_unit_attach: un:0x%p property configuration complete.\n", un);
7552 
7553 	/*
7554 	 * Only if a device has "hotpluggable" property, it is
7555 	 * treated as hotpluggable device. Otherwise, it is
7556 	 * regarded as non-hotpluggable one.
7557 	 */
7558 	if (ddi_prop_get_int(DDI_DEV_T_ANY, devi, 0, "hotpluggable",
7559 	    -1) != -1) {
7560 		un->un_f_is_hotpluggable = TRUE;
7561 	}
7562 
7563 	/*
7564 	 * set unit's attributes(flags) according to "hotpluggable" and
7565 	 * RMB bit in INQUIRY data.
7566 	 */
7567 	sd_set_unit_attributes(un, devi);
7568 
7569 	/*
7570 	 * By default, we mark the capacity, lbasize, and geometry
7571 	 * as invalid. Only if we successfully read a valid capacity
7572 	 * will we update the un_blockcount and un_tgt_blocksize with the
7573 	 * valid values (the geometry will be validated later).
7574 	 */
7575 	un->un_f_blockcount_is_valid	= FALSE;
7576 	un->un_f_tgt_blocksize_is_valid	= FALSE;
7577 
7578 	/*
7579 	 * Use DEV_BSIZE and DEV_BSHIFT as defaults, until we can determine
7580 	 * otherwise.
7581 	 */
7582 	un->un_tgt_blocksize  = un->un_sys_blocksize  = DEV_BSIZE;
7583 	un->un_blockcount = 0;
7584 
7585 	/*
7586 	 * Set up the per-instance info needed to determine the correct
7587 	 * CDBs and other info for issuing commands to the target.
7588 	 */
7589 	sd_init_cdb_limits(un);
7590 
7591 	/*
7592 	 * Set up the IO chains to use, based upon the target type.
7593 	 */
7594 	if (un->un_f_non_devbsize_supported) {
7595 		un->un_buf_chain_type = SD_CHAIN_INFO_RMMEDIA;
7596 	} else {
7597 		un->un_buf_chain_type = SD_CHAIN_INFO_DISK;
7598 	}
7599 	un->un_uscsi_chain_type  = SD_CHAIN_INFO_USCSI_CMD;
7600 	un->un_direct_chain_type = SD_CHAIN_INFO_DIRECT_CMD;
7601 	un->un_priority_chain_type = SD_CHAIN_INFO_PRIORITY_CMD;
7602 
7603 	un->un_xbuf_attr = ddi_xbuf_attr_create(sizeof (struct sd_xbuf),
7604 	    sd_xbuf_strategy, un, sd_xbuf_active_limit,  sd_xbuf_reserve_limit,
7605 	    ddi_driver_major(devi), DDI_XBUF_QTHREAD_DRIVER);
7606 	ddi_xbuf_attr_register_devinfo(un->un_xbuf_attr, devi);
7607 
7608 
7609 	if (ISCD(un)) {
7610 		un->un_additional_codes = sd_additional_codes;
7611 	} else {
7612 		un->un_additional_codes = NULL;
7613 	}
7614 
7615 	/*
7616 	 * Create the kstats here so they can be available for attach-time
7617 	 * routines that send commands to the unit (either polled or via
7618 	 * sd_send_scsi_cmd).
7619 	 *
7620 	 * Note: This is a critical sequence that needs to be maintained:
7621 	 *	1) Instantiate the kstats here, before any routines using the
7622 	 *	   iopath (i.e. sd_send_scsi_cmd).
7623 	 *	2) Instantiate and initialize the partition stats
7624 	 *	   (sd_set_pstats).
7625 	 *	3) Initialize the error stats (sd_set_errstats), following
7626 	 *	   sd_validate_geometry(),sd_register_devid(),
7627 	 *	   and sd_cache_control().
7628 	 */
7629 
7630 	un->un_stats = kstat_create(sd_label, instance,
7631 	    NULL, "disk", KSTAT_TYPE_IO, 1, KSTAT_FLAG_PERSISTENT);
7632 	if (un->un_stats != NULL) {
7633 		un->un_stats->ks_lock = SD_MUTEX(un);
7634 		kstat_install(un->un_stats);
7635 	}
7636 	SD_TRACE(SD_LOG_ATTACH_DETACH, un,
7637 	    "sd_unit_attach: un:0x%p un_stats created\n", un);
7638 
7639 	sd_create_errstats(un, instance);
7640 	if (un->un_errstats == NULL) {
7641 		goto create_errstats_failed;
7642 	}
7643 	SD_TRACE(SD_LOG_ATTACH_DETACH, un,
7644 	    "sd_unit_attach: un:0x%p errstats created\n", un);
7645 
7646 	/*
7647 	 * The following if/else code was relocated here from below as part
7648 	 * of the fix for bug (4430280). However with the default setup added
7649 	 * on entry to this routine, it's no longer absolutely necessary for
7650 	 * this to be before the call to sd_spin_up_unit.
7651 	 */
7652 	if (SD_IS_PARALLEL_SCSI(un) || SD_IS_SERIAL(un)) {
7653 		int tq_trigger_flag = (((devp->sd_inq->inq_ansi == 4) ||
7654 		    (devp->sd_inq->inq_ansi == 5)) &&
7655 		    devp->sd_inq->inq_bque) || devp->sd_inq->inq_cmdque;
7656 
7657 		/*
7658 		 * If tagged queueing is supported by the target
7659 		 * and by the host adapter then we will enable it
7660 		 */
7661 		un->un_tagflags = 0;
7662 		if ((devp->sd_inq->inq_rdf == RDF_SCSI2) && tq_trigger_flag &&
7663 		    (un->un_f_arq_enabled == TRUE)) {
7664 			if (scsi_ifsetcap(SD_ADDRESS(un), "tagged-qing",
7665 			    1, 1) == 1) {
7666 				un->un_tagflags = FLAG_STAG;
7667 				SD_INFO(SD_LOG_ATTACH_DETACH, un,
7668 				    "sd_unit_attach: un:0x%p tag queueing "
7669 				    "enabled\n", un);
7670 			} else if (scsi_ifgetcap(SD_ADDRESS(un),
7671 			    "untagged-qing", 0) == 1) {
7672 				un->un_f_opt_queueing = TRUE;
7673 				un->un_saved_throttle = un->un_throttle =
7674 				    min(un->un_throttle, 3);
7675 			} else {
7676 				un->un_f_opt_queueing = FALSE;
7677 				un->un_saved_throttle = un->un_throttle = 1;
7678 			}
7679 		} else if ((scsi_ifgetcap(SD_ADDRESS(un), "untagged-qing", 0)
7680 		    == 1) && (un->un_f_arq_enabled == TRUE)) {
7681 			/* The Host Adapter supports internal queueing. */
7682 			un->un_f_opt_queueing = TRUE;
7683 			un->un_saved_throttle = un->un_throttle =
7684 			    min(un->un_throttle, 3);
7685 		} else {
7686 			un->un_f_opt_queueing = FALSE;
7687 			un->un_saved_throttle = un->un_throttle = 1;
7688 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
7689 			    "sd_unit_attach: un:0x%p no tag queueing\n", un);
7690 		}
7691 
7692 		/*
7693 		 * Enable large transfers for SATA/SAS drives
7694 		 */
7695 		if (SD_IS_SERIAL(un)) {
7696 			un->un_max_xfer_size =
7697 			    ddi_getprop(DDI_DEV_T_ANY, devi, 0,
7698 			    sd_max_xfer_size, SD_MAX_XFER_SIZE);
7699 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
7700 			    "sd_unit_attach: un:0x%p max transfer "
7701 			    "size=0x%x\n", un, un->un_max_xfer_size);
7702 
7703 		}
7704 
7705 		/* Setup or tear down default wide operations for disks */
7706 
7707 		/*
7708 		 * Note: Legacy: it may be possible for both "sd_max_xfer_size"
7709 		 * and "ssd_max_xfer_size" to exist simultaneously on the same
7710 		 * system and be set to different values. In the future this
7711 		 * code may need to be updated when the ssd module is
7712 		 * obsoleted and removed from the system. (4299588)
7713 		 */
7714 		if (SD_IS_PARALLEL_SCSI(un) &&
7715 		    (devp->sd_inq->inq_rdf == RDF_SCSI2) &&
7716 		    (devp->sd_inq->inq_wbus16 || devp->sd_inq->inq_wbus32)) {
7717 			if (scsi_ifsetcap(SD_ADDRESS(un), "wide-xfer",
7718 			    1, 1) == 1) {
7719 				SD_INFO(SD_LOG_ATTACH_DETACH, un,
7720 				    "sd_unit_attach: un:0x%p Wide Transfer "
7721 				    "enabled\n", un);
7722 			}
7723 
7724 			/*
7725 			 * If tagged queuing has also been enabled, then
7726 			 * enable large xfers
7727 			 */
7728 			if (un->un_saved_throttle == sd_max_throttle) {
7729 				un->un_max_xfer_size =
7730 				    ddi_getprop(DDI_DEV_T_ANY, devi, 0,
7731 				    sd_max_xfer_size, SD_MAX_XFER_SIZE);
7732 				SD_INFO(SD_LOG_ATTACH_DETACH, un,
7733 				    "sd_unit_attach: un:0x%p max transfer "
7734 				    "size=0x%x\n", un, un->un_max_xfer_size);
7735 			}
7736 		} else {
7737 			if (scsi_ifsetcap(SD_ADDRESS(un), "wide-xfer",
7738 			    0, 1) == 1) {
7739 				SD_INFO(SD_LOG_ATTACH_DETACH, un,
7740 				    "sd_unit_attach: un:0x%p "
7741 				    "Wide Transfer disabled\n", un);
7742 			}
7743 		}
7744 	} else {
7745 		un->un_tagflags = FLAG_STAG;
7746 		un->un_max_xfer_size = ddi_getprop(DDI_DEV_T_ANY,
7747 		    devi, 0, sd_max_xfer_size, SD_MAX_XFER_SIZE);
7748 	}
7749 
7750 	/*
7751 	 * If this target supports LUN reset, try to enable it.
7752 	 */
7753 	if (un->un_f_lun_reset_enabled) {
7754 		if (scsi_ifsetcap(SD_ADDRESS(un), "lun-reset", 1, 1) == 1) {
7755 			SD_INFO(SD_LOG_ATTACH_DETACH, un, "sd_unit_attach: "
7756 			    "un:0x%p lun_reset capability set\n", un);
7757 		} else {
7758 			SD_INFO(SD_LOG_ATTACH_DETACH, un, "sd_unit_attach: "
7759 			    "un:0x%p lun-reset capability not set\n", un);
7760 		}
7761 	}
7762 
7763 	/*
7764 	 * Adjust the maximum transfer size. This is to fix
7765 	 * the problem of partial DMA support on SPARC. Some
7766 	 * HBA driver, like aac, has very small dma_attr_maxxfer
7767 	 * size, which requires partial DMA support on SPARC.
7768 	 * In the future the SPARC pci nexus driver may solve
7769 	 * the problem instead of this fix.
7770 	 */
7771 	max_xfer_size = scsi_ifgetcap(SD_ADDRESS(un), "dma-max", 1);
7772 	if ((max_xfer_size > 0) && (max_xfer_size < un->un_max_xfer_size)) {
7773 		/* We need DMA partial even on sparc to ensure sddump() works */
7774 		un->un_max_xfer_size = max_xfer_size;
7775 		if (un->un_partial_dma_supported == 0)
7776 			un->un_partial_dma_supported = 1;
7777 	}
7778 	if (ddi_prop_get_int(DDI_DEV_T_ANY, SD_DEVINFO(un),
7779 	    DDI_PROP_DONTPASS, "buf_break", 0) == 1) {
7780 		if (ddi_xbuf_attr_setup_brk(un->un_xbuf_attr,
7781 		    un->un_max_xfer_size) == 1) {
7782 			un->un_buf_breakup_supported = 1;
7783 			SD_INFO(SD_LOG_ATTACH_DETACH, un, "sd_unit_attach: "
7784 			    "un:0x%p Buf breakup enabled\n", un);
7785 		}
7786 	}
7787 
7788 	/*
7789 	 * Set PKT_DMA_PARTIAL flag.
7790 	 */
7791 	if (un->un_partial_dma_supported == 1) {
7792 		un->un_pkt_flags = PKT_DMA_PARTIAL;
7793 	} else {
7794 		un->un_pkt_flags = 0;
7795 	}
7796 
7797 	/* Initialize sd_ssc_t for internal uscsi commands */
7798 	ssc = sd_ssc_init(un);
7799 	scsi_fm_init(devp);
7800 
7801 	/*
7802 	 * Allocate memory for SCSI FMA stuffs.
7803 	 */
7804 	un->un_fm_private =
7805 	    kmem_zalloc(sizeof (struct sd_fm_internal), KM_SLEEP);
7806 	sfip = (struct sd_fm_internal *)un->un_fm_private;
7807 	sfip->fm_ssc.ssc_uscsi_cmd = &sfip->fm_ucmd;
7808 	sfip->fm_ssc.ssc_uscsi_info = &sfip->fm_uinfo;
7809 	sfip->fm_ssc.ssc_un = un;
7810 
7811 	if (ISCD(un) ||
7812 	    un->un_f_has_removable_media ||
7813 	    devp->sd_fm_capable == DDI_FM_NOT_CAPABLE) {
7814 		/*
7815 		 * We don't touch CDROM or the DDI_FM_NOT_CAPABLE device.
7816 		 * Their log are unchanged.
7817 		 */
7818 		sfip->fm_log_level = SD_FM_LOG_NSUP;
7819 	} else {
7820 		/*
7821 		 * If enter here, it should be non-CDROM and FM-capable
7822 		 * device, and it will not keep the old scsi_log as before
7823 		 * in /var/adm/messages. However, the property
7824 		 * "fm-scsi-log" will control whether the FM telemetry will
7825 		 * be logged in /var/adm/messages.
7826 		 */
7827 		int fm_scsi_log;
7828 		fm_scsi_log = ddi_prop_get_int(DDI_DEV_T_ANY, SD_DEVINFO(un),
7829 		    DDI_PROP_DONTPASS | DDI_PROP_NOTPROM, "fm-scsi-log", 0);
7830 
7831 		if (fm_scsi_log)
7832 			sfip->fm_log_level = SD_FM_LOG_EREPORT;
7833 		else
7834 			sfip->fm_log_level = SD_FM_LOG_SILENT;
7835 	}
7836 
7837 	/*
7838 	 * At this point in the attach, we have enough info in the
7839 	 * soft state to be able to issue commands to the target.
7840 	 *
7841 	 * All command paths used below MUST issue their commands as
7842 	 * SD_PATH_DIRECT. This is important as intermediate layers
7843 	 * are not all initialized yet (such as PM).
7844 	 */
7845 
7846 	/*
7847 	 * Send a TEST UNIT READY command to the device. This should clear
7848 	 * any outstanding UNIT ATTENTION that may be present.
7849 	 *
7850 	 * Note: Don't check for success, just track if there is a reservation,
7851 	 * this is a throw away command to clear any unit attentions.
7852 	 *
7853 	 * Note: This MUST be the first command issued to the target during
7854 	 * attach to ensure power on UNIT ATTENTIONS are cleared.
7855 	 * Pass in flag SD_DONT_RETRY_TUR to prevent the long delays associated
7856 	 * with attempts at spinning up a device with no media.
7857 	 */
7858 	status = sd_send_scsi_TEST_UNIT_READY(ssc, SD_DONT_RETRY_TUR);
7859 	if (status != 0) {
7860 		if (status == EACCES)
7861 			reservation_flag = SD_TARGET_IS_RESERVED;
7862 		sd_ssc_assessment(ssc, SD_FMT_IGNORE);
7863 	}
7864 
7865 	/*
7866 	 * If the device is NOT a removable media device, attempt to spin
7867 	 * it up (using the START_STOP_UNIT command) and read its capacity
7868 	 * (using the READ CAPACITY command).  Note, however, that either
7869 	 * of these could fail and in some cases we would continue with
7870 	 * the attach despite the failure (see below).
7871 	 */
7872 	if (un->un_f_descr_format_supported) {
7873 
7874 		switch (sd_spin_up_unit(ssc)) {
7875 		case 0:
7876 			/*
7877 			 * Spin-up was successful; now try to read the
7878 			 * capacity.  If successful then save the results
7879 			 * and mark the capacity & lbasize as valid.
7880 			 */
7881 			SD_TRACE(SD_LOG_ATTACH_DETACH, un,
7882 			    "sd_unit_attach: un:0x%p spin-up successful\n", un);
7883 
7884 			status = sd_send_scsi_READ_CAPACITY(ssc, &capacity,
7885 			    &lbasize, SD_PATH_DIRECT);
7886 
7887 			switch (status) {
7888 			case 0: {
7889 				if (capacity > DK_MAX_BLOCKS) {
7890 #ifdef _LP64
7891 					if ((capacity + 1) >
7892 					    SD_GROUP1_MAX_ADDRESS) {
7893 						/*
7894 						 * Enable descriptor format
7895 						 * sense data so that we can
7896 						 * get 64 bit sense data
7897 						 * fields.
7898 						 */
7899 						sd_enable_descr_sense(ssc);
7900 					}
7901 #else
7902 					/* 32-bit kernels can't handle this */
7903 					scsi_log(SD_DEVINFO(un),
7904 					    sd_label, CE_WARN,
7905 					    "disk has %llu blocks, which "
7906 					    "is too large for a 32-bit "
7907 					    "kernel", capacity);
7908 
7909 #if defined(__i386) || defined(__amd64)
7910 					/*
7911 					 * 1TB disk was treated as (1T - 512)B
7912 					 * in the past, so that it might have
7913 					 * valid VTOC and solaris partitions,
7914 					 * we have to allow it to continue to
7915 					 * work.
7916 					 */
7917 					if (capacity -1 > DK_MAX_BLOCKS)
7918 #endif
7919 					goto spinup_failed;
7920 #endif
7921 				}
7922 
7923 				/*
7924 				 * Here it's not necessary to check the case:
7925 				 * the capacity of the device is bigger than
7926 				 * what the max hba cdb can support. Because
7927 				 * sd_send_scsi_READ_CAPACITY will retrieve
7928 				 * the capacity by sending USCSI command, which
7929 				 * is constrained by the max hba cdb. Actually,
7930 				 * sd_send_scsi_READ_CAPACITY will return
7931 				 * EINVAL when using bigger cdb than required
7932 				 * cdb length. Will handle this case in
7933 				 * "case EINVAL".
7934 				 */
7935 
7936 				/*
7937 				 * The following relies on
7938 				 * sd_send_scsi_READ_CAPACITY never
7939 				 * returning 0 for capacity and/or lbasize.
7940 				 */
7941 				sd_update_block_info(un, lbasize, capacity);
7942 
7943 				SD_INFO(SD_LOG_ATTACH_DETACH, un,
7944 				    "sd_unit_attach: un:0x%p capacity = %ld "
7945 				    "blocks; lbasize= %ld.\n", un,
7946 				    un->un_blockcount, un->un_tgt_blocksize);
7947 
7948 				break;
7949 			}
7950 			case EINVAL:
7951 				/*
7952 				 * In the case where the max-cdb-length property
7953 				 * is smaller than the required CDB length for
7954 				 * a SCSI device, a target driver can fail to
7955 				 * attach to that device.
7956 				 */
7957 				scsi_log(SD_DEVINFO(un),
7958 				    sd_label, CE_WARN,
7959 				    "disk capacity is too large "
7960 				    "for current cdb length");
7961 				sd_ssc_assessment(ssc, SD_FMT_IGNORE);
7962 
7963 				goto spinup_failed;
7964 			case EACCES:
7965 				/*
7966 				 * Should never get here if the spin-up
7967 				 * succeeded, but code it in anyway.
7968 				 * From here, just continue with the attach...
7969 				 */
7970 				SD_INFO(SD_LOG_ATTACH_DETACH, un,
7971 				    "sd_unit_attach: un:0x%p "
7972 				    "sd_send_scsi_READ_CAPACITY "
7973 				    "returned reservation conflict\n", un);
7974 				reservation_flag = SD_TARGET_IS_RESERVED;
7975 				sd_ssc_assessment(ssc, SD_FMT_IGNORE);
7976 				break;
7977 			default:
7978 				/*
7979 				 * Likewise, should never get here if the
7980 				 * spin-up succeeded. Just continue with
7981 				 * the attach...
7982 				 */
7983 				if (status == EIO)
7984 					sd_ssc_assessment(ssc,
7985 					    SD_FMT_STATUS_CHECK);
7986 				else
7987 					sd_ssc_assessment(ssc,
7988 					    SD_FMT_IGNORE);
7989 				break;
7990 			}
7991 			break;
7992 		case EACCES:
7993 			/*
7994 			 * Device is reserved by another host.  In this case
7995 			 * we could not spin it up or read the capacity, but
7996 			 * we continue with the attach anyway.
7997 			 */
7998 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
7999 			    "sd_unit_attach: un:0x%p spin-up reservation "
8000 			    "conflict.\n", un);
8001 			reservation_flag = SD_TARGET_IS_RESERVED;
8002 			break;
8003 		default:
8004 			/* Fail the attach if the spin-up failed. */
8005 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
8006 			    "sd_unit_attach: un:0x%p spin-up failed.", un);
8007 			goto spinup_failed;
8008 		}
8009 
8010 	}
8011 
8012 	/*
8013 	 * Check to see if this is a MMC drive
8014 	 */
8015 	if (ISCD(un)) {
8016 		sd_set_mmc_caps(ssc);
8017 	}
8018 
8019 
8020 	/*
8021 	 * Add a zero-length attribute to tell the world we support
8022 	 * kernel ioctls (for layered drivers)
8023 	 */
8024 	(void) ddi_prop_create(DDI_DEV_T_NONE, devi, DDI_PROP_CANSLEEP,
8025 	    DDI_KERNEL_IOCTL, NULL, 0);
8026 
8027 	/*
8028 	 * Add a boolean property to tell the world we support
8029 	 * the B_FAILFAST flag (for layered drivers)
8030 	 */
8031 	(void) ddi_prop_create(DDI_DEV_T_NONE, devi, DDI_PROP_CANSLEEP,
8032 	    "ddi-failfast-supported", NULL, 0);
8033 
8034 	/*
8035 	 * Initialize power management
8036 	 */
8037 	mutex_init(&un->un_pm_mutex, NULL, MUTEX_DRIVER, NULL);
8038 	cv_init(&un->un_pm_busy_cv, NULL, CV_DRIVER, NULL);
8039 	sd_setup_pm(ssc, devi);
8040 	if (un->un_f_pm_is_enabled == FALSE) {
8041 		/*
8042 		 * For performance, point to a jump table that does
8043 		 * not include pm.
8044 		 * The direct and priority chains don't change with PM.
8045 		 *
8046 		 * Note: this is currently done based on individual device
8047 		 * capabilities. When an interface for determining system
8048 		 * power enabled state becomes available, or when additional
8049 		 * layers are added to the command chain, these values will
8050 		 * have to be re-evaluated for correctness.
8051 		 */
8052 		if (un->un_f_non_devbsize_supported) {
8053 			un->un_buf_chain_type = SD_CHAIN_INFO_RMMEDIA_NO_PM;
8054 		} else {
8055 			un->un_buf_chain_type = SD_CHAIN_INFO_DISK_NO_PM;
8056 		}
8057 		un->un_uscsi_chain_type  = SD_CHAIN_INFO_USCSI_CMD_NO_PM;
8058 	}
8059 
8060 	/*
8061 	 * This property is set to 0 by HA software to avoid retries
8062 	 * on a reserved disk. (The preferred property name is
8063 	 * "retry-on-reservation-conflict") (1189689)
8064 	 *
8065 	 * Note: The use of a global here can have unintended consequences. A
8066 	 * per instance variable is preferable to match the capabilities of
8067 	 * different underlying hba's (4402600)
8068 	 */
8069 	sd_retry_on_reservation_conflict = ddi_getprop(DDI_DEV_T_ANY, devi,
8070 	    DDI_PROP_DONTPASS, "retry-on-reservation-conflict",
8071 	    sd_retry_on_reservation_conflict);
8072 	if (sd_retry_on_reservation_conflict != 0) {
8073 		sd_retry_on_reservation_conflict = ddi_getprop(DDI_DEV_T_ANY,
8074 		    devi, DDI_PROP_DONTPASS, sd_resv_conflict_name,
8075 		    sd_retry_on_reservation_conflict);
8076 	}
8077 
8078 	/* Set up options for QFULL handling. */
8079 	if ((rval = ddi_getprop(DDI_DEV_T_ANY, devi, 0,
8080 	    "qfull-retries", -1)) != -1) {
8081 		(void) scsi_ifsetcap(SD_ADDRESS(un), "qfull-retries",
8082 		    rval, 1);
8083 	}
8084 	if ((rval = ddi_getprop(DDI_DEV_T_ANY, devi, 0,
8085 	    "qfull-retry-interval", -1)) != -1) {
8086 		(void) scsi_ifsetcap(SD_ADDRESS(un), "qfull-retry-interval",
8087 		    rval, 1);
8088 	}
8089 
8090 	/*
8091 	 * This just prints a message that announces the existence of the
8092 	 * device. The message is always printed in the system logfile, but
8093 	 * only appears on the console if the system is booted with the
8094 	 * -v (verbose) argument.
8095 	 */
8096 	ddi_report_dev(devi);
8097 
8098 	un->un_mediastate = DKIO_NONE;
8099 
8100 	/*
8101 	 * Check if this is a SSD(Solid State Drive).
8102 	 */
8103 	sd_check_solid_state(ssc);
8104 
8105 	cmlb_alloc_handle(&un->un_cmlbhandle);
8106 
8107 #if defined(__i386) || defined(__amd64)
8108 	/*
8109 	 * On x86, compensate for off-by-1 legacy error
8110 	 */
8111 	if (!un->un_f_has_removable_media && !un->un_f_is_hotpluggable &&
8112 	    (lbasize == un->un_sys_blocksize))
8113 		offbyone = CMLB_OFF_BY_ONE;
8114 #endif
8115 
8116 	if (cmlb_attach(devi, &sd_tgops, (int)devp->sd_inq->inq_dtype,
8117 	    VOID2BOOLEAN(un->un_f_has_removable_media != 0),
8118 	    VOID2BOOLEAN(un->un_f_is_hotpluggable != 0),
8119 	    un->un_node_type, offbyone, un->un_cmlbhandle,
8120 	    (void *)SD_PATH_DIRECT) != 0) {
8121 		goto cmlb_attach_failed;
8122 	}
8123 
8124 
8125 	/*
8126 	 * Read and validate the device's geometry (ie, disk label)
8127 	 * A new unformatted drive will not have a valid geometry, but
8128 	 * the driver needs to successfully attach to this device so
8129 	 * the drive can be formatted via ioctls.
8130 	 */
8131 	geom_label_valid = (cmlb_validate(un->un_cmlbhandle, 0,
8132 	    (void *)SD_PATH_DIRECT) == 0) ? 1: 0;
8133 
8134 	mutex_enter(SD_MUTEX(un));
8135 
8136 	/*
8137 	 * Read and initialize the devid for the unit.
8138 	 */
8139 	if (un->un_f_devid_supported) {
8140 		sd_register_devid(ssc, devi, reservation_flag);
8141 	}
8142 	mutex_exit(SD_MUTEX(un));
8143 
8144 #if (defined(__fibre))
8145 	/*
8146 	 * Register callbacks for fibre only.  You can't do this solely
8147 	 * on the basis of the devid_type because this is hba specific.
8148 	 * We need to query our hba capabilities to find out whether to
8149 	 * register or not.
8150 	 */
8151 	if (un->un_f_is_fibre) {
8152 		if (strcmp(un->un_node_type, DDI_NT_BLOCK_CHAN)) {
8153 			sd_init_event_callbacks(un);
8154 			SD_TRACE(SD_LOG_ATTACH_DETACH, un,
8155 			    "sd_unit_attach: un:0x%p event callbacks inserted",
8156 			    un);
8157 		}
8158 	}
8159 #endif
8160 
8161 	if (un->un_f_opt_disable_cache == TRUE) {
8162 		/*
8163 		 * Disable both read cache and write cache.  This is
8164 		 * the historic behavior of the keywords in the config file.
8165 		 */
8166 		if (sd_cache_control(ssc, SD_CACHE_DISABLE, SD_CACHE_DISABLE) !=
8167 		    0) {
8168 			SD_ERROR(SD_LOG_ATTACH_DETACH, un,
8169 			    "sd_unit_attach: un:0x%p Could not disable "
8170 			    "caching", un);
8171 			goto devid_failed;
8172 		}
8173 	}
8174 
8175 	/*
8176 	 * Check the value of the WCE bit now and
8177 	 * set un_f_write_cache_enabled accordingly.
8178 	 */
8179 	(void) sd_get_write_cache_enabled(ssc, &wc_enabled);
8180 	mutex_enter(SD_MUTEX(un));
8181 	un->un_f_write_cache_enabled = (wc_enabled != 0);
8182 	mutex_exit(SD_MUTEX(un));
8183 
8184 	if (un->un_f_rmw_type != SD_RMW_TYPE_RETURN_ERROR &&
8185 	    un->un_tgt_blocksize != DEV_BSIZE) {
8186 		if (!(un->un_wm_cache)) {
8187 			(void) snprintf(name_str, sizeof (name_str),
8188 			    "%s%d_cache",
8189 			    ddi_driver_name(SD_DEVINFO(un)),
8190 			    ddi_get_instance(SD_DEVINFO(un)));
8191 			un->un_wm_cache = kmem_cache_create(
8192 			    name_str, sizeof (struct sd_w_map),
8193 			    8, sd_wm_cache_constructor,
8194 			    sd_wm_cache_destructor, NULL,
8195 			    (void *)un, NULL, 0);
8196 			if (!(un->un_wm_cache)) {
8197 				goto wm_cache_failed;
8198 			}
8199 		}
8200 	}
8201 
8202 	/*
8203 	 * Check the value of the NV_SUP bit and set
8204 	 * un_f_suppress_cache_flush accordingly.
8205 	 */
8206 	sd_get_nv_sup(ssc);
8207 
8208 	/*
8209 	 * Find out what type of reservation this disk supports.
8210 	 */
8211 	status = sd_send_scsi_PERSISTENT_RESERVE_IN(ssc, SD_READ_KEYS, 0, NULL);
8212 
8213 	switch (status) {
8214 	case 0:
8215 		/*
8216 		 * SCSI-3 reservations are supported.
8217 		 */
8218 		un->un_reservation_type = SD_SCSI3_RESERVATION;
8219 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
8220 		    "sd_unit_attach: un:0x%p SCSI-3 reservations\n", un);
8221 		break;
8222 	case ENOTSUP:
8223 		/*
8224 		 * The PERSISTENT RESERVE IN command would not be recognized by
8225 		 * a SCSI-2 device, so assume the reservation type is SCSI-2.
8226 		 */
8227 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
8228 		    "sd_unit_attach: un:0x%p SCSI-2 reservations\n", un);
8229 		un->un_reservation_type = SD_SCSI2_RESERVATION;
8230 
8231 		sd_ssc_assessment(ssc, SD_FMT_IGNORE);
8232 		break;
8233 	default:
8234 		/*
8235 		 * default to SCSI-3 reservations
8236 		 */
8237 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
8238 		    "sd_unit_attach: un:0x%p default SCSI3 reservations\n", un);
8239 		un->un_reservation_type = SD_SCSI3_RESERVATION;
8240 
8241 		sd_ssc_assessment(ssc, SD_FMT_IGNORE);
8242 		break;
8243 	}
8244 
8245 	/*
8246 	 * Set the pstat and error stat values here, so data obtained during the
8247 	 * previous attach-time routines is available.
8248 	 *
8249 	 * Note: This is a critical sequence that needs to be maintained:
8250 	 *	1) Instantiate the kstats before any routines using the iopath
8251 	 *	   (i.e. sd_send_scsi_cmd).
8252 	 *	2) Initialize the error stats (sd_set_errstats) and partition
8253 	 *	   stats (sd_set_pstats)here, following
8254 	 *	   cmlb_validate_geometry(), sd_register_devid(), and
8255 	 *	   sd_cache_control().
8256 	 */
8257 
8258 	if (un->un_f_pkstats_enabled && geom_label_valid) {
8259 		sd_set_pstats(un);
8260 		SD_TRACE(SD_LOG_IO_PARTITION, un,
8261 		    "sd_unit_attach: un:0x%p pstats created and set\n", un);
8262 	}
8263 
8264 	sd_set_errstats(un);
8265 	SD_TRACE(SD_LOG_ATTACH_DETACH, un,
8266 	    "sd_unit_attach: un:0x%p errstats set\n", un);
8267 
8268 
8269 	/*
8270 	 * After successfully attaching an instance, we record the information
8271 	 * of how many luns have been attached on the relative target and
8272 	 * controller for parallel SCSI. This information is used when sd tries
8273 	 * to set the tagged queuing capability in HBA.
8274 	 */
8275 	if (SD_IS_PARALLEL_SCSI(un) && (tgt >= 0) && (tgt < NTARGETS_WIDE)) {
8276 		sd_scsi_update_lun_on_target(pdip, tgt, SD_SCSI_LUN_ATTACH);
8277 	}
8278 
8279 	SD_TRACE(SD_LOG_ATTACH_DETACH, un,
8280 	    "sd_unit_attach: un:0x%p exit success\n", un);
8281 
8282 	/* Uninitialize sd_ssc_t pointer */
8283 	sd_ssc_fini(ssc);
8284 
8285 	return (DDI_SUCCESS);
8286 
8287 	/*
8288 	 * An error occurred during the attach; clean up & return failure.
8289 	 */
8290 wm_cache_failed:
8291 devid_failed:
8292 
8293 setup_pm_failed:
8294 	ddi_remove_minor_node(devi, NULL);
8295 
8296 cmlb_attach_failed:
8297 	/*
8298 	 * Cleanup from the scsi_ifsetcap() calls (437868)
8299 	 */
8300 	(void) scsi_ifsetcap(SD_ADDRESS(un), "lun-reset", 0, 1);
8301 	(void) scsi_ifsetcap(SD_ADDRESS(un), "wide-xfer", 0, 1);
8302 
8303 	/*
8304 	 * Refer to the comments of setting tagged-qing in the beginning of
8305 	 * sd_unit_attach. We can only disable tagged queuing when there is
8306 	 * no lun attached on the target.
8307 	 */
8308 	if (sd_scsi_get_target_lun_count(pdip, tgt) < 1) {
8309 		(void) scsi_ifsetcap(SD_ADDRESS(un), "tagged-qing", 0, 1);
8310 	}
8311 
8312 	if (un->un_f_is_fibre == FALSE) {
8313 		(void) scsi_ifsetcap(SD_ADDRESS(un), "auto-rqsense", 0, 1);
8314 	}
8315 
8316 spinup_failed:
8317 
8318 	/* Uninitialize sd_ssc_t pointer */
8319 	sd_ssc_fini(ssc);
8320 
8321 	mutex_enter(SD_MUTEX(un));
8322 
8323 	/* Deallocate SCSI FMA memory spaces */
8324 	kmem_free(un->un_fm_private, sizeof (struct sd_fm_internal));
8325 
8326 	/* Cancel callback for SD_PATH_DIRECT_PRIORITY cmd. restart */
8327 	if (un->un_direct_priority_timeid != NULL) {
8328 		timeout_id_t temp_id = un->un_direct_priority_timeid;
8329 		un->un_direct_priority_timeid = NULL;
8330 		mutex_exit(SD_MUTEX(un));
8331 		(void) untimeout(temp_id);
8332 		mutex_enter(SD_MUTEX(un));
8333 	}
8334 
8335 	/* Cancel any pending start/stop timeouts */
8336 	if (un->un_startstop_timeid != NULL) {
8337 		timeout_id_t temp_id = un->un_startstop_timeid;
8338 		un->un_startstop_timeid = NULL;
8339 		mutex_exit(SD_MUTEX(un));
8340 		(void) untimeout(temp_id);
8341 		mutex_enter(SD_MUTEX(un));
8342 	}
8343 
8344 	/* Cancel any pending reset-throttle timeouts */
8345 	if (un->un_reset_throttle_timeid != NULL) {
8346 		timeout_id_t temp_id = un->un_reset_throttle_timeid;
8347 		un->un_reset_throttle_timeid = NULL;
8348 		mutex_exit(SD_MUTEX(un));
8349 		(void) untimeout(temp_id);
8350 		mutex_enter(SD_MUTEX(un));
8351 	}
8352 
8353 	/* Cancel rmw warning message timeouts */
8354 	if (un->un_rmw_msg_timeid != NULL) {
8355 		timeout_id_t temp_id = un->un_rmw_msg_timeid;
8356 		un->un_rmw_msg_timeid = NULL;
8357 		mutex_exit(SD_MUTEX(un));
8358 		(void) untimeout(temp_id);
8359 		mutex_enter(SD_MUTEX(un));
8360 	}
8361 
8362 	/* Cancel any pending retry timeouts */
8363 	if (un->un_retry_timeid != NULL) {
8364 		timeout_id_t temp_id = un->un_retry_timeid;
8365 		un->un_retry_timeid = NULL;
8366 		mutex_exit(SD_MUTEX(un));
8367 		(void) untimeout(temp_id);
8368 		mutex_enter(SD_MUTEX(un));
8369 	}
8370 
8371 	/* Cancel any pending delayed cv broadcast timeouts */
8372 	if (un->un_dcvb_timeid != NULL) {
8373 		timeout_id_t temp_id = un->un_dcvb_timeid;
8374 		un->un_dcvb_timeid = NULL;
8375 		mutex_exit(SD_MUTEX(un));
8376 		(void) untimeout(temp_id);
8377 		mutex_enter(SD_MUTEX(un));
8378 	}
8379 
8380 	mutex_exit(SD_MUTEX(un));
8381 
8382 	/* There should not be any in-progress I/O so ASSERT this check */
8383 	ASSERT(un->un_ncmds_in_transport == 0);
8384 	ASSERT(un->un_ncmds_in_driver == 0);
8385 
8386 	/* Do not free the softstate if the callback routine is active */
8387 	sd_sync_with_callback(un);
8388 
8389 	/*
8390 	 * Partition stats apparently are not used with removables. These would
8391 	 * not have been created during attach, so no need to clean them up...
8392 	 */
8393 	if (un->un_errstats != NULL) {
8394 		kstat_delete(un->un_errstats);
8395 		un->un_errstats = NULL;
8396 	}
8397 
8398 create_errstats_failed:
8399 
8400 	if (un->un_stats != NULL) {
8401 		kstat_delete(un->un_stats);
8402 		un->un_stats = NULL;
8403 	}
8404 
8405 	ddi_xbuf_attr_unregister_devinfo(un->un_xbuf_attr, devi);
8406 	ddi_xbuf_attr_destroy(un->un_xbuf_attr);
8407 
8408 	ddi_prop_remove_all(devi);
8409 	sema_destroy(&un->un_semoclose);
8410 	cv_destroy(&un->un_state_cv);
8411 
8412 getrbuf_failed:
8413 
8414 	sd_free_rqs(un);
8415 
8416 alloc_rqs_failed:
8417 
8418 	devp->sd_private = NULL;
8419 	bzero(un, sizeof (struct sd_lun));	/* Clear any stale data! */
8420 
8421 get_softstate_failed:
8422 	/*
8423 	 * Note: the man pages are unclear as to whether or not doing a
8424 	 * ddi_soft_state_free(sd_state, instance) is the right way to
8425 	 * clean up after the ddi_soft_state_zalloc() if the subsequent
8426 	 * ddi_get_soft_state() fails.  The implication seems to be
8427 	 * that the get_soft_state cannot fail if the zalloc succeeds.
8428 	 */
8429 #ifndef XPV_HVM_DRIVER
8430 	ddi_soft_state_free(sd_state, instance);
8431 #endif /* !XPV_HVM_DRIVER */
8432 
8433 probe_failed:
8434 	scsi_unprobe(devp);
8435 
8436 	return (DDI_FAILURE);
8437 }
8438 
8439 
8440 /*
8441  *    Function: sd_unit_detach
8442  *
8443  * Description: Performs DDI_DETACH processing for sddetach().
8444  *
8445  * Return Code: DDI_SUCCESS
8446  *		DDI_FAILURE
8447  *
8448  *     Context: Kernel thread context
8449  */
8450 
8451 static int
8452 sd_unit_detach(dev_info_t *devi)
8453 {
8454 	struct scsi_device	*devp;
8455 	struct sd_lun		*un;
8456 	int			i;
8457 	int			tgt;
8458 	dev_t			dev;
8459 	dev_info_t		*pdip = ddi_get_parent(devi);
8460 #ifndef XPV_HVM_DRIVER
8461 	int			instance = ddi_get_instance(devi);
8462 #endif /* !XPV_HVM_DRIVER */
8463 
8464 	mutex_enter(&sd_detach_mutex);
8465 
8466 	/*
8467 	 * Fail the detach for any of the following:
8468 	 *  - Unable to get the sd_lun struct for the instance
8469 	 *  - A layered driver has an outstanding open on the instance
8470 	 *  - Another thread is already detaching this instance
8471 	 *  - Another thread is currently performing an open
8472 	 */
8473 	devp = ddi_get_driver_private(devi);
8474 	if ((devp == NULL) ||
8475 	    ((un = (struct sd_lun *)devp->sd_private) == NULL) ||
8476 	    (un->un_ncmds_in_driver != 0) || (un->un_layer_count != 0) ||
8477 	    (un->un_detach_count != 0) || (un->un_opens_in_progress != 0)) {
8478 		mutex_exit(&sd_detach_mutex);
8479 		return (DDI_FAILURE);
8480 	}
8481 
8482 	SD_TRACE(SD_LOG_ATTACH_DETACH, un, "sd_unit_detach: entry 0x%p\n", un);
8483 
8484 	/*
8485 	 * Mark this instance as currently in a detach, to inhibit any
8486 	 * opens from a layered driver.
8487 	 */
8488 	un->un_detach_count++;
8489 	mutex_exit(&sd_detach_mutex);
8490 
8491 	tgt = ddi_prop_get_int(DDI_DEV_T_ANY, devi, DDI_PROP_DONTPASS,
8492 	    SCSI_ADDR_PROP_TARGET, -1);
8493 
8494 	dev = sd_make_device(SD_DEVINFO(un));
8495 
8496 #ifndef lint
8497 	_NOTE(COMPETING_THREADS_NOW);
8498 #endif
8499 
8500 	mutex_enter(SD_MUTEX(un));
8501 
8502 	/*
8503 	 * Fail the detach if there are any outstanding layered
8504 	 * opens on this device.
8505 	 */
8506 	for (i = 0; i < NDKMAP; i++) {
8507 		if (un->un_ocmap.lyropen[i] != 0) {
8508 			goto err_notclosed;
8509 		}
8510 	}
8511 
8512 	/*
8513 	 * Verify there are NO outstanding commands issued to this device.
8514 	 * ie, un_ncmds_in_transport == 0.
8515 	 * It's possible to have outstanding commands through the physio
8516 	 * code path, even though everything's closed.
8517 	 */
8518 	if ((un->un_ncmds_in_transport != 0) || (un->un_retry_timeid != NULL) ||
8519 	    (un->un_direct_priority_timeid != NULL) ||
8520 	    (un->un_state == SD_STATE_RWAIT)) {
8521 		mutex_exit(SD_MUTEX(un));
8522 		SD_ERROR(SD_LOG_ATTACH_DETACH, un,
8523 		    "sd_dr_detach: Detach failure due to outstanding cmds\n");
8524 		goto err_stillbusy;
8525 	}
8526 
8527 	/*
8528 	 * If we have the device reserved, release the reservation.
8529 	 */
8530 	if ((un->un_resvd_status & SD_RESERVE) &&
8531 	    !(un->un_resvd_status & SD_LOST_RESERVE)) {
8532 		mutex_exit(SD_MUTEX(un));
8533 		/*
8534 		 * Note: sd_reserve_release sends a command to the device
8535 		 * via the sd_ioctlcmd() path, and can sleep.
8536 		 */
8537 		if (sd_reserve_release(dev, SD_RELEASE) != 0) {
8538 			SD_ERROR(SD_LOG_ATTACH_DETACH, un,
8539 			    "sd_dr_detach: Cannot release reservation \n");
8540 		}
8541 	} else {
8542 		mutex_exit(SD_MUTEX(un));
8543 	}
8544 
8545 	/*
8546 	 * Untimeout any reserve recover, throttle reset, restart unit
8547 	 * and delayed broadcast timeout threads. Protect the timeout pointer
8548 	 * from getting nulled by their callback functions.
8549 	 */
8550 	mutex_enter(SD_MUTEX(un));
8551 	if (un->un_resvd_timeid != NULL) {
8552 		timeout_id_t temp_id = un->un_resvd_timeid;
8553 		un->un_resvd_timeid = NULL;
8554 		mutex_exit(SD_MUTEX(un));
8555 		(void) untimeout(temp_id);
8556 		mutex_enter(SD_MUTEX(un));
8557 	}
8558 
8559 	if (un->un_reset_throttle_timeid != NULL) {
8560 		timeout_id_t temp_id = un->un_reset_throttle_timeid;
8561 		un->un_reset_throttle_timeid = NULL;
8562 		mutex_exit(SD_MUTEX(un));
8563 		(void) untimeout(temp_id);
8564 		mutex_enter(SD_MUTEX(un));
8565 	}
8566 
8567 	if (un->un_startstop_timeid != NULL) {
8568 		timeout_id_t temp_id = un->un_startstop_timeid;
8569 		un->un_startstop_timeid = NULL;
8570 		mutex_exit(SD_MUTEX(un));
8571 		(void) untimeout(temp_id);
8572 		mutex_enter(SD_MUTEX(un));
8573 	}
8574 
8575 	if (un->un_rmw_msg_timeid != NULL) {
8576 		timeout_id_t temp_id = un->un_rmw_msg_timeid;
8577 		un->un_rmw_msg_timeid = NULL;
8578 		mutex_exit(SD_MUTEX(un));
8579 		(void) untimeout(temp_id);
8580 		mutex_enter(SD_MUTEX(un));
8581 	}
8582 
8583 	if (un->un_dcvb_timeid != NULL) {
8584 		timeout_id_t temp_id = un->un_dcvb_timeid;
8585 		un->un_dcvb_timeid = NULL;
8586 		mutex_exit(SD_MUTEX(un));
8587 		(void) untimeout(temp_id);
8588 	} else {
8589 		mutex_exit(SD_MUTEX(un));
8590 	}
8591 
8592 	/* Remove any pending reservation reclaim requests for this device */
8593 	sd_rmv_resv_reclaim_req(dev);
8594 
8595 	mutex_enter(SD_MUTEX(un));
8596 
8597 	/* Cancel any pending callbacks for SD_PATH_DIRECT_PRIORITY cmd. */
8598 	if (un->un_direct_priority_timeid != NULL) {
8599 		timeout_id_t temp_id = un->un_direct_priority_timeid;
8600 		un->un_direct_priority_timeid = NULL;
8601 		mutex_exit(SD_MUTEX(un));
8602 		(void) untimeout(temp_id);
8603 		mutex_enter(SD_MUTEX(un));
8604 	}
8605 
8606 	/* Cancel any active multi-host disk watch thread requests */
8607 	if (un->un_mhd_token != NULL) {
8608 		mutex_exit(SD_MUTEX(un));
8609 		 _NOTE(DATA_READABLE_WITHOUT_LOCK(sd_lun::un_mhd_token));
8610 		if (scsi_watch_request_terminate(un->un_mhd_token,
8611 		    SCSI_WATCH_TERMINATE_NOWAIT)) {
8612 			SD_ERROR(SD_LOG_ATTACH_DETACH, un,
8613 			    "sd_dr_detach: Cannot cancel mhd watch request\n");
8614 			/*
8615 			 * Note: We are returning here after having removed
8616 			 * some driver timeouts above. This is consistent with
8617 			 * the legacy implementation but perhaps the watch
8618 			 * terminate call should be made with the wait flag set.
8619 			 */
8620 			goto err_stillbusy;
8621 		}
8622 		mutex_enter(SD_MUTEX(un));
8623 		un->un_mhd_token = NULL;
8624 	}
8625 
8626 	if (un->un_swr_token != NULL) {
8627 		mutex_exit(SD_MUTEX(un));
8628 		_NOTE(DATA_READABLE_WITHOUT_LOCK(sd_lun::un_swr_token));
8629 		if (scsi_watch_request_terminate(un->un_swr_token,
8630 		    SCSI_WATCH_TERMINATE_NOWAIT)) {
8631 			SD_ERROR(SD_LOG_ATTACH_DETACH, un,
8632 			    "sd_dr_detach: Cannot cancel swr watch request\n");
8633 			/*
8634 			 * Note: We are returning here after having removed
8635 			 * some driver timeouts above. This is consistent with
8636 			 * the legacy implementation but perhaps the watch
8637 			 * terminate call should be made with the wait flag set.
8638 			 */
8639 			goto err_stillbusy;
8640 		}
8641 		mutex_enter(SD_MUTEX(un));
8642 		un->un_swr_token = NULL;
8643 	}
8644 
8645 	mutex_exit(SD_MUTEX(un));
8646 
8647 	/*
8648 	 * Clear any scsi_reset_notifies. We clear the reset notifies
8649 	 * if we have not registered one.
8650 	 * Note: The sd_mhd_reset_notify_cb() fn tries to acquire SD_MUTEX!
8651 	 */
8652 	(void) scsi_reset_notify(SD_ADDRESS(un), SCSI_RESET_CANCEL,
8653 	    sd_mhd_reset_notify_cb, (caddr_t)un);
8654 
8655 	/*
8656 	 * protect the timeout pointers from getting nulled by
8657 	 * their callback functions during the cancellation process.
8658 	 * In such a scenario untimeout can be invoked with a null value.
8659 	 */
8660 	_NOTE(NO_COMPETING_THREADS_NOW);
8661 
8662 	mutex_enter(&un->un_pm_mutex);
8663 	if (un->un_pm_idle_timeid != NULL) {
8664 		timeout_id_t temp_id = un->un_pm_idle_timeid;
8665 		un->un_pm_idle_timeid = NULL;
8666 		mutex_exit(&un->un_pm_mutex);
8667 
8668 		/*
8669 		 * Timeout is active; cancel it.
8670 		 * Note that it'll never be active on a device
8671 		 * that does not support PM therefore we don't
8672 		 * have to check before calling pm_idle_component.
8673 		 */
8674 		(void) untimeout(temp_id);
8675 		(void) pm_idle_component(SD_DEVINFO(un), 0);
8676 		mutex_enter(&un->un_pm_mutex);
8677 	}
8678 
8679 	/*
8680 	 * Check whether there is already a timeout scheduled for power
8681 	 * management. If yes then don't lower the power here, that's.
8682 	 * the timeout handler's job.
8683 	 */
8684 	if (un->un_pm_timeid != NULL) {
8685 		timeout_id_t temp_id = un->un_pm_timeid;
8686 		un->un_pm_timeid = NULL;
8687 		mutex_exit(&un->un_pm_mutex);
8688 		/*
8689 		 * Timeout is active; cancel it.
8690 		 * Note that it'll never be active on a device
8691 		 * that does not support PM therefore we don't
8692 		 * have to check before calling pm_idle_component.
8693 		 */
8694 		(void) untimeout(temp_id);
8695 		(void) pm_idle_component(SD_DEVINFO(un), 0);
8696 
8697 	} else {
8698 		mutex_exit(&un->un_pm_mutex);
8699 		if ((un->un_f_pm_is_enabled == TRUE) &&
8700 		    (pm_lower_power(SD_DEVINFO(un), 0, SD_PM_STATE_STOPPED(un))
8701 		    != DDI_SUCCESS)) {
8702 			SD_ERROR(SD_LOG_ATTACH_DETACH, un,
8703 		    "sd_dr_detach: Lower power request failed, ignoring.\n");
8704 			/*
8705 			 * Fix for bug: 4297749, item # 13
8706 			 * The above test now includes a check to see if PM is
8707 			 * supported by this device before call
8708 			 * pm_lower_power().
8709 			 * Note, the following is not dead code. The call to
8710 			 * pm_lower_power above will generate a call back into
8711 			 * our sdpower routine which might result in a timeout
8712 			 * handler getting activated. Therefore the following
8713 			 * code is valid and necessary.
8714 			 */
8715 			mutex_enter(&un->un_pm_mutex);
8716 			if (un->un_pm_timeid != NULL) {
8717 				timeout_id_t temp_id = un->un_pm_timeid;
8718 				un->un_pm_timeid = NULL;
8719 				mutex_exit(&un->un_pm_mutex);
8720 				(void) untimeout(temp_id);
8721 				(void) pm_idle_component(SD_DEVINFO(un), 0);
8722 			} else {
8723 				mutex_exit(&un->un_pm_mutex);
8724 			}
8725 		}
8726 	}
8727 
8728 	/*
8729 	 * Cleanup from the scsi_ifsetcap() calls (437868)
8730 	 * Relocated here from above to be after the call to
8731 	 * pm_lower_power, which was getting errors.
8732 	 */
8733 	(void) scsi_ifsetcap(SD_ADDRESS(un), "lun-reset", 0, 1);
8734 	(void) scsi_ifsetcap(SD_ADDRESS(un), "wide-xfer", 0, 1);
8735 
8736 	/*
8737 	 * Currently, tagged queuing is supported per target based by HBA.
8738 	 * Setting this per lun instance actually sets the capability of this
8739 	 * target in HBA, which affects those luns already attached on the
8740 	 * same target. So during detach, we can only disable this capability
8741 	 * only when this is the only lun left on this target. By doing
8742 	 * this, we assume a target has the same tagged queuing capability
8743 	 * for every lun. The condition can be removed when HBA is changed to
8744 	 * support per lun based tagged queuing capability.
8745 	 */
8746 	if (sd_scsi_get_target_lun_count(pdip, tgt) <= 1) {
8747 		(void) scsi_ifsetcap(SD_ADDRESS(un), "tagged-qing", 0, 1);
8748 	}
8749 
8750 	if (un->un_f_is_fibre == FALSE) {
8751 		(void) scsi_ifsetcap(SD_ADDRESS(un), "auto-rqsense", 0, 1);
8752 	}
8753 
8754 	/*
8755 	 * Remove any event callbacks, fibre only
8756 	 */
8757 	if (un->un_f_is_fibre == TRUE) {
8758 		if ((un->un_insert_event != NULL) &&
8759 		    (ddi_remove_event_handler(un->un_insert_cb_id) !=
8760 		    DDI_SUCCESS)) {
8761 			/*
8762 			 * Note: We are returning here after having done
8763 			 * substantial cleanup above. This is consistent
8764 			 * with the legacy implementation but this may not
8765 			 * be the right thing to do.
8766 			 */
8767 			SD_ERROR(SD_LOG_ATTACH_DETACH, un,
8768 			    "sd_dr_detach: Cannot cancel insert event\n");
8769 			goto err_remove_event;
8770 		}
8771 		un->un_insert_event = NULL;
8772 
8773 		if ((un->un_remove_event != NULL) &&
8774 		    (ddi_remove_event_handler(un->un_remove_cb_id) !=
8775 		    DDI_SUCCESS)) {
8776 			/*
8777 			 * Note: We are returning here after having done
8778 			 * substantial cleanup above. This is consistent
8779 			 * with the legacy implementation but this may not
8780 			 * be the right thing to do.
8781 			 */
8782 			SD_ERROR(SD_LOG_ATTACH_DETACH, un,
8783 			    "sd_dr_detach: Cannot cancel remove event\n");
8784 			goto err_remove_event;
8785 		}
8786 		un->un_remove_event = NULL;
8787 	}
8788 
8789 	/* Do not free the softstate if the callback routine is active */
8790 	sd_sync_with_callback(un);
8791 
8792 	cmlb_detach(un->un_cmlbhandle, (void *)SD_PATH_DIRECT);
8793 	cmlb_free_handle(&un->un_cmlbhandle);
8794 
8795 	/*
8796 	 * Hold the detach mutex here, to make sure that no other threads ever
8797 	 * can access a (partially) freed soft state structure.
8798 	 */
8799 	mutex_enter(&sd_detach_mutex);
8800 
8801 	/*
8802 	 * Clean up the soft state struct.
8803 	 * Cleanup is done in reverse order of allocs/inits.
8804 	 * At this point there should be no competing threads anymore.
8805 	 */
8806 
8807 	scsi_fm_fini(devp);
8808 
8809 	/*
8810 	 * Deallocate memory for SCSI FMA.
8811 	 */
8812 	kmem_free(un->un_fm_private, sizeof (struct sd_fm_internal));
8813 
8814 	/*
8815 	 * Unregister and free device id if it was not registered
8816 	 * by the transport.
8817 	 */
8818 	if (un->un_f_devid_transport_defined == FALSE)
8819 		ddi_devid_unregister(devi);
8820 
8821 	/*
8822 	 * free the devid structure if allocated before (by ddi_devid_init()
8823 	 * or ddi_devid_get()).
8824 	 */
8825 	if (un->un_devid) {
8826 		ddi_devid_free(un->un_devid);
8827 		un->un_devid = NULL;
8828 	}
8829 
8830 	/*
8831 	 * Destroy wmap cache if it exists.
8832 	 */
8833 	if (un->un_wm_cache != NULL) {
8834 		kmem_cache_destroy(un->un_wm_cache);
8835 		un->un_wm_cache = NULL;
8836 	}
8837 
8838 	/*
8839 	 * kstat cleanup is done in detach for all device types (4363169).
8840 	 * We do not want to fail detach if the device kstats are not deleted
8841 	 * since there is a confusion about the devo_refcnt for the device.
8842 	 * We just delete the kstats and let detach complete successfully.
8843 	 */
8844 	if (un->un_stats != NULL) {
8845 		kstat_delete(un->un_stats);
8846 		un->un_stats = NULL;
8847 	}
8848 	if (un->un_errstats != NULL) {
8849 		kstat_delete(un->un_errstats);
8850 		un->un_errstats = NULL;
8851 	}
8852 
8853 	/* Remove partition stats */
8854 	if (un->un_f_pkstats_enabled) {
8855 		for (i = 0; i < NSDMAP; i++) {
8856 			if (un->un_pstats[i] != NULL) {
8857 				kstat_delete(un->un_pstats[i]);
8858 				un->un_pstats[i] = NULL;
8859 			}
8860 		}
8861 	}
8862 
8863 	/* Remove xbuf registration */
8864 	ddi_xbuf_attr_unregister_devinfo(un->un_xbuf_attr, devi);
8865 	ddi_xbuf_attr_destroy(un->un_xbuf_attr);
8866 
8867 	/* Remove driver properties */
8868 	ddi_prop_remove_all(devi);
8869 
8870 	mutex_destroy(&un->un_pm_mutex);
8871 	cv_destroy(&un->un_pm_busy_cv);
8872 
8873 	cv_destroy(&un->un_wcc_cv);
8874 
8875 	/* Open/close semaphore */
8876 	sema_destroy(&un->un_semoclose);
8877 
8878 	/* Removable media condvar. */
8879 	cv_destroy(&un->un_state_cv);
8880 
8881 	/* Suspend/resume condvar. */
8882 	cv_destroy(&un->un_suspend_cv);
8883 	cv_destroy(&un->un_disk_busy_cv);
8884 
8885 	sd_free_rqs(un);
8886 
8887 	/* Free up soft state */
8888 	devp->sd_private = NULL;
8889 
8890 	bzero(un, sizeof (struct sd_lun));
8891 #ifndef XPV_HVM_DRIVER
8892 	ddi_soft_state_free(sd_state, instance);
8893 #endif /* !XPV_HVM_DRIVER */
8894 
8895 	mutex_exit(&sd_detach_mutex);
8896 
8897 	/* This frees up the INQUIRY data associated with the device. */
8898 	scsi_unprobe(devp);
8899 
8900 	/*
8901 	 * After successfully detaching an instance, we update the information
8902 	 * of how many luns have been attached in the relative target and
8903 	 * controller for parallel SCSI. This information is used when sd tries
8904 	 * to set the tagged queuing capability in HBA.
8905 	 * Since un has been released, we can't use SD_IS_PARALLEL_SCSI(un) to
8906 	 * check if the device is parallel SCSI. However, we don't need to
8907 	 * check here because we've already checked during attach. No device
8908 	 * that is not parallel SCSI is in the chain.
8909 	 */
8910 	if ((tgt >= 0) && (tgt < NTARGETS_WIDE)) {
8911 		sd_scsi_update_lun_on_target(pdip, tgt, SD_SCSI_LUN_DETACH);
8912 	}
8913 
8914 	return (DDI_SUCCESS);
8915 
8916 err_notclosed:
8917 	mutex_exit(SD_MUTEX(un));
8918 
8919 err_stillbusy:
8920 	_NOTE(NO_COMPETING_THREADS_NOW);
8921 
8922 err_remove_event:
8923 	mutex_enter(&sd_detach_mutex);
8924 	un->un_detach_count--;
8925 	mutex_exit(&sd_detach_mutex);
8926 
8927 	SD_TRACE(SD_LOG_ATTACH_DETACH, un, "sd_unit_detach: exit failure\n");
8928 	return (DDI_FAILURE);
8929 }
8930 
8931 
8932 /*
8933  *    Function: sd_create_errstats
8934  *
8935  * Description: This routine instantiates the device error stats.
8936  *
8937  *		Note: During attach the stats are instantiated first so they are
8938  *		available for attach-time routines that utilize the driver
8939  *		iopath to send commands to the device. The stats are initialized
8940  *		separately so data obtained during some attach-time routines is
8941  *		available. (4362483)
8942  *
8943  *   Arguments: un - driver soft state (unit) structure
8944  *		instance - driver instance
8945  *
8946  *     Context: Kernel thread context
8947  */
8948 
8949 static void
8950 sd_create_errstats(struct sd_lun *un, int instance)
8951 {
8952 	struct	sd_errstats	*stp;
8953 	char	kstatmodule_err[KSTAT_STRLEN];
8954 	char	kstatname[KSTAT_STRLEN];
8955 	int	ndata = (sizeof (struct sd_errstats) / sizeof (kstat_named_t));
8956 
8957 	ASSERT(un != NULL);
8958 
8959 	if (un->un_errstats != NULL) {
8960 		return;
8961 	}
8962 
8963 	(void) snprintf(kstatmodule_err, sizeof (kstatmodule_err),
8964 	    "%serr", sd_label);
8965 	(void) snprintf(kstatname, sizeof (kstatname),
8966 	    "%s%d,err", sd_label, instance);
8967 
8968 	un->un_errstats = kstat_create(kstatmodule_err, instance, kstatname,
8969 	    "device_error", KSTAT_TYPE_NAMED, ndata, KSTAT_FLAG_PERSISTENT);
8970 
8971 	if (un->un_errstats == NULL) {
8972 		SD_ERROR(SD_LOG_ATTACH_DETACH, un,
8973 		    "sd_create_errstats: Failed kstat_create\n");
8974 		return;
8975 	}
8976 
8977 	stp = (struct sd_errstats *)un->un_errstats->ks_data;
8978 	kstat_named_init(&stp->sd_softerrs,	"Soft Errors",
8979 	    KSTAT_DATA_UINT32);
8980 	kstat_named_init(&stp->sd_harderrs,	"Hard Errors",
8981 	    KSTAT_DATA_UINT32);
8982 	kstat_named_init(&stp->sd_transerrs,	"Transport Errors",
8983 	    KSTAT_DATA_UINT32);
8984 	kstat_named_init(&stp->sd_vid,		"Vendor",
8985 	    KSTAT_DATA_CHAR);
8986 	kstat_named_init(&stp->sd_pid,		"Product",
8987 	    KSTAT_DATA_CHAR);
8988 	kstat_named_init(&stp->sd_revision,	"Revision",
8989 	    KSTAT_DATA_CHAR);
8990 	kstat_named_init(&stp->sd_serial,	"Serial No",
8991 	    KSTAT_DATA_CHAR);
8992 	kstat_named_init(&stp->sd_capacity,	"Size",
8993 	    KSTAT_DATA_ULONGLONG);
8994 	kstat_named_init(&stp->sd_rq_media_err,	"Media Error",
8995 	    KSTAT_DATA_UINT32);
8996 	kstat_named_init(&stp->sd_rq_ntrdy_err,	"Device Not Ready",
8997 	    KSTAT_DATA_UINT32);
8998 	kstat_named_init(&stp->sd_rq_nodev_err,	"No Device",
8999 	    KSTAT_DATA_UINT32);
9000 	kstat_named_init(&stp->sd_rq_recov_err,	"Recoverable",
9001 	    KSTAT_DATA_UINT32);
9002 	kstat_named_init(&stp->sd_rq_illrq_err,	"Illegal Request",
9003 	    KSTAT_DATA_UINT32);
9004 	kstat_named_init(&stp->sd_rq_pfa_err,	"Predictive Failure Analysis",
9005 	    KSTAT_DATA_UINT32);
9006 
9007 	un->un_errstats->ks_private = un;
9008 	un->un_errstats->ks_update  = nulldev;
9009 
9010 	kstat_install(un->un_errstats);
9011 }
9012 
9013 
9014 /*
9015  *    Function: sd_set_errstats
9016  *
9017  * Description: This routine sets the value of the vendor id, product id,
9018  *		revision, serial number, and capacity device error stats.
9019  *
9020  *		Note: During attach the stats are instantiated first so they are
9021  *		available for attach-time routines that utilize the driver
9022  *		iopath to send commands to the device. The stats are initialized
9023  *		separately so data obtained during some attach-time routines is
9024  *		available. (4362483)
9025  *
9026  *   Arguments: un - driver soft state (unit) structure
9027  *
9028  *     Context: Kernel thread context
9029  */
9030 
9031 static void
9032 sd_set_errstats(struct sd_lun *un)
9033 {
9034 	struct	sd_errstats	*stp;
9035 
9036 	ASSERT(un != NULL);
9037 	ASSERT(un->un_errstats != NULL);
9038 	stp = (struct sd_errstats *)un->un_errstats->ks_data;
9039 	ASSERT(stp != NULL);
9040 	(void) strncpy(stp->sd_vid.value.c, un->un_sd->sd_inq->inq_vid, 8);
9041 	(void) strncpy(stp->sd_pid.value.c, un->un_sd->sd_inq->inq_pid, 16);
9042 	(void) strncpy(stp->sd_revision.value.c,
9043 	    un->un_sd->sd_inq->inq_revision, 4);
9044 
9045 	/*
9046 	 * All the errstats are persistent across detach/attach,
9047 	 * so reset all the errstats here in case of the hot
9048 	 * replacement of disk drives, except for not changed
9049 	 * Sun qualified drives.
9050 	 */
9051 	if ((bcmp(&SD_INQUIRY(un)->inq_pid[9], "SUN", 3) != 0) ||
9052 	    (bcmp(&SD_INQUIRY(un)->inq_serial, stp->sd_serial.value.c,
9053 	    sizeof (SD_INQUIRY(un)->inq_serial)) != 0)) {
9054 		stp->sd_softerrs.value.ui32 = 0;
9055 		stp->sd_harderrs.value.ui32 = 0;
9056 		stp->sd_transerrs.value.ui32 = 0;
9057 		stp->sd_rq_media_err.value.ui32 = 0;
9058 		stp->sd_rq_ntrdy_err.value.ui32 = 0;
9059 		stp->sd_rq_nodev_err.value.ui32 = 0;
9060 		stp->sd_rq_recov_err.value.ui32 = 0;
9061 		stp->sd_rq_illrq_err.value.ui32 = 0;
9062 		stp->sd_rq_pfa_err.value.ui32 = 0;
9063 	}
9064 
9065 	/*
9066 	 * Set the "Serial No" kstat for Sun qualified drives (indicated by
9067 	 * "SUN" in bytes 25-27 of the inquiry data (bytes 9-11 of the pid)
9068 	 * (4376302))
9069 	 */
9070 	if (bcmp(&SD_INQUIRY(un)->inq_pid[9], "SUN", 3) == 0) {
9071 		bcopy(&SD_INQUIRY(un)->inq_serial, stp->sd_serial.value.c,
9072 		    sizeof (SD_INQUIRY(un)->inq_serial));
9073 	}
9074 
9075 	if (un->un_f_blockcount_is_valid != TRUE) {
9076 		/*
9077 		 * Set capacity error stat to 0 for no media. This ensures
9078 		 * a valid capacity is displayed in response to 'iostat -E'
9079 		 * when no media is present in the device.
9080 		 */
9081 		stp->sd_capacity.value.ui64 = 0;
9082 	} else {
9083 		/*
9084 		 * Multiply un_blockcount by un->un_sys_blocksize to get
9085 		 * capacity.
9086 		 *
9087 		 * Note: for non-512 blocksize devices "un_blockcount" has been
9088 		 * "scaled" in sd_send_scsi_READ_CAPACITY by multiplying by
9089 		 * (un_tgt_blocksize / un->un_sys_blocksize).
9090 		 */
9091 		stp->sd_capacity.value.ui64 = (uint64_t)
9092 		    ((uint64_t)un->un_blockcount * un->un_sys_blocksize);
9093 	}
9094 }
9095 
9096 
9097 /*
9098  *    Function: sd_set_pstats
9099  *
9100  * Description: This routine instantiates and initializes the partition
9101  *              stats for each partition with more than zero blocks.
9102  *		(4363169)
9103  *
9104  *   Arguments: un - driver soft state (unit) structure
9105  *
9106  *     Context: Kernel thread context
9107  */
9108 
9109 static void
9110 sd_set_pstats(struct sd_lun *un)
9111 {
9112 	char	kstatname[KSTAT_STRLEN];
9113 	int	instance;
9114 	int	i;
9115 	diskaddr_t	nblks = 0;
9116 	char	*partname = NULL;
9117 
9118 	ASSERT(un != NULL);
9119 
9120 	instance = ddi_get_instance(SD_DEVINFO(un));
9121 
9122 	/* Note:x86: is this a VTOC8/VTOC16 difference? */
9123 	for (i = 0; i < NSDMAP; i++) {
9124 
9125 		if (cmlb_partinfo(un->un_cmlbhandle, i,
9126 		    &nblks, NULL, &partname, NULL, (void *)SD_PATH_DIRECT) != 0)
9127 			continue;
9128 		mutex_enter(SD_MUTEX(un));
9129 
9130 		if ((un->un_pstats[i] == NULL) &&
9131 		    (nblks != 0)) {
9132 
9133 			(void) snprintf(kstatname, sizeof (kstatname),
9134 			    "%s%d,%s", sd_label, instance,
9135 			    partname);
9136 
9137 			un->un_pstats[i] = kstat_create(sd_label,
9138 			    instance, kstatname, "partition", KSTAT_TYPE_IO,
9139 			    1, KSTAT_FLAG_PERSISTENT);
9140 			if (un->un_pstats[i] != NULL) {
9141 				un->un_pstats[i]->ks_lock = SD_MUTEX(un);
9142 				kstat_install(un->un_pstats[i]);
9143 			}
9144 		}
9145 		mutex_exit(SD_MUTEX(un));
9146 	}
9147 }
9148 
9149 
9150 #if (defined(__fibre))
9151 /*
9152  *    Function: sd_init_event_callbacks
9153  *
9154  * Description: This routine initializes the insertion and removal event
9155  *		callbacks. (fibre only)
9156  *
9157  *   Arguments: un - driver soft state (unit) structure
9158  *
9159  *     Context: Kernel thread context
9160  */
9161 
9162 static void
9163 sd_init_event_callbacks(struct sd_lun *un)
9164 {
9165 	ASSERT(un != NULL);
9166 
9167 	if ((un->un_insert_event == NULL) &&
9168 	    (ddi_get_eventcookie(SD_DEVINFO(un), FCAL_INSERT_EVENT,
9169 	    &un->un_insert_event) == DDI_SUCCESS)) {
9170 		/*
9171 		 * Add the callback for an insertion event
9172 		 */
9173 		(void) ddi_add_event_handler(SD_DEVINFO(un),
9174 		    un->un_insert_event, sd_event_callback, (void *)un,
9175 		    &(un->un_insert_cb_id));
9176 	}
9177 
9178 	if ((un->un_remove_event == NULL) &&
9179 	    (ddi_get_eventcookie(SD_DEVINFO(un), FCAL_REMOVE_EVENT,
9180 	    &un->un_remove_event) == DDI_SUCCESS)) {
9181 		/*
9182 		 * Add the callback for a removal event
9183 		 */
9184 		(void) ddi_add_event_handler(SD_DEVINFO(un),
9185 		    un->un_remove_event, sd_event_callback, (void *)un,
9186 		    &(un->un_remove_cb_id));
9187 	}
9188 }
9189 
9190 
9191 /*
9192  *    Function: sd_event_callback
9193  *
9194  * Description: This routine handles insert/remove events (photon). The
9195  *		state is changed to OFFLINE which can be used to supress
9196  *		error msgs. (fibre only)
9197  *
9198  *   Arguments: un - driver soft state (unit) structure
9199  *
9200  *     Context: Callout thread context
9201  */
9202 /* ARGSUSED */
9203 static void
9204 sd_event_callback(dev_info_t *dip, ddi_eventcookie_t event, void *arg,
9205     void *bus_impldata)
9206 {
9207 	struct sd_lun *un = (struct sd_lun *)arg;
9208 
9209 	_NOTE(DATA_READABLE_WITHOUT_LOCK(sd_lun::un_insert_event));
9210 	if (event == un->un_insert_event) {
9211 		SD_TRACE(SD_LOG_COMMON, un, "sd_event_callback: insert event");
9212 		mutex_enter(SD_MUTEX(un));
9213 		if (un->un_state == SD_STATE_OFFLINE) {
9214 			if (un->un_last_state != SD_STATE_SUSPENDED) {
9215 				un->un_state = un->un_last_state;
9216 			} else {
9217 				/*
9218 				 * We have gone through SUSPEND/RESUME while
9219 				 * we were offline. Restore the last state
9220 				 */
9221 				un->un_state = un->un_save_state;
9222 			}
9223 		}
9224 		mutex_exit(SD_MUTEX(un));
9225 
9226 	_NOTE(DATA_READABLE_WITHOUT_LOCK(sd_lun::un_remove_event));
9227 	} else if (event == un->un_remove_event) {
9228 		SD_TRACE(SD_LOG_COMMON, un, "sd_event_callback: remove event");
9229 		mutex_enter(SD_MUTEX(un));
9230 		/*
9231 		 * We need to handle an event callback that occurs during
9232 		 * the suspend operation, since we don't prevent it.
9233 		 */
9234 		if (un->un_state != SD_STATE_OFFLINE) {
9235 			if (un->un_state != SD_STATE_SUSPENDED) {
9236 				New_state(un, SD_STATE_OFFLINE);
9237 			} else {
9238 				un->un_last_state = SD_STATE_OFFLINE;
9239 			}
9240 		}
9241 		mutex_exit(SD_MUTEX(un));
9242 	} else {
9243 		scsi_log(SD_DEVINFO(un), sd_label, CE_NOTE,
9244 		    "!Unknown event\n");
9245 	}
9246 
9247 }
9248 #endif
9249 
9250 /*
9251  *    Function: sd_cache_control()
9252  *
9253  * Description: This routine is the driver entry point for setting
9254  *		read and write caching by modifying the WCE (write cache
9255  *		enable) and RCD (read cache disable) bits of mode
9256  *		page 8 (MODEPAGE_CACHING).
9257  *
9258  *   Arguments: ssc   - ssc contains pointer to driver soft state (unit)
9259  *                      structure for this target.
9260  *		rcd_flag - flag for controlling the read cache
9261  *		wce_flag - flag for controlling the write cache
9262  *
9263  * Return Code: EIO
9264  *		code returned by sd_send_scsi_MODE_SENSE and
9265  *		sd_send_scsi_MODE_SELECT
9266  *
9267  *     Context: Kernel Thread
9268  */
9269 
9270 static int
9271 sd_cache_control(sd_ssc_t *ssc, int rcd_flag, int wce_flag)
9272 {
9273 	struct mode_caching	*mode_caching_page;
9274 	uchar_t			*header;
9275 	size_t			buflen;
9276 	int			hdrlen;
9277 	int			bd_len;
9278 	int			rval = 0;
9279 	struct mode_header_grp2	*mhp;
9280 	struct sd_lun		*un;
9281 	int			status;
9282 
9283 	ASSERT(ssc != NULL);
9284 	un = ssc->ssc_un;
9285 	ASSERT(un != NULL);
9286 
9287 	/*
9288 	 * Do a test unit ready, otherwise a mode sense may not work if this
9289 	 * is the first command sent to the device after boot.
9290 	 */
9291 	status = sd_send_scsi_TEST_UNIT_READY(ssc, 0);
9292 	if (status != 0)
9293 		sd_ssc_assessment(ssc, SD_FMT_IGNORE);
9294 
9295 	if (un->un_f_cfg_is_atapi == TRUE) {
9296 		hdrlen = MODE_HEADER_LENGTH_GRP2;
9297 	} else {
9298 		hdrlen = MODE_HEADER_LENGTH;
9299 	}
9300 
9301 	/*
9302 	 * Allocate memory for the retrieved mode page and its headers.  Set
9303 	 * a pointer to the page itself.  Use mode_cache_scsi3 to insure
9304 	 * we get all of the mode sense data otherwise, the mode select
9305 	 * will fail.  mode_cache_scsi3 is a superset of mode_caching.
9306 	 */
9307 	buflen = hdrlen + MODE_BLK_DESC_LENGTH +
9308 	    sizeof (struct mode_cache_scsi3);
9309 
9310 	header = kmem_zalloc(buflen, KM_SLEEP);
9311 
9312 	/* Get the information from the device. */
9313 	if (un->un_f_cfg_is_atapi == TRUE) {
9314 		rval = sd_send_scsi_MODE_SENSE(ssc, CDB_GROUP1, header, buflen,
9315 		    MODEPAGE_CACHING, SD_PATH_DIRECT);
9316 	} else {
9317 		rval = sd_send_scsi_MODE_SENSE(ssc, CDB_GROUP0, header, buflen,
9318 		    MODEPAGE_CACHING, SD_PATH_DIRECT);
9319 	}
9320 
9321 	if (rval != 0) {
9322 		SD_ERROR(SD_LOG_IOCTL_RMMEDIA, un,
9323 		    "sd_cache_control: Mode Sense Failed\n");
9324 		goto mode_sense_failed;
9325 	}
9326 
9327 	/*
9328 	 * Determine size of Block Descriptors in order to locate
9329 	 * the mode page data. ATAPI devices return 0, SCSI devices
9330 	 * should return MODE_BLK_DESC_LENGTH.
9331 	 */
9332 	if (un->un_f_cfg_is_atapi == TRUE) {
9333 		mhp	= (struct mode_header_grp2 *)header;
9334 		bd_len  = (mhp->bdesc_length_hi << 8) | mhp->bdesc_length_lo;
9335 	} else {
9336 		bd_len  = ((struct mode_header *)header)->bdesc_length;
9337 	}
9338 
9339 	if (bd_len > MODE_BLK_DESC_LENGTH) {
9340 		sd_ssc_set_info(ssc, SSC_FLAGS_INVALID_DATA, 0,
9341 		    "sd_cache_control: Mode Sense returned invalid block "
9342 		    "descriptor length\n");
9343 		rval = EIO;
9344 		goto mode_sense_failed;
9345 	}
9346 
9347 	mode_caching_page = (struct mode_caching *)(header + hdrlen + bd_len);
9348 	if (mode_caching_page->mode_page.code != MODEPAGE_CACHING) {
9349 		sd_ssc_set_info(ssc, SSC_FLAGS_INVALID_DATA, SD_LOG_COMMON,
9350 		    "sd_cache_control: Mode Sense caching page code mismatch "
9351 		    "%d\n", mode_caching_page->mode_page.code);
9352 		rval = EIO;
9353 		goto mode_sense_failed;
9354 	}
9355 
9356 	/* Check the relevant bits on successful mode sense. */
9357 	if ((mode_caching_page->rcd && rcd_flag == SD_CACHE_ENABLE) ||
9358 	    (!mode_caching_page->rcd && rcd_flag == SD_CACHE_DISABLE) ||
9359 	    (mode_caching_page->wce && wce_flag == SD_CACHE_DISABLE) ||
9360 	    (!mode_caching_page->wce && wce_flag == SD_CACHE_ENABLE)) {
9361 
9362 		size_t sbuflen;
9363 		uchar_t save_pg;
9364 
9365 		/*
9366 		 * Construct select buffer length based on the
9367 		 * length of the sense data returned.
9368 		 */
9369 		sbuflen =  hdrlen + bd_len +
9370 		    sizeof (struct mode_page) +
9371 		    (int)mode_caching_page->mode_page.length;
9372 
9373 		/*
9374 		 * Set the caching bits as requested.
9375 		 */
9376 		if (rcd_flag == SD_CACHE_ENABLE)
9377 			mode_caching_page->rcd = 0;
9378 		else if (rcd_flag == SD_CACHE_DISABLE)
9379 			mode_caching_page->rcd = 1;
9380 
9381 		if (wce_flag == SD_CACHE_ENABLE)
9382 			mode_caching_page->wce = 1;
9383 		else if (wce_flag == SD_CACHE_DISABLE)
9384 			mode_caching_page->wce = 0;
9385 
9386 		/*
9387 		 * Save the page if the mode sense says the
9388 		 * drive supports it.
9389 		 */
9390 		save_pg = mode_caching_page->mode_page.ps ?
9391 		    SD_SAVE_PAGE : SD_DONTSAVE_PAGE;
9392 
9393 		/* Clear reserved bits before mode select. */
9394 		mode_caching_page->mode_page.ps = 0;
9395 
9396 		/*
9397 		 * Clear out mode header for mode select.
9398 		 * The rest of the retrieved page will be reused.
9399 		 */
9400 		bzero(header, hdrlen);
9401 
9402 		if (un->un_f_cfg_is_atapi == TRUE) {
9403 			mhp = (struct mode_header_grp2 *)header;
9404 			mhp->bdesc_length_hi = bd_len >> 8;
9405 			mhp->bdesc_length_lo = (uchar_t)bd_len & 0xff;
9406 		} else {
9407 			((struct mode_header *)header)->bdesc_length = bd_len;
9408 		}
9409 
9410 		sd_ssc_assessment(ssc, SD_FMT_IGNORE);
9411 
9412 		/* Issue mode select to change the cache settings */
9413 		if (un->un_f_cfg_is_atapi == TRUE) {
9414 			rval = sd_send_scsi_MODE_SELECT(ssc, CDB_GROUP1, header,
9415 			    sbuflen, save_pg, SD_PATH_DIRECT);
9416 		} else {
9417 			rval = sd_send_scsi_MODE_SELECT(ssc, CDB_GROUP0, header,
9418 			    sbuflen, save_pg, SD_PATH_DIRECT);
9419 		}
9420 
9421 	}
9422 
9423 
9424 mode_sense_failed:
9425 
9426 	kmem_free(header, buflen);
9427 
9428 	if (rval != 0) {
9429 		if (rval == EIO)
9430 			sd_ssc_assessment(ssc, SD_FMT_STATUS_CHECK);
9431 		else
9432 			sd_ssc_assessment(ssc, SD_FMT_IGNORE);
9433 	}
9434 	return (rval);
9435 }
9436 
9437 
9438 /*
9439  *    Function: sd_get_write_cache_enabled()
9440  *
9441  * Description: This routine is the driver entry point for determining if
9442  *		write caching is enabled.  It examines the WCE (write cache
9443  *		enable) bits of mode page 8 (MODEPAGE_CACHING).
9444  *
9445  *   Arguments: ssc   - ssc contains pointer to driver soft state (unit)
9446  *                      structure for this target.
9447  *		is_enabled - pointer to int where write cache enabled state
9448  *		is returned (non-zero -> write cache enabled)
9449  *
9450  *
9451  * Return Code: EIO
9452  *		code returned by sd_send_scsi_MODE_SENSE
9453  *
9454  *     Context: Kernel Thread
9455  *
9456  * NOTE: If ioctl is added to disable write cache, this sequence should
9457  * be followed so that no locking is required for accesses to
9458  * un->un_f_write_cache_enabled:
9459  * 	do mode select to clear wce
9460  * 	do synchronize cache to flush cache
9461  * 	set un->un_f_write_cache_enabled = FALSE
9462  *
9463  * Conversely, an ioctl to enable the write cache should be done
9464  * in this order:
9465  * 	set un->un_f_write_cache_enabled = TRUE
9466  * 	do mode select to set wce
9467  */
9468 
9469 static int
9470 sd_get_write_cache_enabled(sd_ssc_t *ssc, int *is_enabled)
9471 {
9472 	struct mode_caching	*mode_caching_page;
9473 	uchar_t			*header;
9474 	size_t			buflen;
9475 	int			hdrlen;
9476 	int			bd_len;
9477 	int			rval = 0;
9478 	struct sd_lun		*un;
9479 	int			status;
9480 
9481 	ASSERT(ssc != NULL);
9482 	un = ssc->ssc_un;
9483 	ASSERT(un != NULL);
9484 	ASSERT(is_enabled != NULL);
9485 
9486 	/* in case of error, flag as enabled */
9487 	*is_enabled = TRUE;
9488 
9489 	/*
9490 	 * Do a test unit ready, otherwise a mode sense may not work if this
9491 	 * is the first command sent to the device after boot.
9492 	 */
9493 	status = sd_send_scsi_TEST_UNIT_READY(ssc, 0);
9494 
9495 	if (status != 0)
9496 		sd_ssc_assessment(ssc, SD_FMT_IGNORE);
9497 
9498 	if (un->un_f_cfg_is_atapi == TRUE) {
9499 		hdrlen = MODE_HEADER_LENGTH_GRP2;
9500 	} else {
9501 		hdrlen = MODE_HEADER_LENGTH;
9502 	}
9503 
9504 	/*
9505 	 * Allocate memory for the retrieved mode page and its headers.  Set
9506 	 * a pointer to the page itself.
9507 	 */
9508 	buflen = hdrlen + MODE_BLK_DESC_LENGTH + sizeof (struct mode_caching);
9509 	header = kmem_zalloc(buflen, KM_SLEEP);
9510 
9511 	/* Get the information from the device. */
9512 	if (un->un_f_cfg_is_atapi == TRUE) {
9513 		rval = sd_send_scsi_MODE_SENSE(ssc, CDB_GROUP1, header, buflen,
9514 		    MODEPAGE_CACHING, SD_PATH_DIRECT);
9515 	} else {
9516 		rval = sd_send_scsi_MODE_SENSE(ssc, CDB_GROUP0, header, buflen,
9517 		    MODEPAGE_CACHING, SD_PATH_DIRECT);
9518 	}
9519 
9520 	if (rval != 0) {
9521 		SD_ERROR(SD_LOG_IOCTL_RMMEDIA, un,
9522 		    "sd_get_write_cache_enabled: Mode Sense Failed\n");
9523 		goto mode_sense_failed;
9524 	}
9525 
9526 	/*
9527 	 * Determine size of Block Descriptors in order to locate
9528 	 * the mode page data. ATAPI devices return 0, SCSI devices
9529 	 * should return MODE_BLK_DESC_LENGTH.
9530 	 */
9531 	if (un->un_f_cfg_is_atapi == TRUE) {
9532 		struct mode_header_grp2	*mhp;
9533 		mhp	= (struct mode_header_grp2 *)header;
9534 		bd_len  = (mhp->bdesc_length_hi << 8) | mhp->bdesc_length_lo;
9535 	} else {
9536 		bd_len  = ((struct mode_header *)header)->bdesc_length;
9537 	}
9538 
9539 	if (bd_len > MODE_BLK_DESC_LENGTH) {
9540 		/* FMA should make upset complain here */
9541 		sd_ssc_set_info(ssc, SSC_FLAGS_INVALID_DATA, 0,
9542 		    "sd_get_write_cache_enabled: Mode Sense returned invalid "
9543 		    "block descriptor length\n");
9544 		rval = EIO;
9545 		goto mode_sense_failed;
9546 	}
9547 
9548 	mode_caching_page = (struct mode_caching *)(header + hdrlen + bd_len);
9549 	if (mode_caching_page->mode_page.code != MODEPAGE_CACHING) {
9550 		/* FMA could make upset complain here */
9551 		sd_ssc_set_info(ssc, SSC_FLAGS_INVALID_DATA, SD_LOG_COMMON,
9552 		    "sd_get_write_cache_enabled: Mode Sense caching page "
9553 		    "code mismatch %d\n", mode_caching_page->mode_page.code);
9554 		rval = EIO;
9555 		goto mode_sense_failed;
9556 	}
9557 	*is_enabled = mode_caching_page->wce;
9558 
9559 mode_sense_failed:
9560 	if (rval == 0) {
9561 		sd_ssc_assessment(ssc, SD_FMT_STANDARD);
9562 	} else if (rval == EIO) {
9563 		/*
9564 		 * Some disks do not support mode sense(6), we
9565 		 * should ignore this kind of error(sense key is
9566 		 * 0x5 - illegal request).
9567 		 */
9568 		uint8_t *sensep;
9569 		int senlen;
9570 
9571 		sensep = (uint8_t *)ssc->ssc_uscsi_cmd->uscsi_rqbuf;
9572 		senlen = (int)(ssc->ssc_uscsi_cmd->uscsi_rqlen -
9573 		    ssc->ssc_uscsi_cmd->uscsi_rqresid);
9574 
9575 		if (senlen > 0 &&
9576 		    scsi_sense_key(sensep) == KEY_ILLEGAL_REQUEST) {
9577 			sd_ssc_assessment(ssc, SD_FMT_IGNORE_COMPROMISE);
9578 		} else {
9579 			sd_ssc_assessment(ssc, SD_FMT_STATUS_CHECK);
9580 		}
9581 	} else {
9582 		sd_ssc_assessment(ssc, SD_FMT_IGNORE);
9583 	}
9584 	kmem_free(header, buflen);
9585 	return (rval);
9586 }
9587 
9588 /*
9589  *    Function: sd_get_nv_sup()
9590  *
9591  * Description: This routine is the driver entry point for
9592  * determining whether non-volatile cache is supported. This
9593  * determination process works as follows:
9594  *
9595  * 1. sd first queries sd.conf on whether
9596  * suppress_cache_flush bit is set for this device.
9597  *
9598  * 2. if not there, then queries the internal disk table.
9599  *
9600  * 3. if either sd.conf or internal disk table specifies
9601  * cache flush be suppressed, we don't bother checking
9602  * NV_SUP bit.
9603  *
9604  * If SUPPRESS_CACHE_FLUSH bit is not set to 1, sd queries
9605  * the optional INQUIRY VPD page 0x86. If the device
9606  * supports VPD page 0x86, sd examines the NV_SUP
9607  * (non-volatile cache support) bit in the INQUIRY VPD page
9608  * 0x86:
9609  *   o If NV_SUP bit is set, sd assumes the device has a
9610  *   non-volatile cache and set the
9611  *   un_f_sync_nv_supported to TRUE.
9612  *   o Otherwise cache is not non-volatile,
9613  *   un_f_sync_nv_supported is set to FALSE.
9614  *
9615  * Arguments: un - driver soft state (unit) structure
9616  *
9617  * Return Code:
9618  *
9619  *     Context: Kernel Thread
9620  */
9621 
9622 static void
9623 sd_get_nv_sup(sd_ssc_t *ssc)
9624 {
9625 	int		rval		= 0;
9626 	uchar_t		*inq86		= NULL;
9627 	size_t		inq86_len	= MAX_INQUIRY_SIZE;
9628 	size_t		inq86_resid	= 0;
9629 	struct		dk_callback *dkc;
9630 	struct sd_lun	*un;
9631 
9632 	ASSERT(ssc != NULL);
9633 	un = ssc->ssc_un;
9634 	ASSERT(un != NULL);
9635 
9636 	mutex_enter(SD_MUTEX(un));
9637 
9638 	/*
9639 	 * Be conservative on the device's support of
9640 	 * SYNC_NV bit: un_f_sync_nv_supported is
9641 	 * initialized to be false.
9642 	 */
9643 	un->un_f_sync_nv_supported = FALSE;
9644 
9645 	/*
9646 	 * If either sd.conf or internal disk table
9647 	 * specifies cache flush be suppressed, then
9648 	 * we don't bother checking NV_SUP bit.
9649 	 */
9650 	if (un->un_f_suppress_cache_flush == TRUE) {
9651 		mutex_exit(SD_MUTEX(un));
9652 		return;
9653 	}
9654 
9655 	if (sd_check_vpd_page_support(ssc) == 0 &&
9656 	    un->un_vpd_page_mask & SD_VPD_EXTENDED_DATA_PG) {
9657 		mutex_exit(SD_MUTEX(un));
9658 		/* collect page 86 data if available */
9659 		inq86 = kmem_zalloc(inq86_len, KM_SLEEP);
9660 
9661 		rval = sd_send_scsi_INQUIRY(ssc, inq86, inq86_len,
9662 		    0x01, 0x86, &inq86_resid);
9663 
9664 		if (rval == 0 && (inq86_len - inq86_resid > 6)) {
9665 			SD_TRACE(SD_LOG_COMMON, un,
9666 			    "sd_get_nv_sup: \
9667 			    successfully get VPD page: %x \
9668 			    PAGE LENGTH: %x BYTE 6: %x\n",
9669 			    inq86[1], inq86[3], inq86[6]);
9670 
9671 			mutex_enter(SD_MUTEX(un));
9672 			/*
9673 			 * check the value of NV_SUP bit: only if the device
9674 			 * reports NV_SUP bit to be 1, the
9675 			 * un_f_sync_nv_supported bit will be set to true.
9676 			 */
9677 			if (inq86[6] & SD_VPD_NV_SUP) {
9678 				un->un_f_sync_nv_supported = TRUE;
9679 			}
9680 			mutex_exit(SD_MUTEX(un));
9681 		} else if (rval != 0) {
9682 			sd_ssc_assessment(ssc, SD_FMT_IGNORE);
9683 		}
9684 
9685 		kmem_free(inq86, inq86_len);
9686 	} else {
9687 		mutex_exit(SD_MUTEX(un));
9688 	}
9689 
9690 	/*
9691 	 * Send a SYNC CACHE command to check whether
9692 	 * SYNC_NV bit is supported. This command should have
9693 	 * un_f_sync_nv_supported set to correct value.
9694 	 */
9695 	mutex_enter(SD_MUTEX(un));
9696 	if (un->un_f_sync_nv_supported) {
9697 		mutex_exit(SD_MUTEX(un));
9698 		dkc = kmem_zalloc(sizeof (struct dk_callback), KM_SLEEP);
9699 		dkc->dkc_flag = FLUSH_VOLATILE;
9700 		(void) sd_send_scsi_SYNCHRONIZE_CACHE(un, dkc);
9701 
9702 		/*
9703 		 * Send a TEST UNIT READY command to the device. This should
9704 		 * clear any outstanding UNIT ATTENTION that may be present.
9705 		 */
9706 		rval = sd_send_scsi_TEST_UNIT_READY(ssc, SD_DONT_RETRY_TUR);
9707 		if (rval != 0)
9708 			sd_ssc_assessment(ssc, SD_FMT_IGNORE);
9709 
9710 		kmem_free(dkc, sizeof (struct dk_callback));
9711 	} else {
9712 		mutex_exit(SD_MUTEX(un));
9713 	}
9714 
9715 	SD_TRACE(SD_LOG_COMMON, un, "sd_get_nv_sup: \
9716 	    un_f_suppress_cache_flush is set to %d\n",
9717 	    un->un_f_suppress_cache_flush);
9718 }
9719 
9720 /*
9721  *    Function: sd_make_device
9722  *
9723  * Description: Utility routine to return the Solaris device number from
9724  *		the data in the device's dev_info structure.
9725  *
9726  * Return Code: The Solaris device number
9727  *
9728  *     Context: Any
9729  */
9730 
9731 static dev_t
9732 sd_make_device(dev_info_t *devi)
9733 {
9734 	return (makedevice(ddi_driver_major(devi),
9735 	    ddi_get_instance(devi) << SDUNIT_SHIFT));
9736 }
9737 
9738 
9739 /*
9740  *    Function: sd_pm_entry
9741  *
9742  * Description: Called at the start of a new command to manage power
9743  *		and busy status of a device. This includes determining whether
9744  *		the current power state of the device is sufficient for
9745  *		performing the command or whether it must be changed.
9746  *		The PM framework is notified appropriately.
9747  *		Only with a return status of DDI_SUCCESS will the
9748  *		component be busy to the framework.
9749  *
9750  *		All callers of sd_pm_entry must check the return status
9751  *		and only call sd_pm_exit it it was DDI_SUCCESS. A status
9752  *		of DDI_FAILURE indicates the device failed to power up.
9753  *		In this case un_pm_count has been adjusted so the result
9754  *		on exit is still powered down, ie. count is less than 0.
9755  *		Calling sd_pm_exit with this count value hits an ASSERT.
9756  *
9757  * Return Code: DDI_SUCCESS or DDI_FAILURE
9758  *
9759  *     Context: Kernel thread context.
9760  */
9761 
9762 static int
9763 sd_pm_entry(struct sd_lun *un)
9764 {
9765 	int return_status = DDI_SUCCESS;
9766 
9767 	ASSERT(!mutex_owned(SD_MUTEX(un)));
9768 	ASSERT(!mutex_owned(&un->un_pm_mutex));
9769 
9770 	SD_TRACE(SD_LOG_IO_PM, un, "sd_pm_entry: entry\n");
9771 
9772 	if (un->un_f_pm_is_enabled == FALSE) {
9773 		SD_TRACE(SD_LOG_IO_PM, un,
9774 		    "sd_pm_entry: exiting, PM not enabled\n");
9775 		return (return_status);
9776 	}
9777 
9778 	/*
9779 	 * Just increment a counter if PM is enabled. On the transition from
9780 	 * 0 ==> 1, mark the device as busy.  The iodone side will decrement
9781 	 * the count with each IO and mark the device as idle when the count
9782 	 * hits 0.
9783 	 *
9784 	 * If the count is less than 0 the device is powered down. If a powered
9785 	 * down device is successfully powered up then the count must be
9786 	 * incremented to reflect the power up. Note that it'll get incremented
9787 	 * a second time to become busy.
9788 	 *
9789 	 * Because the following has the potential to change the device state
9790 	 * and must release the un_pm_mutex to do so, only one thread can be
9791 	 * allowed through at a time.
9792 	 */
9793 
9794 	mutex_enter(&un->un_pm_mutex);
9795 	while (un->un_pm_busy == TRUE) {
9796 		cv_wait(&un->un_pm_busy_cv, &un->un_pm_mutex);
9797 	}
9798 	un->un_pm_busy = TRUE;
9799 
9800 	if (un->un_pm_count < 1) {
9801 
9802 		SD_TRACE(SD_LOG_IO_PM, un, "sd_pm_entry: busy component\n");
9803 
9804 		/*
9805 		 * Indicate we are now busy so the framework won't attempt to
9806 		 * power down the device. This call will only fail if either
9807 		 * we passed a bad component number or the device has no
9808 		 * components. Neither of these should ever happen.
9809 		 */
9810 		mutex_exit(&un->un_pm_mutex);
9811 		return_status = pm_busy_component(SD_DEVINFO(un), 0);
9812 		ASSERT(return_status == DDI_SUCCESS);
9813 
9814 		mutex_enter(&un->un_pm_mutex);
9815 
9816 		if (un->un_pm_count < 0) {
9817 			mutex_exit(&un->un_pm_mutex);
9818 
9819 			SD_TRACE(SD_LOG_IO_PM, un,
9820 			    "sd_pm_entry: power up component\n");
9821 
9822 			/*
9823 			 * pm_raise_power will cause sdpower to be called
9824 			 * which brings the device power level to the
9825 			 * desired state, If successful, un_pm_count and
9826 			 * un_power_level will be updated appropriately.
9827 			 */
9828 			return_status = pm_raise_power(SD_DEVINFO(un), 0,
9829 			    SD_PM_STATE_ACTIVE(un));
9830 
9831 			mutex_enter(&un->un_pm_mutex);
9832 
9833 			if (return_status != DDI_SUCCESS) {
9834 				/*
9835 				 * Power up failed.
9836 				 * Idle the device and adjust the count
9837 				 * so the result on exit is that we're
9838 				 * still powered down, ie. count is less than 0.
9839 				 */
9840 				SD_TRACE(SD_LOG_IO_PM, un,
9841 				    "sd_pm_entry: power up failed,"
9842 				    " idle the component\n");
9843 
9844 				(void) pm_idle_component(SD_DEVINFO(un), 0);
9845 				un->un_pm_count--;
9846 			} else {
9847 				/*
9848 				 * Device is powered up, verify the
9849 				 * count is non-negative.
9850 				 * This is debug only.
9851 				 */
9852 				ASSERT(un->un_pm_count == 0);
9853 			}
9854 		}
9855 
9856 		if (return_status == DDI_SUCCESS) {
9857 			/*
9858 			 * For performance, now that the device has been tagged
9859 			 * as busy, and it's known to be powered up, update the
9860 			 * chain types to use jump tables that do not include
9861 			 * pm. This significantly lowers the overhead and
9862 			 * therefore improves performance.
9863 			 */
9864 
9865 			mutex_exit(&un->un_pm_mutex);
9866 			mutex_enter(SD_MUTEX(un));
9867 			SD_TRACE(SD_LOG_IO_PM, un,
9868 			    "sd_pm_entry: changing uscsi_chain_type from %d\n",
9869 			    un->un_uscsi_chain_type);
9870 
9871 			if (un->un_f_non_devbsize_supported) {
9872 				un->un_buf_chain_type =
9873 				    SD_CHAIN_INFO_RMMEDIA_NO_PM;
9874 			} else {
9875 				un->un_buf_chain_type =
9876 				    SD_CHAIN_INFO_DISK_NO_PM;
9877 			}
9878 			un->un_uscsi_chain_type = SD_CHAIN_INFO_USCSI_CMD_NO_PM;
9879 
9880 			SD_TRACE(SD_LOG_IO_PM, un,
9881 			    "             changed  uscsi_chain_type to   %d\n",
9882 			    un->un_uscsi_chain_type);
9883 			mutex_exit(SD_MUTEX(un));
9884 			mutex_enter(&un->un_pm_mutex);
9885 
9886 			if (un->un_pm_idle_timeid == NULL) {
9887 				/* 300 ms. */
9888 				un->un_pm_idle_timeid =
9889 				    timeout(sd_pm_idletimeout_handler, un,
9890 				    (drv_usectohz((clock_t)300000)));
9891 				/*
9892 				 * Include an extra call to busy which keeps the
9893 				 * device busy with-respect-to the PM layer
9894 				 * until the timer fires, at which time it'll
9895 				 * get the extra idle call.
9896 				 */
9897 				(void) pm_busy_component(SD_DEVINFO(un), 0);
9898 			}
9899 		}
9900 	}
9901 	un->un_pm_busy = FALSE;
9902 	/* Next... */
9903 	cv_signal(&un->un_pm_busy_cv);
9904 
9905 	un->un_pm_count++;
9906 
9907 	SD_TRACE(SD_LOG_IO_PM, un,
9908 	    "sd_pm_entry: exiting, un_pm_count = %d\n", un->un_pm_count);
9909 
9910 	mutex_exit(&un->un_pm_mutex);
9911 
9912 	return (return_status);
9913 }
9914 
9915 
9916 /*
9917  *    Function: sd_pm_exit
9918  *
9919  * Description: Called at the completion of a command to manage busy
9920  *		status for the device. If the device becomes idle the
9921  *		PM framework is notified.
9922  *
9923  *     Context: Kernel thread context
9924  */
9925 
9926 static void
9927 sd_pm_exit(struct sd_lun *un)
9928 {
9929 	ASSERT(!mutex_owned(SD_MUTEX(un)));
9930 	ASSERT(!mutex_owned(&un->un_pm_mutex));
9931 
9932 	SD_TRACE(SD_LOG_IO_PM, un, "sd_pm_exit: entry\n");
9933 
9934 	/*
9935 	 * After attach the following flag is only read, so don't
9936 	 * take the penalty of acquiring a mutex for it.
9937 	 */
9938 	if (un->un_f_pm_is_enabled == TRUE) {
9939 
9940 		mutex_enter(&un->un_pm_mutex);
9941 		un->un_pm_count--;
9942 
9943 		SD_TRACE(SD_LOG_IO_PM, un,
9944 		    "sd_pm_exit: un_pm_count = %d\n", un->un_pm_count);
9945 
9946 		ASSERT(un->un_pm_count >= 0);
9947 		if (un->un_pm_count == 0) {
9948 			mutex_exit(&un->un_pm_mutex);
9949 
9950 			SD_TRACE(SD_LOG_IO_PM, un,
9951 			    "sd_pm_exit: idle component\n");
9952 
9953 			(void) pm_idle_component(SD_DEVINFO(un), 0);
9954 
9955 		} else {
9956 			mutex_exit(&un->un_pm_mutex);
9957 		}
9958 	}
9959 
9960 	SD_TRACE(SD_LOG_IO_PM, un, "sd_pm_exit: exiting\n");
9961 }
9962 
9963 
9964 /*
9965  *    Function: sdopen
9966  *
9967  * Description: Driver's open(9e) entry point function.
9968  *
9969  *   Arguments: dev_i   - pointer to device number
9970  *		flag    - how to open file (FEXCL, FNDELAY, FREAD, FWRITE)
9971  *		otyp    - open type (OTYP_BLK, OTYP_CHR, OTYP_LYR)
9972  *		cred_p  - user credential pointer
9973  *
9974  * Return Code: EINVAL
9975  *		ENXIO
9976  *		EIO
9977  *		EROFS
9978  *		EBUSY
9979  *
9980  *     Context: Kernel thread context
9981  */
9982 /* ARGSUSED */
9983 static int
9984 sdopen(dev_t *dev_p, int flag, int otyp, cred_t *cred_p)
9985 {
9986 	struct sd_lun	*un;
9987 	int		nodelay;
9988 	int		part;
9989 	uint64_t	partmask;
9990 	int		instance;
9991 	dev_t		dev;
9992 	int		rval = EIO;
9993 	diskaddr_t	nblks = 0;
9994 	diskaddr_t	label_cap;
9995 
9996 	/* Validate the open type */
9997 	if (otyp >= OTYPCNT) {
9998 		return (EINVAL);
9999 	}
10000 
10001 	dev = *dev_p;
10002 	instance = SDUNIT(dev);
10003 	mutex_enter(&sd_detach_mutex);
10004 
10005 	/*
10006 	 * Fail the open if there is no softstate for the instance, or
10007 	 * if another thread somewhere is trying to detach the instance.
10008 	 */
10009 	if (((un = ddi_get_soft_state(sd_state, instance)) == NULL) ||
10010 	    (un->un_detach_count != 0)) {
10011 		mutex_exit(&sd_detach_mutex);
10012 		/*
10013 		 * The probe cache only needs to be cleared when open (9e) fails
10014 		 * with ENXIO (4238046).
10015 		 */
10016 		/*
10017 		 * un-conditionally clearing probe cache is ok with
10018 		 * separate sd/ssd binaries
10019 		 * x86 platform can be an issue with both parallel
10020 		 * and fibre in 1 binary
10021 		 */
10022 		sd_scsi_clear_probe_cache();
10023 		return (ENXIO);
10024 	}
10025 
10026 	/*
10027 	 * The un_layer_count is to prevent another thread in specfs from
10028 	 * trying to detach the instance, which can happen when we are
10029 	 * called from a higher-layer driver instead of thru specfs.
10030 	 * This will not be needed when DDI provides a layered driver
10031 	 * interface that allows specfs to know that an instance is in
10032 	 * use by a layered driver & should not be detached.
10033 	 *
10034 	 * Note: the semantics for layered driver opens are exactly one
10035 	 * close for every open.
10036 	 */
10037 	if (otyp == OTYP_LYR) {
10038 		un->un_layer_count++;
10039 	}
10040 
10041 	/*
10042 	 * Keep a count of the current # of opens in progress. This is because
10043 	 * some layered drivers try to call us as a regular open. This can
10044 	 * cause problems that we cannot prevent, however by keeping this count
10045 	 * we can at least keep our open and detach routines from racing against
10046 	 * each other under such conditions.
10047 	 */
10048 	un->un_opens_in_progress++;
10049 	mutex_exit(&sd_detach_mutex);
10050 
10051 	nodelay  = (flag & (FNDELAY | FNONBLOCK));
10052 	part	 = SDPART(dev);
10053 	partmask = 1 << part;
10054 
10055 	/*
10056 	 * We use a semaphore here in order to serialize
10057 	 * open and close requests on the device.
10058 	 */
10059 	sema_p(&un->un_semoclose);
10060 
10061 	mutex_enter(SD_MUTEX(un));
10062 
10063 	/*
10064 	 * All device accesses go thru sdstrategy() where we check
10065 	 * on suspend status but there could be a scsi_poll command,
10066 	 * which bypasses sdstrategy(), so we need to check pm
10067 	 * status.
10068 	 */
10069 
10070 	if (!nodelay) {
10071 		while ((un->un_state == SD_STATE_SUSPENDED) ||
10072 		    (un->un_state == SD_STATE_PM_CHANGING)) {
10073 			cv_wait(&un->un_suspend_cv, SD_MUTEX(un));
10074 		}
10075 
10076 		mutex_exit(SD_MUTEX(un));
10077 		if (sd_pm_entry(un) != DDI_SUCCESS) {
10078 			rval = EIO;
10079 			SD_ERROR(SD_LOG_OPEN_CLOSE, un,
10080 			    "sdopen: sd_pm_entry failed\n");
10081 			goto open_failed_with_pm;
10082 		}
10083 		mutex_enter(SD_MUTEX(un));
10084 	}
10085 
10086 	/* check for previous exclusive open */
10087 	SD_TRACE(SD_LOG_OPEN_CLOSE, un, "sdopen: un=%p\n", (void *)un);
10088 	SD_TRACE(SD_LOG_OPEN_CLOSE, un,
10089 	    "sdopen: exclopen=%x, flag=%x, regopen=%x\n",
10090 	    un->un_exclopen, flag, un->un_ocmap.regopen[otyp]);
10091 
10092 	if (un->un_exclopen & (partmask)) {
10093 		goto excl_open_fail;
10094 	}
10095 
10096 	if (flag & FEXCL) {
10097 		int i;
10098 		if (un->un_ocmap.lyropen[part]) {
10099 			goto excl_open_fail;
10100 		}
10101 		for (i = 0; i < (OTYPCNT - 1); i++) {
10102 			if (un->un_ocmap.regopen[i] & (partmask)) {
10103 				goto excl_open_fail;
10104 			}
10105 		}
10106 	}
10107 
10108 	/*
10109 	 * Check the write permission if this is a removable media device,
10110 	 * NDELAY has not been set, and writable permission is requested.
10111 	 *
10112 	 * Note: If NDELAY was set and this is write-protected media the WRITE
10113 	 * attempt will fail with EIO as part of the I/O processing. This is a
10114 	 * more permissive implementation that allows the open to succeed and
10115 	 * WRITE attempts to fail when appropriate.
10116 	 */
10117 	if (un->un_f_chk_wp_open) {
10118 		if ((flag & FWRITE) && (!nodelay)) {
10119 			mutex_exit(SD_MUTEX(un));
10120 			/*
10121 			 * Defer the check for write permission on writable
10122 			 * DVD drive till sdstrategy and will not fail open even
10123 			 * if FWRITE is set as the device can be writable
10124 			 * depending upon the media and the media can change
10125 			 * after the call to open().
10126 			 */
10127 			if (un->un_f_dvdram_writable_device == FALSE) {
10128 				if (ISCD(un) || sr_check_wp(dev)) {
10129 				rval = EROFS;
10130 				mutex_enter(SD_MUTEX(un));
10131 				SD_ERROR(SD_LOG_OPEN_CLOSE, un, "sdopen: "
10132 				    "write to cd or write protected media\n");
10133 				goto open_fail;
10134 				}
10135 			}
10136 			mutex_enter(SD_MUTEX(un));
10137 		}
10138 	}
10139 
10140 	/*
10141 	 * If opening in NDELAY/NONBLOCK mode, just return.
10142 	 * Check if disk is ready and has a valid geometry later.
10143 	 */
10144 	if (!nodelay) {
10145 		sd_ssc_t	*ssc;
10146 
10147 		mutex_exit(SD_MUTEX(un));
10148 		ssc = sd_ssc_init(un);
10149 		rval = sd_ready_and_valid(ssc, part);
10150 		sd_ssc_fini(ssc);
10151 		mutex_enter(SD_MUTEX(un));
10152 		/*
10153 		 * Fail if device is not ready or if the number of disk
10154 		 * blocks is zero or negative for non CD devices.
10155 		 */
10156 
10157 		nblks = 0;
10158 
10159 		if (rval == SD_READY_VALID && (!ISCD(un))) {
10160 			/* if cmlb_partinfo fails, nblks remains 0 */
10161 			mutex_exit(SD_MUTEX(un));
10162 			(void) cmlb_partinfo(un->un_cmlbhandle, part, &nblks,
10163 			    NULL, NULL, NULL, (void *)SD_PATH_DIRECT);
10164 			mutex_enter(SD_MUTEX(un));
10165 		}
10166 
10167 		if ((rval != SD_READY_VALID) ||
10168 		    (!ISCD(un) && nblks <= 0)) {
10169 			rval = un->un_f_has_removable_media ? ENXIO : EIO;
10170 			SD_ERROR(SD_LOG_OPEN_CLOSE, un, "sdopen: "
10171 			    "device not ready or invalid disk block value\n");
10172 			goto open_fail;
10173 		}
10174 #if defined(__i386) || defined(__amd64)
10175 	} else {
10176 		uchar_t *cp;
10177 		/*
10178 		 * x86 requires special nodelay handling, so that p0 is
10179 		 * always defined and accessible.
10180 		 * Invalidate geometry only if device is not already open.
10181 		 */
10182 		cp = &un->un_ocmap.chkd[0];
10183 		while (cp < &un->un_ocmap.chkd[OCSIZE]) {
10184 			if (*cp != (uchar_t)0) {
10185 				break;
10186 			}
10187 			cp++;
10188 		}
10189 		if (cp == &un->un_ocmap.chkd[OCSIZE]) {
10190 			mutex_exit(SD_MUTEX(un));
10191 			cmlb_invalidate(un->un_cmlbhandle,
10192 			    (void *)SD_PATH_DIRECT);
10193 			mutex_enter(SD_MUTEX(un));
10194 		}
10195 
10196 #endif
10197 	}
10198 
10199 	if (otyp == OTYP_LYR) {
10200 		un->un_ocmap.lyropen[part]++;
10201 	} else {
10202 		un->un_ocmap.regopen[otyp] |= partmask;
10203 	}
10204 
10205 	/* Set up open and exclusive open flags */
10206 	if (flag & FEXCL) {
10207 		un->un_exclopen |= (partmask);
10208 	}
10209 
10210 	/*
10211 	 * If the lun is EFI labeled and lun capacity is greater than the
10212 	 * capacity contained in the label, log a sys-event to notify the
10213 	 * interested module.
10214 	 * To avoid an infinite loop of logging sys-event, we only log the
10215 	 * event when the lun is not opened in NDELAY mode. The event handler
10216 	 * should open the lun in NDELAY mode.
10217 	 */
10218 	if (!(flag & FNDELAY)) {
10219 		mutex_exit(SD_MUTEX(un));
10220 		if (cmlb_efi_label_capacity(un->un_cmlbhandle, &label_cap,
10221 		    (void*)SD_PATH_DIRECT) == 0) {
10222 			mutex_enter(SD_MUTEX(un));
10223 			if (un->un_f_blockcount_is_valid &&
10224 			    un->un_blockcount > label_cap) {
10225 				mutex_exit(SD_MUTEX(un));
10226 				sd_log_lun_expansion_event(un,
10227 				    (nodelay ? KM_NOSLEEP : KM_SLEEP));
10228 				mutex_enter(SD_MUTEX(un));
10229 			}
10230 		} else {
10231 			mutex_enter(SD_MUTEX(un));
10232 		}
10233 	}
10234 
10235 	SD_TRACE(SD_LOG_OPEN_CLOSE, un, "sdopen: "
10236 	    "open of part %d type %d\n", part, otyp);
10237 
10238 	mutex_exit(SD_MUTEX(un));
10239 	if (!nodelay) {
10240 		sd_pm_exit(un);
10241 	}
10242 
10243 	sema_v(&un->un_semoclose);
10244 
10245 	mutex_enter(&sd_detach_mutex);
10246 	un->un_opens_in_progress--;
10247 	mutex_exit(&sd_detach_mutex);
10248 
10249 	SD_TRACE(SD_LOG_OPEN_CLOSE, un, "sdopen: exit success\n");
10250 	return (DDI_SUCCESS);
10251 
10252 excl_open_fail:
10253 	SD_ERROR(SD_LOG_OPEN_CLOSE, un, "sdopen: fail exclusive open\n");
10254 	rval = EBUSY;
10255 
10256 open_fail:
10257 	mutex_exit(SD_MUTEX(un));
10258 
10259 	/*
10260 	 * On a failed open we must exit the pm management.
10261 	 */
10262 	if (!nodelay) {
10263 		sd_pm_exit(un);
10264 	}
10265 open_failed_with_pm:
10266 	sema_v(&un->un_semoclose);
10267 
10268 	mutex_enter(&sd_detach_mutex);
10269 	un->un_opens_in_progress--;
10270 	if (otyp == OTYP_LYR) {
10271 		un->un_layer_count--;
10272 	}
10273 	mutex_exit(&sd_detach_mutex);
10274 
10275 	return (rval);
10276 }
10277 
10278 
10279 /*
10280  *    Function: sdclose
10281  *
10282  * Description: Driver's close(9e) entry point function.
10283  *
10284  *   Arguments: dev    - device number
10285  *		flag   - file status flag, informational only
10286  *		otyp   - close type (OTYP_BLK, OTYP_CHR, OTYP_LYR)
10287  *		cred_p - user credential pointer
10288  *
10289  * Return Code: ENXIO
10290  *
10291  *     Context: Kernel thread context
10292  */
10293 /* ARGSUSED */
10294 static int
10295 sdclose(dev_t dev, int flag, int otyp, cred_t *cred_p)
10296 {
10297 	struct sd_lun	*un;
10298 	uchar_t		*cp;
10299 	int		part;
10300 	int		nodelay;
10301 	int		rval = 0;
10302 
10303 	/* Validate the open type */
10304 	if (otyp >= OTYPCNT) {
10305 		return (ENXIO);
10306 	}
10307 
10308 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
10309 		return (ENXIO);
10310 	}
10311 
10312 	part = SDPART(dev);
10313 	nodelay = flag & (FNDELAY | FNONBLOCK);
10314 
10315 	SD_TRACE(SD_LOG_OPEN_CLOSE, un,
10316 	    "sdclose: close of part %d type %d\n", part, otyp);
10317 
10318 	/*
10319 	 * We use a semaphore here in order to serialize
10320 	 * open and close requests on the device.
10321 	 */
10322 	sema_p(&un->un_semoclose);
10323 
10324 	mutex_enter(SD_MUTEX(un));
10325 
10326 	/* Don't proceed if power is being changed. */
10327 	while (un->un_state == SD_STATE_PM_CHANGING) {
10328 		cv_wait(&un->un_suspend_cv, SD_MUTEX(un));
10329 	}
10330 
10331 	if (un->un_exclopen & (1 << part)) {
10332 		un->un_exclopen &= ~(1 << part);
10333 	}
10334 
10335 	/* Update the open partition map */
10336 	if (otyp == OTYP_LYR) {
10337 		un->un_ocmap.lyropen[part] -= 1;
10338 	} else {
10339 		un->un_ocmap.regopen[otyp] &= ~(1 << part);
10340 	}
10341 
10342 	cp = &un->un_ocmap.chkd[0];
10343 	while (cp < &un->un_ocmap.chkd[OCSIZE]) {
10344 		if (*cp != NULL) {
10345 			break;
10346 		}
10347 		cp++;
10348 	}
10349 
10350 	if (cp == &un->un_ocmap.chkd[OCSIZE]) {
10351 		SD_TRACE(SD_LOG_OPEN_CLOSE, un, "sdclose: last close\n");
10352 
10353 		/*
10354 		 * We avoid persistance upon the last close, and set
10355 		 * the throttle back to the maximum.
10356 		 */
10357 		un->un_throttle = un->un_saved_throttle;
10358 
10359 		if (un->un_state == SD_STATE_OFFLINE) {
10360 			if (un->un_f_is_fibre == FALSE) {
10361 				scsi_log(SD_DEVINFO(un), sd_label,
10362 				    CE_WARN, "offline\n");
10363 			}
10364 			mutex_exit(SD_MUTEX(un));
10365 			cmlb_invalidate(un->un_cmlbhandle,
10366 			    (void *)SD_PATH_DIRECT);
10367 			mutex_enter(SD_MUTEX(un));
10368 
10369 		} else {
10370 			/*
10371 			 * Flush any outstanding writes in NVRAM cache.
10372 			 * Note: SYNCHRONIZE CACHE is an optional SCSI-2
10373 			 * cmd, it may not work for non-Pluto devices.
10374 			 * SYNCHRONIZE CACHE is not required for removables,
10375 			 * except DVD-RAM drives.
10376 			 *
10377 			 * Also note: because SYNCHRONIZE CACHE is currently
10378 			 * the only command issued here that requires the
10379 			 * drive be powered up, only do the power up before
10380 			 * sending the Sync Cache command. If additional
10381 			 * commands are added which require a powered up
10382 			 * drive, the following sequence may have to change.
10383 			 *
10384 			 * And finally, note that parallel SCSI on SPARC
10385 			 * only issues a Sync Cache to DVD-RAM, a newly
10386 			 * supported device.
10387 			 */
10388 #if defined(__i386) || defined(__amd64)
10389 			if ((un->un_f_sync_cache_supported &&
10390 			    un->un_f_sync_cache_required) ||
10391 			    un->un_f_dvdram_writable_device == TRUE) {
10392 #else
10393 			if (un->un_f_dvdram_writable_device == TRUE) {
10394 #endif
10395 				mutex_exit(SD_MUTEX(un));
10396 				if (sd_pm_entry(un) == DDI_SUCCESS) {
10397 					rval =
10398 					    sd_send_scsi_SYNCHRONIZE_CACHE(un,
10399 					    NULL);
10400 					/* ignore error if not supported */
10401 					if (rval == ENOTSUP) {
10402 						rval = 0;
10403 					} else if (rval != 0) {
10404 						rval = EIO;
10405 					}
10406 					sd_pm_exit(un);
10407 				} else {
10408 					rval = EIO;
10409 				}
10410 				mutex_enter(SD_MUTEX(un));
10411 			}
10412 
10413 			/*
10414 			 * For devices which supports DOOR_LOCK, send an ALLOW
10415 			 * MEDIA REMOVAL command, but don't get upset if it
10416 			 * fails. We need to raise the power of the drive before
10417 			 * we can call sd_send_scsi_DOORLOCK()
10418 			 */
10419 			if (un->un_f_doorlock_supported) {
10420 				mutex_exit(SD_MUTEX(un));
10421 				if (sd_pm_entry(un) == DDI_SUCCESS) {
10422 					sd_ssc_t	*ssc;
10423 
10424 					ssc = sd_ssc_init(un);
10425 					rval = sd_send_scsi_DOORLOCK(ssc,
10426 					    SD_REMOVAL_ALLOW, SD_PATH_DIRECT);
10427 					if (rval != 0)
10428 						sd_ssc_assessment(ssc,
10429 						    SD_FMT_IGNORE);
10430 					sd_ssc_fini(ssc);
10431 
10432 					sd_pm_exit(un);
10433 					if (ISCD(un) && (rval != 0) &&
10434 					    (nodelay != 0)) {
10435 						rval = ENXIO;
10436 					}
10437 				} else {
10438 					rval = EIO;
10439 				}
10440 				mutex_enter(SD_MUTEX(un));
10441 			}
10442 
10443 			/*
10444 			 * If a device has removable media, invalidate all
10445 			 * parameters related to media, such as geometry,
10446 			 * blocksize, and blockcount.
10447 			 */
10448 			if (un->un_f_has_removable_media) {
10449 				sr_ejected(un);
10450 			}
10451 
10452 			/*
10453 			 * Destroy the cache (if it exists) which was
10454 			 * allocated for the write maps since this is
10455 			 * the last close for this media.
10456 			 */
10457 			if (un->un_wm_cache) {
10458 				/*
10459 				 * Check if there are pending commands.
10460 				 * and if there are give a warning and
10461 				 * do not destroy the cache.
10462 				 */
10463 				if (un->un_ncmds_in_driver > 0) {
10464 					scsi_log(SD_DEVINFO(un),
10465 					    sd_label, CE_WARN,
10466 					    "Unable to clean up memory "
10467 					    "because of pending I/O\n");
10468 				} else {
10469 					kmem_cache_destroy(
10470 					    un->un_wm_cache);
10471 					un->un_wm_cache = NULL;
10472 				}
10473 			}
10474 		}
10475 	}
10476 
10477 	mutex_exit(SD_MUTEX(un));
10478 	sema_v(&un->un_semoclose);
10479 
10480 	if (otyp == OTYP_LYR) {
10481 		mutex_enter(&sd_detach_mutex);
10482 		/*
10483 		 * The detach routine may run when the layer count
10484 		 * drops to zero.
10485 		 */
10486 		un->un_layer_count--;
10487 		mutex_exit(&sd_detach_mutex);
10488 	}
10489 
10490 	return (rval);
10491 }
10492 
10493 
10494 /*
10495  *    Function: sd_ready_and_valid
10496  *
10497  * Description: Test if device is ready and has a valid geometry.
10498  *
10499  *   Arguments: ssc - sd_ssc_t will contain un
10500  *		un  - driver soft state (unit) structure
10501  *
10502  * Return Code: SD_READY_VALID		ready and valid label
10503  *		SD_NOT_READY_VALID	not ready, no label
10504  *		SD_RESERVED_BY_OTHERS	reservation conflict
10505  *
10506  *     Context: Never called at interrupt context.
10507  */
10508 
10509 static int
10510 sd_ready_and_valid(sd_ssc_t *ssc, int part)
10511 {
10512 	struct sd_errstats	*stp;
10513 	uint64_t		capacity;
10514 	uint_t			lbasize;
10515 	int			rval = SD_READY_VALID;
10516 	char			name_str[48];
10517 	boolean_t		is_valid;
10518 	struct sd_lun		*un;
10519 	int			status;
10520 
10521 	ASSERT(ssc != NULL);
10522 	un = ssc->ssc_un;
10523 	ASSERT(un != NULL);
10524 	ASSERT(!mutex_owned(SD_MUTEX(un)));
10525 
10526 	mutex_enter(SD_MUTEX(un));
10527 	/*
10528 	 * If a device has removable media, we must check if media is
10529 	 * ready when checking if this device is ready and valid.
10530 	 */
10531 	if (un->un_f_has_removable_media) {
10532 		mutex_exit(SD_MUTEX(un));
10533 		status = sd_send_scsi_TEST_UNIT_READY(ssc, 0);
10534 
10535 		if (status != 0) {
10536 			rval = SD_NOT_READY_VALID;
10537 			mutex_enter(SD_MUTEX(un));
10538 
10539 			/* Ignore all failed status for removalbe media */
10540 			sd_ssc_assessment(ssc, SD_FMT_IGNORE);
10541 
10542 			goto done;
10543 		}
10544 
10545 		is_valid = SD_IS_VALID_LABEL(un);
10546 		mutex_enter(SD_MUTEX(un));
10547 		if (!is_valid ||
10548 		    (un->un_f_blockcount_is_valid == FALSE) ||
10549 		    (un->un_f_tgt_blocksize_is_valid == FALSE)) {
10550 
10551 			/* capacity has to be read every open. */
10552 			mutex_exit(SD_MUTEX(un));
10553 			status = sd_send_scsi_READ_CAPACITY(ssc, &capacity,
10554 			    &lbasize, SD_PATH_DIRECT);
10555 
10556 			if (status != 0) {
10557 				sd_ssc_assessment(ssc, SD_FMT_IGNORE);
10558 
10559 				cmlb_invalidate(un->un_cmlbhandle,
10560 				    (void *)SD_PATH_DIRECT);
10561 				mutex_enter(SD_MUTEX(un));
10562 				rval = SD_NOT_READY_VALID;
10563 
10564 				goto done;
10565 			} else {
10566 				mutex_enter(SD_MUTEX(un));
10567 				sd_update_block_info(un, lbasize, capacity);
10568 			}
10569 		}
10570 
10571 		/*
10572 		 * Check if the media in the device is writable or not.
10573 		 */
10574 		if (!is_valid && ISCD(un)) {
10575 			sd_check_for_writable_cd(ssc, SD_PATH_DIRECT);
10576 		}
10577 
10578 	} else {
10579 		/*
10580 		 * Do a test unit ready to clear any unit attention from non-cd
10581 		 * devices.
10582 		 */
10583 		mutex_exit(SD_MUTEX(un));
10584 
10585 		status = sd_send_scsi_TEST_UNIT_READY(ssc, 0);
10586 		if (status != 0) {
10587 			sd_ssc_assessment(ssc, SD_FMT_IGNORE);
10588 		}
10589 
10590 		mutex_enter(SD_MUTEX(un));
10591 	}
10592 
10593 
10594 	/*
10595 	 * If this is a non 512 block device, allocate space for
10596 	 * the wmap cache. This is being done here since every time
10597 	 * a media is changed this routine will be called and the
10598 	 * block size is a function of media rather than device.
10599 	 */
10600 	if ((un->un_f_rmw_type != SD_RMW_TYPE_RETURN_ERROR ||
10601 	    un->un_f_non_devbsize_supported) &&
10602 	    un->un_tgt_blocksize != DEV_BSIZE) {
10603 		if (!(un->un_wm_cache)) {
10604 			(void) snprintf(name_str, sizeof (name_str),
10605 			    "%s%d_cache",
10606 			    ddi_driver_name(SD_DEVINFO(un)),
10607 			    ddi_get_instance(SD_DEVINFO(un)));
10608 			un->un_wm_cache = kmem_cache_create(
10609 			    name_str, sizeof (struct sd_w_map),
10610 			    8, sd_wm_cache_constructor,
10611 			    sd_wm_cache_destructor, NULL,
10612 			    (void *)un, NULL, 0);
10613 			if (!(un->un_wm_cache)) {
10614 				rval = ENOMEM;
10615 				goto done;
10616 			}
10617 		}
10618 	}
10619 
10620 	if (un->un_state == SD_STATE_NORMAL) {
10621 		/*
10622 		 * If the target is not yet ready here (defined by a TUR
10623 		 * failure), invalidate the geometry and print an 'offline'
10624 		 * message. This is a legacy message, as the state of the
10625 		 * target is not actually changed to SD_STATE_OFFLINE.
10626 		 *
10627 		 * If the TUR fails for EACCES (Reservation Conflict),
10628 		 * SD_RESERVED_BY_OTHERS will be returned to indicate
10629 		 * reservation conflict. If the TUR fails for other
10630 		 * reasons, SD_NOT_READY_VALID will be returned.
10631 		 */
10632 		int err;
10633 
10634 		mutex_exit(SD_MUTEX(un));
10635 		err = sd_send_scsi_TEST_UNIT_READY(ssc, 0);
10636 		mutex_enter(SD_MUTEX(un));
10637 
10638 		if (err != 0) {
10639 			mutex_exit(SD_MUTEX(un));
10640 			cmlb_invalidate(un->un_cmlbhandle,
10641 			    (void *)SD_PATH_DIRECT);
10642 			mutex_enter(SD_MUTEX(un));
10643 			if (err == EACCES) {
10644 				scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
10645 				    "reservation conflict\n");
10646 				rval = SD_RESERVED_BY_OTHERS;
10647 				sd_ssc_assessment(ssc, SD_FMT_IGNORE);
10648 			} else {
10649 				scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
10650 				    "drive offline\n");
10651 				rval = SD_NOT_READY_VALID;
10652 				sd_ssc_assessment(ssc, SD_FMT_STATUS_CHECK);
10653 			}
10654 			goto done;
10655 		}
10656 	}
10657 
10658 	if (un->un_f_format_in_progress == FALSE) {
10659 		mutex_exit(SD_MUTEX(un));
10660 
10661 		(void) cmlb_validate(un->un_cmlbhandle, 0,
10662 		    (void *)SD_PATH_DIRECT);
10663 		if (cmlb_partinfo(un->un_cmlbhandle, part, NULL, NULL, NULL,
10664 		    NULL, (void *) SD_PATH_DIRECT) != 0) {
10665 			rval = SD_NOT_READY_VALID;
10666 			mutex_enter(SD_MUTEX(un));
10667 
10668 			goto done;
10669 		}
10670 		if (un->un_f_pkstats_enabled) {
10671 			sd_set_pstats(un);
10672 			SD_TRACE(SD_LOG_IO_PARTITION, un,
10673 			    "sd_ready_and_valid: un:0x%p pstats created and "
10674 			    "set\n", un);
10675 		}
10676 		mutex_enter(SD_MUTEX(un));
10677 	}
10678 
10679 	/*
10680 	 * If this device supports DOOR_LOCK command, try and send
10681 	 * this command to PREVENT MEDIA REMOVAL, but don't get upset
10682 	 * if it fails. For a CD, however, it is an error
10683 	 */
10684 	if (un->un_f_doorlock_supported) {
10685 		mutex_exit(SD_MUTEX(un));
10686 		status = sd_send_scsi_DOORLOCK(ssc, SD_REMOVAL_PREVENT,
10687 		    SD_PATH_DIRECT);
10688 
10689 		if ((status != 0) && ISCD(un)) {
10690 			rval = SD_NOT_READY_VALID;
10691 			mutex_enter(SD_MUTEX(un));
10692 
10693 			sd_ssc_assessment(ssc, SD_FMT_IGNORE);
10694 
10695 			goto done;
10696 		} else if (status != 0)
10697 			sd_ssc_assessment(ssc, SD_FMT_IGNORE);
10698 		mutex_enter(SD_MUTEX(un));
10699 	}
10700 
10701 	/* The state has changed, inform the media watch routines */
10702 	un->un_mediastate = DKIO_INSERTED;
10703 	cv_broadcast(&un->un_state_cv);
10704 	rval = SD_READY_VALID;
10705 
10706 done:
10707 
10708 	/*
10709 	 * Initialize the capacity kstat value, if no media previously
10710 	 * (capacity kstat is 0) and a media has been inserted
10711 	 * (un_blockcount > 0).
10712 	 */
10713 	if (un->un_errstats != NULL) {
10714 		stp = (struct sd_errstats *)un->un_errstats->ks_data;
10715 		if ((stp->sd_capacity.value.ui64 == 0) &&
10716 		    (un->un_f_blockcount_is_valid == TRUE)) {
10717 			stp->sd_capacity.value.ui64 =
10718 			    (uint64_t)((uint64_t)un->un_blockcount *
10719 			    un->un_sys_blocksize);
10720 		}
10721 	}
10722 
10723 	mutex_exit(SD_MUTEX(un));
10724 	return (rval);
10725 }
10726 
10727 
10728 /*
10729  *    Function: sdmin
10730  *
10731  * Description: Routine to limit the size of a data transfer. Used in
10732  *		conjunction with physio(9F).
10733  *
10734  *   Arguments: bp - pointer to the indicated buf(9S) struct.
10735  *
10736  *     Context: Kernel thread context.
10737  */
10738 
10739 static void
10740 sdmin(struct buf *bp)
10741 {
10742 	struct sd_lun	*un;
10743 	int		instance;
10744 
10745 	instance = SDUNIT(bp->b_edev);
10746 
10747 	un = ddi_get_soft_state(sd_state, instance);
10748 	ASSERT(un != NULL);
10749 
10750 	/*
10751 	 * We depend on DMA partial or buf breakup to restrict
10752 	 * IO size if any of them enabled.
10753 	 */
10754 	if (un->un_partial_dma_supported ||
10755 	    un->un_buf_breakup_supported) {
10756 		return;
10757 	}
10758 
10759 	if (bp->b_bcount > un->un_max_xfer_size) {
10760 		bp->b_bcount = un->un_max_xfer_size;
10761 	}
10762 }
10763 
10764 
10765 /*
10766  *    Function: sdread
10767  *
10768  * Description: Driver's read(9e) entry point function.
10769  *
10770  *   Arguments: dev   - device number
10771  *		uio   - structure pointer describing where data is to be stored
10772  *			in user's space
10773  *		cred_p  - user credential pointer
10774  *
10775  * Return Code: ENXIO
10776  *		EIO
10777  *		EINVAL
10778  *		value returned by physio
10779  *
10780  *     Context: Kernel thread context.
10781  */
10782 /* ARGSUSED */
10783 static int
10784 sdread(dev_t dev, struct uio *uio, cred_t *cred_p)
10785 {
10786 	struct sd_lun	*un = NULL;
10787 	int		secmask;
10788 	int		err = 0;
10789 	sd_ssc_t	*ssc;
10790 
10791 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
10792 		return (ENXIO);
10793 	}
10794 
10795 	ASSERT(!mutex_owned(SD_MUTEX(un)));
10796 
10797 
10798 	if (!SD_IS_VALID_LABEL(un) && !ISCD(un)) {
10799 		mutex_enter(SD_MUTEX(un));
10800 		/*
10801 		 * Because the call to sd_ready_and_valid will issue I/O we
10802 		 * must wait here if either the device is suspended or
10803 		 * if it's power level is changing.
10804 		 */
10805 		while ((un->un_state == SD_STATE_SUSPENDED) ||
10806 		    (un->un_state == SD_STATE_PM_CHANGING)) {
10807 			cv_wait(&un->un_suspend_cv, SD_MUTEX(un));
10808 		}
10809 		un->un_ncmds_in_driver++;
10810 		mutex_exit(SD_MUTEX(un));
10811 
10812 		/* Initialize sd_ssc_t for internal uscsi commands */
10813 		ssc = sd_ssc_init(un);
10814 		if ((sd_ready_and_valid(ssc, SDPART(dev))) != SD_READY_VALID) {
10815 			err = EIO;
10816 		} else {
10817 			err = 0;
10818 		}
10819 		sd_ssc_fini(ssc);
10820 
10821 		mutex_enter(SD_MUTEX(un));
10822 		un->un_ncmds_in_driver--;
10823 		ASSERT(un->un_ncmds_in_driver >= 0);
10824 		mutex_exit(SD_MUTEX(un));
10825 		if (err != 0)
10826 			return (err);
10827 	}
10828 
10829 	/*
10830 	 * Read requests are restricted to multiples of the system block size.
10831 	 */
10832 	if (un->un_f_rmw_type == SD_RMW_TYPE_RETURN_ERROR)
10833 		secmask = un->un_tgt_blocksize - 1;
10834 	else
10835 		secmask = DEV_BSIZE - 1;
10836 
10837 	if (uio->uio_loffset & ((offset_t)(secmask))) {
10838 		SD_ERROR(SD_LOG_READ_WRITE, un,
10839 		    "sdread: file offset not modulo %d\n",
10840 		    secmask + 1);
10841 		err = EINVAL;
10842 	} else if (uio->uio_iov->iov_len & (secmask)) {
10843 		SD_ERROR(SD_LOG_READ_WRITE, un,
10844 		    "sdread: transfer length not modulo %d\n",
10845 		    secmask + 1);
10846 		err = EINVAL;
10847 	} else {
10848 		err = physio(sdstrategy, NULL, dev, B_READ, sdmin, uio);
10849 	}
10850 
10851 	return (err);
10852 }
10853 
10854 
10855 /*
10856  *    Function: sdwrite
10857  *
10858  * Description: Driver's write(9e) entry point function.
10859  *
10860  *   Arguments: dev   - device number
10861  *		uio   - structure pointer describing where data is stored in
10862  *			user's space
10863  *		cred_p  - user credential pointer
10864  *
10865  * Return Code: ENXIO
10866  *		EIO
10867  *		EINVAL
10868  *		value returned by physio
10869  *
10870  *     Context: Kernel thread context.
10871  */
10872 /* ARGSUSED */
10873 static int
10874 sdwrite(dev_t dev, struct uio *uio, cred_t *cred_p)
10875 {
10876 	struct sd_lun	*un = NULL;
10877 	int		secmask;
10878 	int		err = 0;
10879 	sd_ssc_t	*ssc;
10880 
10881 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
10882 		return (ENXIO);
10883 	}
10884 
10885 	ASSERT(!mutex_owned(SD_MUTEX(un)));
10886 
10887 	if (!SD_IS_VALID_LABEL(un) && !ISCD(un)) {
10888 		mutex_enter(SD_MUTEX(un));
10889 		/*
10890 		 * Because the call to sd_ready_and_valid will issue I/O we
10891 		 * must wait here if either the device is suspended or
10892 		 * if it's power level is changing.
10893 		 */
10894 		while ((un->un_state == SD_STATE_SUSPENDED) ||
10895 		    (un->un_state == SD_STATE_PM_CHANGING)) {
10896 			cv_wait(&un->un_suspend_cv, SD_MUTEX(un));
10897 		}
10898 		un->un_ncmds_in_driver++;
10899 		mutex_exit(SD_MUTEX(un));
10900 
10901 		/* Initialize sd_ssc_t for internal uscsi commands */
10902 		ssc = sd_ssc_init(un);
10903 		if ((sd_ready_and_valid(ssc, SDPART(dev))) != SD_READY_VALID) {
10904 			err = EIO;
10905 		} else {
10906 			err = 0;
10907 		}
10908 		sd_ssc_fini(ssc);
10909 
10910 		mutex_enter(SD_MUTEX(un));
10911 		un->un_ncmds_in_driver--;
10912 		ASSERT(un->un_ncmds_in_driver >= 0);
10913 		mutex_exit(SD_MUTEX(un));
10914 		if (err != 0)
10915 			return (err);
10916 	}
10917 
10918 	/*
10919 	 * Write requests are restricted to multiples of the system block size.
10920 	 */
10921 	if (un->un_f_rmw_type == SD_RMW_TYPE_RETURN_ERROR)
10922 		secmask = un->un_tgt_blocksize - 1;
10923 	else
10924 		secmask = DEV_BSIZE - 1;
10925 
10926 	if (uio->uio_loffset & ((offset_t)(secmask))) {
10927 		SD_ERROR(SD_LOG_READ_WRITE, un,
10928 		    "sdwrite: file offset not modulo %d\n",
10929 		    secmask + 1);
10930 		err = EINVAL;
10931 	} else if (uio->uio_iov->iov_len & (secmask)) {
10932 		SD_ERROR(SD_LOG_READ_WRITE, un,
10933 		    "sdwrite: transfer length not modulo %d\n",
10934 		    secmask + 1);
10935 		err = EINVAL;
10936 	} else {
10937 		err = physio(sdstrategy, NULL, dev, B_WRITE, sdmin, uio);
10938 	}
10939 
10940 	return (err);
10941 }
10942 
10943 
10944 /*
10945  *    Function: sdaread
10946  *
10947  * Description: Driver's aread(9e) entry point function.
10948  *
10949  *   Arguments: dev   - device number
10950  *		aio   - structure pointer describing where data is to be stored
10951  *		cred_p  - user credential pointer
10952  *
10953  * Return Code: ENXIO
10954  *		EIO
10955  *		EINVAL
10956  *		value returned by aphysio
10957  *
10958  *     Context: Kernel thread context.
10959  */
10960 /* ARGSUSED */
10961 static int
10962 sdaread(dev_t dev, struct aio_req *aio, cred_t *cred_p)
10963 {
10964 	struct sd_lun	*un = NULL;
10965 	struct uio	*uio = aio->aio_uio;
10966 	int		secmask;
10967 	int		err = 0;
10968 	sd_ssc_t	*ssc;
10969 
10970 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
10971 		return (ENXIO);
10972 	}
10973 
10974 	ASSERT(!mutex_owned(SD_MUTEX(un)));
10975 
10976 	if (!SD_IS_VALID_LABEL(un) && !ISCD(un)) {
10977 		mutex_enter(SD_MUTEX(un));
10978 		/*
10979 		 * Because the call to sd_ready_and_valid will issue I/O we
10980 		 * must wait here if either the device is suspended or
10981 		 * if it's power level is changing.
10982 		 */
10983 		while ((un->un_state == SD_STATE_SUSPENDED) ||
10984 		    (un->un_state == SD_STATE_PM_CHANGING)) {
10985 			cv_wait(&un->un_suspend_cv, SD_MUTEX(un));
10986 		}
10987 		un->un_ncmds_in_driver++;
10988 		mutex_exit(SD_MUTEX(un));
10989 
10990 		/* Initialize sd_ssc_t for internal uscsi commands */
10991 		ssc = sd_ssc_init(un);
10992 		if ((sd_ready_and_valid(ssc, SDPART(dev))) != SD_READY_VALID) {
10993 			err = EIO;
10994 		} else {
10995 			err = 0;
10996 		}
10997 		sd_ssc_fini(ssc);
10998 
10999 		mutex_enter(SD_MUTEX(un));
11000 		un->un_ncmds_in_driver--;
11001 		ASSERT(un->un_ncmds_in_driver >= 0);
11002 		mutex_exit(SD_MUTEX(un));
11003 		if (err != 0)
11004 			return (err);
11005 	}
11006 
11007 	/*
11008 	 * Read requests are restricted to multiples of the system block size.
11009 	 */
11010 	if (un->un_f_rmw_type == SD_RMW_TYPE_RETURN_ERROR)
11011 		secmask = un->un_tgt_blocksize - 1;
11012 	else
11013 		secmask = DEV_BSIZE - 1;
11014 
11015 	if (uio->uio_loffset & ((offset_t)(secmask))) {
11016 		SD_ERROR(SD_LOG_READ_WRITE, un,
11017 		    "sdaread: file offset not modulo %d\n",
11018 		    secmask + 1);
11019 		err = EINVAL;
11020 	} else if (uio->uio_iov->iov_len & (secmask)) {
11021 		SD_ERROR(SD_LOG_READ_WRITE, un,
11022 		    "sdaread: transfer length not modulo %d\n",
11023 		    secmask + 1);
11024 		err = EINVAL;
11025 	} else {
11026 		err = aphysio(sdstrategy, anocancel, dev, B_READ, sdmin, aio);
11027 	}
11028 
11029 	return (err);
11030 }
11031 
11032 
11033 /*
11034  *    Function: sdawrite
11035  *
11036  * Description: Driver's awrite(9e) entry point function.
11037  *
11038  *   Arguments: dev   - device number
11039  *		aio   - structure pointer describing where data is stored
11040  *		cred_p  - user credential pointer
11041  *
11042  * Return Code: ENXIO
11043  *		EIO
11044  *		EINVAL
11045  *		value returned by aphysio
11046  *
11047  *     Context: Kernel thread context.
11048  */
11049 /* ARGSUSED */
11050 static int
11051 sdawrite(dev_t dev, struct aio_req *aio, cred_t *cred_p)
11052 {
11053 	struct sd_lun	*un = NULL;
11054 	struct uio	*uio = aio->aio_uio;
11055 	int		secmask;
11056 	int		err = 0;
11057 	sd_ssc_t	*ssc;
11058 
11059 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
11060 		return (ENXIO);
11061 	}
11062 
11063 	ASSERT(!mutex_owned(SD_MUTEX(un)));
11064 
11065 	if (!SD_IS_VALID_LABEL(un) && !ISCD(un)) {
11066 		mutex_enter(SD_MUTEX(un));
11067 		/*
11068 		 * Because the call to sd_ready_and_valid will issue I/O we
11069 		 * must wait here if either the device is suspended or
11070 		 * if it's power level is changing.
11071 		 */
11072 		while ((un->un_state == SD_STATE_SUSPENDED) ||
11073 		    (un->un_state == SD_STATE_PM_CHANGING)) {
11074 			cv_wait(&un->un_suspend_cv, SD_MUTEX(un));
11075 		}
11076 		un->un_ncmds_in_driver++;
11077 		mutex_exit(SD_MUTEX(un));
11078 
11079 		/* Initialize sd_ssc_t for internal uscsi commands */
11080 		ssc = sd_ssc_init(un);
11081 		if ((sd_ready_and_valid(ssc, SDPART(dev))) != SD_READY_VALID) {
11082 			err = EIO;
11083 		} else {
11084 			err = 0;
11085 		}
11086 		sd_ssc_fini(ssc);
11087 
11088 		mutex_enter(SD_MUTEX(un));
11089 		un->un_ncmds_in_driver--;
11090 		ASSERT(un->un_ncmds_in_driver >= 0);
11091 		mutex_exit(SD_MUTEX(un));
11092 		if (err != 0)
11093 			return (err);
11094 	}
11095 
11096 	/*
11097 	 * Write requests are restricted to multiples of the system block size.
11098 	 */
11099 	if (un->un_f_rmw_type == SD_RMW_TYPE_RETURN_ERROR)
11100 		secmask = un->un_tgt_blocksize - 1;
11101 	else
11102 		secmask = DEV_BSIZE - 1;
11103 
11104 	if (uio->uio_loffset & ((offset_t)(secmask))) {
11105 		SD_ERROR(SD_LOG_READ_WRITE, un,
11106 		    "sdawrite: file offset not modulo %d\n",
11107 		    secmask + 1);
11108 		err = EINVAL;
11109 	} else if (uio->uio_iov->iov_len & (secmask)) {
11110 		SD_ERROR(SD_LOG_READ_WRITE, un,
11111 		    "sdawrite: transfer length not modulo %d\n",
11112 		    secmask + 1);
11113 		err = EINVAL;
11114 	} else {
11115 		err = aphysio(sdstrategy, anocancel, dev, B_WRITE, sdmin, aio);
11116 	}
11117 
11118 	return (err);
11119 }
11120 
11121 
11122 
11123 
11124 
11125 /*
11126  * Driver IO processing follows the following sequence:
11127  *
11128  *     sdioctl(9E)     sdstrategy(9E)         biodone(9F)
11129  *         |                |                     ^
11130  *         v                v                     |
11131  * sd_send_scsi_cmd()  ddi_xbuf_qstrategy()       +-------------------+
11132  *         |                |                     |                   |
11133  *         v                |                     |                   |
11134  * sd_uscsi_strategy() sd_xbuf_strategy()   sd_buf_iodone()   sd_uscsi_iodone()
11135  *         |                |                     ^                   ^
11136  *         v                v                     |                   |
11137  * SD_BEGIN_IOSTART()  SD_BEGIN_IOSTART()         |                   |
11138  *         |                |                     |                   |
11139  *     +---+                |                     +------------+      +-------+
11140  *     |                    |                                  |              |
11141  *     |   SD_NEXT_IOSTART()|                  SD_NEXT_IODONE()|              |
11142  *     |                    v                                  |              |
11143  *     |         sd_mapblockaddr_iostart()           sd_mapblockaddr_iodone() |
11144  *     |                    |                                  ^              |
11145  *     |   SD_NEXT_IOSTART()|                  SD_NEXT_IODONE()|              |
11146  *     |                    v                                  |              |
11147  *     |         sd_mapblocksize_iostart()           sd_mapblocksize_iodone() |
11148  *     |                    |                                  ^              |
11149  *     |   SD_NEXT_IOSTART()|                  SD_NEXT_IODONE()|              |
11150  *     |                    v                                  |              |
11151  *     |           sd_checksum_iostart()               sd_checksum_iodone()   |
11152  *     |                    |                                  ^              |
11153  *     +-> SD_NEXT_IOSTART()|                  SD_NEXT_IODONE()+------------->+
11154  *     |                    v                                  |              |
11155  *     |              sd_pm_iostart()                     sd_pm_iodone()      |
11156  *     |                    |                                  ^              |
11157  *     |                    |                                  |              |
11158  *     +-> SD_NEXT_IOSTART()|               SD_BEGIN_IODONE()--+--------------+
11159  *                          |                           ^
11160  *                          v                           |
11161  *                   sd_core_iostart()                  |
11162  *                          |                           |
11163  *                          |                           +------>(*destroypkt)()
11164  *                          +-> sd_start_cmds() <-+     |           |
11165  *                          |                     |     |           v
11166  *                          |                     |     |  scsi_destroy_pkt(9F)
11167  *                          |                     |     |
11168  *                          +->(*initpkt)()       +- sdintr()
11169  *                          |  |                        |  |
11170  *                          |  +-> scsi_init_pkt(9F)    |  +-> sd_handle_xxx()
11171  *                          |  +-> scsi_setup_cdb(9F)   |
11172  *                          |                           |
11173  *                          +--> scsi_transport(9F)     |
11174  *                                     |                |
11175  *                                     +----> SCSA ---->+
11176  *
11177  *
11178  * This code is based upon the following presumptions:
11179  *
11180  *   - iostart and iodone functions operate on buf(9S) structures. These
11181  *     functions perform the necessary operations on the buf(9S) and pass
11182  *     them along to the next function in the chain by using the macros
11183  *     SD_NEXT_IOSTART() (for iostart side functions) and SD_NEXT_IODONE()
11184  *     (for iodone side functions).
11185  *
11186  *   - The iostart side functions may sleep. The iodone side functions
11187  *     are called under interrupt context and may NOT sleep. Therefore
11188  *     iodone side functions also may not call iostart side functions.
11189  *     (NOTE: iostart side functions should NOT sleep for memory, as
11190  *     this could result in deadlock.)
11191  *
11192  *   - An iostart side function may call its corresponding iodone side
11193  *     function directly (if necessary).
11194  *
11195  *   - In the event of an error, an iostart side function can return a buf(9S)
11196  *     to its caller by calling SD_BEGIN_IODONE() (after setting B_ERROR and
11197  *     b_error in the usual way of course).
11198  *
11199  *   - The taskq mechanism may be used by the iodone side functions to dispatch
11200  *     requests to the iostart side functions.  The iostart side functions in
11201  *     this case would be called under the context of a taskq thread, so it's
11202  *     OK for them to block/sleep/spin in this case.
11203  *
11204  *   - iostart side functions may allocate "shadow" buf(9S) structs and
11205  *     pass them along to the next function in the chain.  The corresponding
11206  *     iodone side functions must coalesce the "shadow" bufs and return
11207  *     the "original" buf to the next higher layer.
11208  *
11209  *   - The b_private field of the buf(9S) struct holds a pointer to
11210  *     an sd_xbuf struct, which contains information needed to
11211  *     construct the scsi_pkt for the command.
11212  *
11213  *   - The SD_MUTEX(un) is NOT held across calls to the next layer. Each
11214  *     layer must acquire & release the SD_MUTEX(un) as needed.
11215  */
11216 
11217 
11218 /*
11219  * Create taskq for all targets in the system. This is created at
11220  * _init(9E) and destroyed at _fini(9E).
11221  *
11222  * Note: here we set the minalloc to a reasonably high number to ensure that
11223  * we will have an adequate supply of task entries available at interrupt time.
11224  * This is used in conjunction with the TASKQ_PREPOPULATE flag in
11225  * sd_create_taskq().  Since we do not want to sleep for allocations at
11226  * interrupt time, set maxalloc equal to minalloc. That way we will just fail
11227  * the command if we ever try to dispatch more than SD_TASKQ_MAXALLOC taskq
11228  * requests any one instant in time.
11229  */
11230 #define	SD_TASKQ_NUMTHREADS	8
11231 #define	SD_TASKQ_MINALLOC	256
11232 #define	SD_TASKQ_MAXALLOC	256
11233 
11234 static taskq_t	*sd_tq = NULL;
11235 _NOTE(SCHEME_PROTECTS_DATA("stable data", sd_tq))
11236 
11237 static int	sd_taskq_minalloc = SD_TASKQ_MINALLOC;
11238 static int	sd_taskq_maxalloc = SD_TASKQ_MAXALLOC;
11239 
11240 /*
11241  * The following task queue is being created for the write part of
11242  * read-modify-write of non-512 block size devices.
11243  * Limit the number of threads to 1 for now. This number has been chosen
11244  * considering the fact that it applies only to dvd ram drives/MO drives
11245  * currently. Performance for which is not main criteria at this stage.
11246  * Note: It needs to be explored if we can use a single taskq in future
11247  */
11248 #define	SD_WMR_TASKQ_NUMTHREADS	1
11249 static taskq_t	*sd_wmr_tq = NULL;
11250 _NOTE(SCHEME_PROTECTS_DATA("stable data", sd_wmr_tq))
11251 
11252 /*
11253  *    Function: sd_taskq_create
11254  *
11255  * Description: Create taskq thread(s) and preallocate task entries
11256  *
11257  * Return Code: Returns a pointer to the allocated taskq_t.
11258  *
11259  *     Context: Can sleep. Requires blockable context.
11260  *
11261  *       Notes: - The taskq() facility currently is NOT part of the DDI.
11262  *		  (definitely NOT recommeded for 3rd-party drivers!) :-)
11263  *		- taskq_create() will block for memory, also it will panic
11264  *		  if it cannot create the requested number of threads.
11265  *		- Currently taskq_create() creates threads that cannot be
11266  *		  swapped.
11267  *		- We use TASKQ_PREPOPULATE to ensure we have an adequate
11268  *		  supply of taskq entries at interrupt time (ie, so that we
11269  *		  do not have to sleep for memory)
11270  */
11271 
11272 static void
11273 sd_taskq_create(void)
11274 {
11275 	char	taskq_name[TASKQ_NAMELEN];
11276 
11277 	ASSERT(sd_tq == NULL);
11278 	ASSERT(sd_wmr_tq == NULL);
11279 
11280 	(void) snprintf(taskq_name, sizeof (taskq_name),
11281 	    "%s_drv_taskq", sd_label);
11282 	sd_tq = (taskq_create(taskq_name, SD_TASKQ_NUMTHREADS,
11283 	    (v.v_maxsyspri - 2), sd_taskq_minalloc, sd_taskq_maxalloc,
11284 	    TASKQ_PREPOPULATE));
11285 
11286 	(void) snprintf(taskq_name, sizeof (taskq_name),
11287 	    "%s_rmw_taskq", sd_label);
11288 	sd_wmr_tq = (taskq_create(taskq_name, SD_WMR_TASKQ_NUMTHREADS,
11289 	    (v.v_maxsyspri - 2), sd_taskq_minalloc, sd_taskq_maxalloc,
11290 	    TASKQ_PREPOPULATE));
11291 }
11292 
11293 
11294 /*
11295  *    Function: sd_taskq_delete
11296  *
11297  * Description: Complementary cleanup routine for sd_taskq_create().
11298  *
11299  *     Context: Kernel thread context.
11300  */
11301 
11302 static void
11303 sd_taskq_delete(void)
11304 {
11305 	ASSERT(sd_tq != NULL);
11306 	ASSERT(sd_wmr_tq != NULL);
11307 	taskq_destroy(sd_tq);
11308 	taskq_destroy(sd_wmr_tq);
11309 	sd_tq = NULL;
11310 	sd_wmr_tq = NULL;
11311 }
11312 
11313 
11314 /*
11315  *    Function: sdstrategy
11316  *
11317  * Description: Driver's strategy (9E) entry point function.
11318  *
11319  *   Arguments: bp - pointer to buf(9S)
11320  *
11321  * Return Code: Always returns zero
11322  *
11323  *     Context: Kernel thread context.
11324  */
11325 
11326 static int
11327 sdstrategy(struct buf *bp)
11328 {
11329 	struct sd_lun *un;
11330 
11331 	un = ddi_get_soft_state(sd_state, SD_GET_INSTANCE_FROM_BUF(bp));
11332 	if (un == NULL) {
11333 		bioerror(bp, EIO);
11334 		bp->b_resid = bp->b_bcount;
11335 		biodone(bp);
11336 		return (0);
11337 	}
11338 
11339 	/* As was done in the past, fail new cmds. if state is dumping. */
11340 	if (un->un_state == SD_STATE_DUMPING) {
11341 		bioerror(bp, ENXIO);
11342 		bp->b_resid = bp->b_bcount;
11343 		biodone(bp);
11344 		return (0);
11345 	}
11346 
11347 	ASSERT(!mutex_owned(SD_MUTEX(un)));
11348 
11349 	/*
11350 	 * Commands may sneak in while we released the mutex in
11351 	 * DDI_SUSPEND, we should block new commands. However, old
11352 	 * commands that are still in the driver at this point should
11353 	 * still be allowed to drain.
11354 	 */
11355 	mutex_enter(SD_MUTEX(un));
11356 	/*
11357 	 * Must wait here if either the device is suspended or
11358 	 * if it's power level is changing.
11359 	 */
11360 	while ((un->un_state == SD_STATE_SUSPENDED) ||
11361 	    (un->un_state == SD_STATE_PM_CHANGING)) {
11362 		cv_wait(&un->un_suspend_cv, SD_MUTEX(un));
11363 	}
11364 
11365 	un->un_ncmds_in_driver++;
11366 
11367 	/*
11368 	 * atapi: Since we are running the CD for now in PIO mode we need to
11369 	 * call bp_mapin here to avoid bp_mapin called interrupt context under
11370 	 * the HBA's init_pkt routine.
11371 	 */
11372 	if (un->un_f_cfg_is_atapi == TRUE) {
11373 		mutex_exit(SD_MUTEX(un));
11374 		bp_mapin(bp);
11375 		mutex_enter(SD_MUTEX(un));
11376 	}
11377 	SD_INFO(SD_LOG_IO, un, "sdstrategy: un_ncmds_in_driver = %ld\n",
11378 	    un->un_ncmds_in_driver);
11379 
11380 	if (bp->b_flags & B_WRITE)
11381 		un->un_f_sync_cache_required = TRUE;
11382 
11383 	mutex_exit(SD_MUTEX(un));
11384 
11385 	/*
11386 	 * This will (eventually) allocate the sd_xbuf area and
11387 	 * call sd_xbuf_strategy().  We just want to return the
11388 	 * result of ddi_xbuf_qstrategy so that we have an opt-
11389 	 * imized tail call which saves us a stack frame.
11390 	 */
11391 	return (ddi_xbuf_qstrategy(bp, un->un_xbuf_attr));
11392 }
11393 
11394 
11395 /*
11396  *    Function: sd_xbuf_strategy
11397  *
11398  * Description: Function for initiating IO operations via the
11399  *		ddi_xbuf_qstrategy() mechanism.
11400  *
11401  *     Context: Kernel thread context.
11402  */
11403 
11404 static void
11405 sd_xbuf_strategy(struct buf *bp, ddi_xbuf_t xp, void *arg)
11406 {
11407 	struct sd_lun *un = arg;
11408 
11409 	ASSERT(bp != NULL);
11410 	ASSERT(xp != NULL);
11411 	ASSERT(un != NULL);
11412 	ASSERT(!mutex_owned(SD_MUTEX(un)));
11413 
11414 	/*
11415 	 * Initialize the fields in the xbuf and save a pointer to the
11416 	 * xbuf in bp->b_private.
11417 	 */
11418 	sd_xbuf_init(un, bp, xp, SD_CHAIN_BUFIO, NULL);
11419 
11420 	/* Send the buf down the iostart chain */
11421 	SD_BEGIN_IOSTART(((struct sd_xbuf *)xp)->xb_chain_iostart, un, bp);
11422 }
11423 
11424 
11425 /*
11426  *    Function: sd_xbuf_init
11427  *
11428  * Description: Prepare the given sd_xbuf struct for use.
11429  *
11430  *   Arguments: un - ptr to softstate
11431  *		bp - ptr to associated buf(9S)
11432  *		xp - ptr to associated sd_xbuf
11433  *		chain_type - IO chain type to use:
11434  *			SD_CHAIN_NULL
11435  *			SD_CHAIN_BUFIO
11436  *			SD_CHAIN_USCSI
11437  *			SD_CHAIN_DIRECT
11438  *			SD_CHAIN_DIRECT_PRIORITY
11439  *		pktinfop - ptr to private data struct for scsi_pkt(9S)
11440  *			initialization; may be NULL if none.
11441  *
11442  *     Context: Kernel thread context
11443  */
11444 
11445 static void
11446 sd_xbuf_init(struct sd_lun *un, struct buf *bp, struct sd_xbuf *xp,
11447 	uchar_t chain_type, void *pktinfop)
11448 {
11449 	int index;
11450 
11451 	ASSERT(un != NULL);
11452 	ASSERT(bp != NULL);
11453 	ASSERT(xp != NULL);
11454 
11455 	SD_INFO(SD_LOG_IO, un, "sd_xbuf_init: buf:0x%p chain type:0x%x\n",
11456 	    bp, chain_type);
11457 
11458 	xp->xb_un	= un;
11459 	xp->xb_pktp	= NULL;
11460 	xp->xb_pktinfo	= pktinfop;
11461 	xp->xb_private	= bp->b_private;
11462 	xp->xb_blkno	= (daddr_t)bp->b_blkno;
11463 
11464 	/*
11465 	 * Set up the iostart and iodone chain indexes in the xbuf, based
11466 	 * upon the specified chain type to use.
11467 	 */
11468 	switch (chain_type) {
11469 	case SD_CHAIN_NULL:
11470 		/*
11471 		 * Fall thru to just use the values for the buf type, even
11472 		 * tho for the NULL chain these values will never be used.
11473 		 */
11474 		/* FALLTHRU */
11475 	case SD_CHAIN_BUFIO:
11476 		index = un->un_buf_chain_type;
11477 		if ((!un->un_f_has_removable_media) &&
11478 		    (un->un_tgt_blocksize != 0) &&
11479 		    (un->un_tgt_blocksize != DEV_BSIZE)) {
11480 			int secmask = 0, blknomask = 0;
11481 			blknomask =
11482 			    (un->un_tgt_blocksize / DEV_BSIZE) - 1;
11483 			secmask = un->un_tgt_blocksize - 1;
11484 
11485 			if ((bp->b_lblkno & (blknomask)) ||
11486 			    (bp->b_bcount & (secmask))) {
11487 				if (un->un_f_rmw_type !=
11488 				    SD_RMW_TYPE_RETURN_ERROR) {
11489 					if (un->un_f_pm_is_enabled == FALSE)
11490 						index =
11491 						    SD_CHAIN_INFO_MSS_DSK_NO_PM;
11492 					else
11493 						index =
11494 						    SD_CHAIN_INFO_MSS_DISK;
11495 				}
11496 			}
11497 		}
11498 		break;
11499 	case SD_CHAIN_USCSI:
11500 		index = un->un_uscsi_chain_type;
11501 		break;
11502 	case SD_CHAIN_DIRECT:
11503 		index = un->un_direct_chain_type;
11504 		break;
11505 	case SD_CHAIN_DIRECT_PRIORITY:
11506 		index = un->un_priority_chain_type;
11507 		break;
11508 	default:
11509 		/* We're really broken if we ever get here... */
11510 		panic("sd_xbuf_init: illegal chain type!");
11511 		/*NOTREACHED*/
11512 	}
11513 
11514 	xp->xb_chain_iostart = sd_chain_index_map[index].sci_iostart_index;
11515 	xp->xb_chain_iodone = sd_chain_index_map[index].sci_iodone_index;
11516 
11517 	/*
11518 	 * It might be a bit easier to simply bzero the entire xbuf above,
11519 	 * but it turns out that since we init a fair number of members anyway,
11520 	 * we save a fair number cycles by doing explicit assignment of zero.
11521 	 */
11522 	xp->xb_pkt_flags	= 0;
11523 	xp->xb_dma_resid	= 0;
11524 	xp->xb_retry_count	= 0;
11525 	xp->xb_victim_retry_count = 0;
11526 	xp->xb_ua_retry_count	= 0;
11527 	xp->xb_nr_retry_count	= 0;
11528 	xp->xb_sense_bp		= NULL;
11529 	xp->xb_sense_status	= 0;
11530 	xp->xb_sense_state	= 0;
11531 	xp->xb_sense_resid	= 0;
11532 	xp->xb_ena		= 0;
11533 
11534 	bp->b_private	= xp;
11535 	bp->b_flags	&= ~(B_DONE | B_ERROR);
11536 	bp->b_resid	= 0;
11537 	bp->av_forw	= NULL;
11538 	bp->av_back	= NULL;
11539 	bioerror(bp, 0);
11540 
11541 	SD_INFO(SD_LOG_IO, un, "sd_xbuf_init: done.\n");
11542 }
11543 
11544 
11545 /*
11546  *    Function: sd_uscsi_strategy
11547  *
11548  * Description: Wrapper for calling into the USCSI chain via physio(9F)
11549  *
11550  *   Arguments: bp - buf struct ptr
11551  *
11552  * Return Code: Always returns 0
11553  *
11554  *     Context: Kernel thread context
11555  */
11556 
11557 static int
11558 sd_uscsi_strategy(struct buf *bp)
11559 {
11560 	struct sd_lun		*un;
11561 	struct sd_uscsi_info	*uip;
11562 	struct sd_xbuf		*xp;
11563 	uchar_t			chain_type;
11564 	uchar_t			cmd;
11565 
11566 	ASSERT(bp != NULL);
11567 
11568 	un = ddi_get_soft_state(sd_state, SD_GET_INSTANCE_FROM_BUF(bp));
11569 	if (un == NULL) {
11570 		bioerror(bp, EIO);
11571 		bp->b_resid = bp->b_bcount;
11572 		biodone(bp);
11573 		return (0);
11574 	}
11575 
11576 	ASSERT(!mutex_owned(SD_MUTEX(un)));
11577 
11578 	SD_TRACE(SD_LOG_IO, un, "sd_uscsi_strategy: entry: buf:0x%p\n", bp);
11579 
11580 	/*
11581 	 * A pointer to a struct sd_uscsi_info is expected in bp->b_private
11582 	 */
11583 	ASSERT(bp->b_private != NULL);
11584 	uip = (struct sd_uscsi_info *)bp->b_private;
11585 	cmd = ((struct uscsi_cmd *)(uip->ui_cmdp))->uscsi_cdb[0];
11586 
11587 	mutex_enter(SD_MUTEX(un));
11588 	/*
11589 	 * atapi: Since we are running the CD for now in PIO mode we need to
11590 	 * call bp_mapin here to avoid bp_mapin called interrupt context under
11591 	 * the HBA's init_pkt routine.
11592 	 */
11593 	if (un->un_f_cfg_is_atapi == TRUE) {
11594 		mutex_exit(SD_MUTEX(un));
11595 		bp_mapin(bp);
11596 		mutex_enter(SD_MUTEX(un));
11597 	}
11598 	un->un_ncmds_in_driver++;
11599 	SD_INFO(SD_LOG_IO, un, "sd_uscsi_strategy: un_ncmds_in_driver = %ld\n",
11600 	    un->un_ncmds_in_driver);
11601 
11602 	if ((bp->b_flags & B_WRITE) && (bp->b_bcount != 0) &&
11603 	    (cmd != SCMD_MODE_SELECT) && (cmd != SCMD_MODE_SELECT_G1))
11604 		un->un_f_sync_cache_required = TRUE;
11605 
11606 	mutex_exit(SD_MUTEX(un));
11607 
11608 	switch (uip->ui_flags) {
11609 	case SD_PATH_DIRECT:
11610 		chain_type = SD_CHAIN_DIRECT;
11611 		break;
11612 	case SD_PATH_DIRECT_PRIORITY:
11613 		chain_type = SD_CHAIN_DIRECT_PRIORITY;
11614 		break;
11615 	default:
11616 		chain_type = SD_CHAIN_USCSI;
11617 		break;
11618 	}
11619 
11620 	/*
11621 	 * We may allocate extra buf for external USCSI commands. If the
11622 	 * application asks for bigger than 20-byte sense data via USCSI,
11623 	 * SCSA layer will allocate 252 bytes sense buf for that command.
11624 	 */
11625 	if (((struct uscsi_cmd *)(uip->ui_cmdp))->uscsi_rqlen >
11626 	    SENSE_LENGTH) {
11627 		xp = kmem_zalloc(sizeof (struct sd_xbuf) - SENSE_LENGTH +
11628 		    MAX_SENSE_LENGTH, KM_SLEEP);
11629 	} else {
11630 		xp = kmem_zalloc(sizeof (struct sd_xbuf), KM_SLEEP);
11631 	}
11632 
11633 	sd_xbuf_init(un, bp, xp, chain_type, uip->ui_cmdp);
11634 
11635 	/* Use the index obtained within xbuf_init */
11636 	SD_BEGIN_IOSTART(xp->xb_chain_iostart, un, bp);
11637 
11638 	SD_TRACE(SD_LOG_IO, un, "sd_uscsi_strategy: exit: buf:0x%p\n", bp);
11639 
11640 	return (0);
11641 }
11642 
11643 /*
11644  *    Function: sd_send_scsi_cmd
11645  *
11646  * Description: Runs a USCSI command for user (when called thru sdioctl),
11647  *		or for the driver
11648  *
11649  *   Arguments: dev - the dev_t for the device
11650  *		incmd - ptr to a valid uscsi_cmd struct
11651  *		flag - bit flag, indicating open settings, 32/64 bit type
11652  *		dataspace - UIO_USERSPACE or UIO_SYSSPACE
11653  *		path_flag - SD_PATH_DIRECT to use the USCSI "direct" chain and
11654  *			the normal command waitq, or SD_PATH_DIRECT_PRIORITY
11655  *			to use the USCSI "direct" chain and bypass the normal
11656  *			command waitq.
11657  *
11658  * Return Code: 0 -  successful completion of the given command
11659  *		EIO - scsi_uscsi_handle_command() failed
11660  *		ENXIO  - soft state not found for specified dev
11661  *		EINVAL
11662  *		EFAULT - copyin/copyout error
11663  *		return code of scsi_uscsi_handle_command():
11664  *			EIO
11665  *			ENXIO
11666  *			EACCES
11667  *
11668  *     Context: Waits for command to complete. Can sleep.
11669  */
11670 
11671 static int
11672 sd_send_scsi_cmd(dev_t dev, struct uscsi_cmd *incmd, int flag,
11673 	enum uio_seg dataspace, int path_flag)
11674 {
11675 	struct sd_lun	*un;
11676 	sd_ssc_t	*ssc;
11677 	int		rval;
11678 
11679 	un = ddi_get_soft_state(sd_state, SDUNIT(dev));
11680 	if (un == NULL) {
11681 		return (ENXIO);
11682 	}
11683 
11684 	/*
11685 	 * Using sd_ssc_send to handle uscsi cmd
11686 	 */
11687 	ssc = sd_ssc_init(un);
11688 	rval = sd_ssc_send(ssc, incmd, flag, dataspace, path_flag);
11689 	sd_ssc_fini(ssc);
11690 
11691 	return (rval);
11692 }
11693 
11694 /*
11695  *    Function: sd_ssc_init
11696  *
11697  * Description: Uscsi end-user call this function to initialize necessary
11698  *              fields, such as uscsi_cmd and sd_uscsi_info struct.
11699  *
11700  *              The return value of sd_send_scsi_cmd will be treated as a
11701  *              fault in various conditions. Even it is not Zero, some
11702  *              callers may ignore the return value. That is to say, we can
11703  *              not make an accurate assessment in sdintr, since if a
11704  *              command is failed in sdintr it does not mean the caller of
11705  *              sd_send_scsi_cmd will treat it as a real failure.
11706  *
11707  *              To avoid printing too many error logs for a failed uscsi
11708  *              packet that the caller may not treat it as a failure, the
11709  *              sd will keep silent for handling all uscsi commands.
11710  *
11711  *              During detach->attach and attach-open, for some types of
11712  *              problems, the driver should be providing information about
11713  *              the problem encountered. Device use USCSI_SILENT, which
11714  *              suppresses all driver information. The result is that no
11715  *              information about the problem is available. Being
11716  *              completely silent during this time is inappropriate. The
11717  *              driver needs a more selective filter than USCSI_SILENT, so
11718  *              that information related to faults is provided.
11719  *
11720  *              To make the accurate accessment, the caller  of
11721  *              sd_send_scsi_USCSI_CMD should take the ownership and
11722  *              get necessary information to print error messages.
11723  *
11724  *              If we want to print necessary info of uscsi command, we need to
11725  *              keep the uscsi_cmd and sd_uscsi_info till we can make the
11726  *              assessment. We use sd_ssc_init to alloc necessary
11727  *              structs for sending an uscsi command and we are also
11728  *              responsible for free the memory by calling
11729  *              sd_ssc_fini.
11730  *
11731  *              The calling secquences will look like:
11732  *              sd_ssc_init->
11733  *
11734  *                  ...
11735  *
11736  *                  sd_send_scsi_USCSI_CMD->
11737  *                      sd_ssc_send-> - - - sdintr
11738  *                  ...
11739  *
11740  *                  if we think the return value should be treated as a
11741  *                  failure, we make the accessment here and print out
11742  *                  necessary by retrieving uscsi_cmd and sd_uscsi_info'
11743  *
11744  *                  ...
11745  *
11746  *              sd_ssc_fini
11747  *
11748  *
11749  *   Arguments: un - pointer to driver soft state (unit) structure for this
11750  *                   target.
11751  *
11752  * Return code: sd_ssc_t - pointer to allocated sd_ssc_t struct, it contains
11753  *                         uscsi_cmd and sd_uscsi_info.
11754  *                  NULL - if can not alloc memory for sd_ssc_t struct
11755  *
11756  *     Context: Kernel Thread.
11757  */
11758 static sd_ssc_t *
11759 sd_ssc_init(struct sd_lun *un)
11760 {
11761 	sd_ssc_t		*ssc;
11762 	struct uscsi_cmd	*ucmdp;
11763 	struct sd_uscsi_info	*uip;
11764 
11765 	ASSERT(un != NULL);
11766 	ASSERT(!mutex_owned(SD_MUTEX(un)));
11767 
11768 	/*
11769 	 * Allocate sd_ssc_t structure
11770 	 */
11771 	ssc = kmem_zalloc(sizeof (sd_ssc_t), KM_SLEEP);
11772 
11773 	/*
11774 	 * Allocate uscsi_cmd by calling scsi_uscsi_alloc common routine
11775 	 */
11776 	ucmdp = scsi_uscsi_alloc();
11777 
11778 	/*
11779 	 * Allocate sd_uscsi_info structure
11780 	 */
11781 	uip = kmem_zalloc(sizeof (struct sd_uscsi_info), KM_SLEEP);
11782 
11783 	ssc->ssc_uscsi_cmd = ucmdp;
11784 	ssc->ssc_uscsi_info = uip;
11785 	ssc->ssc_un = un;
11786 
11787 	return (ssc);
11788 }
11789 
11790 /*
11791  * Function: sd_ssc_fini
11792  *
11793  * Description: To free sd_ssc_t and it's hanging off
11794  *
11795  * Arguments: ssc - struct pointer of sd_ssc_t.
11796  */
11797 static void
11798 sd_ssc_fini(sd_ssc_t *ssc)
11799 {
11800 	scsi_uscsi_free(ssc->ssc_uscsi_cmd);
11801 
11802 	if (ssc->ssc_uscsi_info != NULL) {
11803 		kmem_free(ssc->ssc_uscsi_info, sizeof (struct sd_uscsi_info));
11804 		ssc->ssc_uscsi_info = NULL;
11805 	}
11806 
11807 	kmem_free(ssc, sizeof (sd_ssc_t));
11808 	ssc = NULL;
11809 }
11810 
11811 /*
11812  * Function: sd_ssc_send
11813  *
11814  * Description: Runs a USCSI command for user when called through sdioctl,
11815  *              or for the driver.
11816  *
11817  *   Arguments: ssc - the struct of sd_ssc_t will bring uscsi_cmd and
11818  *                    sd_uscsi_info in.
11819  *		incmd - ptr to a valid uscsi_cmd struct
11820  *		flag - bit flag, indicating open settings, 32/64 bit type
11821  *		dataspace - UIO_USERSPACE or UIO_SYSSPACE
11822  *		path_flag - SD_PATH_DIRECT to use the USCSI "direct" chain and
11823  *			the normal command waitq, or SD_PATH_DIRECT_PRIORITY
11824  *			to use the USCSI "direct" chain and bypass the normal
11825  *			command waitq.
11826  *
11827  * Return Code: 0 -  successful completion of the given command
11828  *		EIO - scsi_uscsi_handle_command() failed
11829  *		ENXIO  - soft state not found for specified dev
11830  *		ECANCELED - command cancelled due to low power
11831  *		EINVAL
11832  *		EFAULT - copyin/copyout error
11833  *		return code of scsi_uscsi_handle_command():
11834  *			EIO
11835  *			ENXIO
11836  *			EACCES
11837  *
11838  *     Context: Kernel Thread;
11839  *              Waits for command to complete. Can sleep.
11840  */
11841 static int
11842 sd_ssc_send(sd_ssc_t *ssc, struct uscsi_cmd *incmd, int flag,
11843 	enum uio_seg dataspace, int path_flag)
11844 {
11845 	struct sd_uscsi_info	*uip;
11846 	struct uscsi_cmd	*uscmd;
11847 	struct sd_lun		*un;
11848 	dev_t			dev;
11849 
11850 	int	format = 0;
11851 	int	rval;
11852 
11853 	ASSERT(ssc != NULL);
11854 	un = ssc->ssc_un;
11855 	ASSERT(un != NULL);
11856 	uscmd = ssc->ssc_uscsi_cmd;
11857 	ASSERT(uscmd != NULL);
11858 	ASSERT(!mutex_owned(SD_MUTEX(un)));
11859 	if (ssc->ssc_flags & SSC_FLAGS_NEED_ASSESSMENT) {
11860 		/*
11861 		 * If enter here, it indicates that the previous uscsi
11862 		 * command has not been processed by sd_ssc_assessment.
11863 		 * This is violating our rules of FMA telemetry processing.
11864 		 * We should print out this message and the last undisposed
11865 		 * uscsi command.
11866 		 */
11867 		if (uscmd->uscsi_cdb != NULL) {
11868 			SD_INFO(SD_LOG_SDTEST, un,
11869 			    "sd_ssc_send is missing the alternative "
11870 			    "sd_ssc_assessment when running command 0x%x.\n",
11871 			    uscmd->uscsi_cdb[0]);
11872 		}
11873 		/*
11874 		 * Set the ssc_flags to SSC_FLAGS_UNKNOWN, which should be
11875 		 * the initial status.
11876 		 */
11877 		ssc->ssc_flags = SSC_FLAGS_UNKNOWN;
11878 	}
11879 
11880 	/*
11881 	 * We need to make sure sd_ssc_send will have sd_ssc_assessment
11882 	 * followed to avoid missing FMA telemetries.
11883 	 */
11884 	ssc->ssc_flags |= SSC_FLAGS_NEED_ASSESSMENT;
11885 
11886 	/*
11887 	 * if USCSI_PMFAILFAST is set and un is in low power, fail the
11888 	 * command immediately.
11889 	 */
11890 	mutex_enter(SD_MUTEX(un));
11891 	mutex_enter(&un->un_pm_mutex);
11892 	if ((uscmd->uscsi_flags & USCSI_PMFAILFAST) &&
11893 	    SD_DEVICE_IS_IN_LOW_POWER(un)) {
11894 		SD_TRACE(SD_LOG_IO, un, "sd_ssc_send:"
11895 		    "un:0x%p is in low power\n", un);
11896 		mutex_exit(&un->un_pm_mutex);
11897 		mutex_exit(SD_MUTEX(un));
11898 		return (ECANCELED);
11899 	}
11900 	mutex_exit(&un->un_pm_mutex);
11901 	mutex_exit(SD_MUTEX(un));
11902 
11903 #ifdef SDDEBUG
11904 	switch (dataspace) {
11905 	case UIO_USERSPACE:
11906 		SD_TRACE(SD_LOG_IO, un,
11907 		    "sd_ssc_send: entry: un:0x%p UIO_USERSPACE\n", un);
11908 		break;
11909 	case UIO_SYSSPACE:
11910 		SD_TRACE(SD_LOG_IO, un,
11911 		    "sd_ssc_send: entry: un:0x%p UIO_SYSSPACE\n", un);
11912 		break;
11913 	default:
11914 		SD_TRACE(SD_LOG_IO, un,
11915 		    "sd_ssc_send: entry: un:0x%p UNEXPECTED SPACE\n", un);
11916 		break;
11917 	}
11918 #endif
11919 
11920 	rval = scsi_uscsi_copyin((intptr_t)incmd, flag,
11921 	    SD_ADDRESS(un), &uscmd);
11922 	if (rval != 0) {
11923 		SD_TRACE(SD_LOG_IO, un, "sd_sense_scsi_cmd: "
11924 		    "scsi_uscsi_alloc_and_copyin failed\n", un);
11925 		return (rval);
11926 	}
11927 
11928 	if ((uscmd->uscsi_cdb != NULL) &&
11929 	    (uscmd->uscsi_cdb[0] == SCMD_FORMAT)) {
11930 		mutex_enter(SD_MUTEX(un));
11931 		un->un_f_format_in_progress = TRUE;
11932 		mutex_exit(SD_MUTEX(un));
11933 		format = 1;
11934 	}
11935 
11936 	/*
11937 	 * Allocate an sd_uscsi_info struct and fill it with the info
11938 	 * needed by sd_initpkt_for_uscsi().  Then put the pointer into
11939 	 * b_private in the buf for sd_initpkt_for_uscsi().  Note that
11940 	 * since we allocate the buf here in this function, we do not
11941 	 * need to preserve the prior contents of b_private.
11942 	 * The sd_uscsi_info struct is also used by sd_uscsi_strategy()
11943 	 */
11944 	uip = ssc->ssc_uscsi_info;
11945 	uip->ui_flags = path_flag;
11946 	uip->ui_cmdp = uscmd;
11947 
11948 	/*
11949 	 * Commands sent with priority are intended for error recovery
11950 	 * situations, and do not have retries performed.
11951 	 */
11952 	if (path_flag == SD_PATH_DIRECT_PRIORITY) {
11953 		uscmd->uscsi_flags |= USCSI_DIAGNOSE;
11954 	}
11955 	uscmd->uscsi_flags &= ~USCSI_NOINTR;
11956 
11957 	dev = SD_GET_DEV(un);
11958 	rval = scsi_uscsi_handle_cmd(dev, dataspace, uscmd,
11959 	    sd_uscsi_strategy, NULL, uip);
11960 
11961 	/*
11962 	 * mark ssc_flags right after handle_cmd to make sure
11963 	 * the uscsi has been sent
11964 	 */
11965 	ssc->ssc_flags |= SSC_FLAGS_CMD_ISSUED;
11966 
11967 #ifdef SDDEBUG
11968 	SD_INFO(SD_LOG_IO, un, "sd_ssc_send: "
11969 	    "uscsi_status: 0x%02x  uscsi_resid:0x%x\n",
11970 	    uscmd->uscsi_status, uscmd->uscsi_resid);
11971 	if (uscmd->uscsi_bufaddr != NULL) {
11972 		SD_INFO(SD_LOG_IO, un, "sd_ssc_send: "
11973 		    "uscmd->uscsi_bufaddr: 0x%p  uscmd->uscsi_buflen:%d\n",
11974 		    uscmd->uscsi_bufaddr, uscmd->uscsi_buflen);
11975 		if (dataspace == UIO_SYSSPACE) {
11976 			SD_DUMP_MEMORY(un, SD_LOG_IO,
11977 			    "data", (uchar_t *)uscmd->uscsi_bufaddr,
11978 			    uscmd->uscsi_buflen, SD_LOG_HEX);
11979 		}
11980 	}
11981 #endif
11982 
11983 	if (format == 1) {
11984 		mutex_enter(SD_MUTEX(un));
11985 		un->un_f_format_in_progress = FALSE;
11986 		mutex_exit(SD_MUTEX(un));
11987 	}
11988 
11989 	(void) scsi_uscsi_copyout((intptr_t)incmd, uscmd);
11990 
11991 	return (rval);
11992 }
11993 
11994 /*
11995  *     Function: sd_ssc_print
11996  *
11997  * Description: Print information available to the console.
11998  *
11999  * Arguments: ssc - the struct of sd_ssc_t will bring uscsi_cmd and
12000  *                    sd_uscsi_info in.
12001  *            sd_severity - log level.
12002  *     Context: Kernel thread or interrupt context.
12003  */
12004 static void
12005 sd_ssc_print(sd_ssc_t *ssc, int sd_severity)
12006 {
12007 	struct uscsi_cmd	*ucmdp;
12008 	struct scsi_device	*devp;
12009 	dev_info_t 		*devinfo;
12010 	uchar_t			*sensep;
12011 	int			senlen;
12012 	union scsi_cdb		*cdbp;
12013 	uchar_t			com;
12014 	extern struct scsi_key_strings scsi_cmds[];
12015 
12016 	ASSERT(ssc != NULL);
12017 	ASSERT(ssc->ssc_un != NULL);
12018 
12019 	if (SD_FM_LOG(ssc->ssc_un) != SD_FM_LOG_EREPORT)
12020 		return;
12021 	ucmdp = ssc->ssc_uscsi_cmd;
12022 	devp = SD_SCSI_DEVP(ssc->ssc_un);
12023 	devinfo = SD_DEVINFO(ssc->ssc_un);
12024 	ASSERT(ucmdp != NULL);
12025 	ASSERT(devp != NULL);
12026 	ASSERT(devinfo != NULL);
12027 	sensep = (uint8_t *)ucmdp->uscsi_rqbuf;
12028 	senlen = ucmdp->uscsi_rqlen - ucmdp->uscsi_rqresid;
12029 	cdbp = (union scsi_cdb *)ucmdp->uscsi_cdb;
12030 
12031 	/* In certain case (like DOORLOCK), the cdb could be NULL. */
12032 	if (cdbp == NULL)
12033 		return;
12034 	/* We don't print log if no sense data available. */
12035 	if (senlen == 0)
12036 		sensep = NULL;
12037 	com = cdbp->scc_cmd;
12038 	scsi_generic_errmsg(devp, sd_label, sd_severity, 0, 0, com,
12039 	    scsi_cmds, sensep, ssc->ssc_un->un_additional_codes, NULL);
12040 }
12041 
12042 /*
12043  *     Function: sd_ssc_assessment
12044  *
12045  * Description: We use this function to make an assessment at the point
12046  *              where SD driver may encounter a potential error.
12047  *
12048  * Arguments: ssc - the struct of sd_ssc_t will bring uscsi_cmd and
12049  *                  sd_uscsi_info in.
12050  *            tp_assess - a hint of strategy for ereport posting.
12051  *            Possible values of tp_assess include:
12052  *                SD_FMT_IGNORE - we don't post any ereport because we're
12053  *                sure that it is ok to ignore the underlying problems.
12054  *                SD_FMT_IGNORE_COMPROMISE - we don't post any ereport for now
12055  *                but it might be not correct to ignore the underlying hardware
12056  *                error.
12057  *                SD_FMT_STATUS_CHECK - we will post an ereport with the
12058  *                payload driver-assessment of value "fail" or
12059  *                "fatal"(depending on what information we have here). This
12060  *                assessment value is usually set when SD driver think there
12061  *                is a potential error occurred(Typically, when return value
12062  *                of the SCSI command is EIO).
12063  *                SD_FMT_STANDARD - we will post an ereport with the payload
12064  *                driver-assessment of value "info". This assessment value is
12065  *                set when the SCSI command returned successfully and with
12066  *                sense data sent back.
12067  *
12068  *     Context: Kernel thread.
12069  */
12070 static void
12071 sd_ssc_assessment(sd_ssc_t *ssc, enum sd_type_assessment tp_assess)
12072 {
12073 	int senlen = 0;
12074 	struct uscsi_cmd *ucmdp = NULL;
12075 	struct sd_lun *un;
12076 
12077 	ASSERT(ssc != NULL);
12078 	un = ssc->ssc_un;
12079 	ASSERT(un != NULL);
12080 	ucmdp = ssc->ssc_uscsi_cmd;
12081 	ASSERT(ucmdp != NULL);
12082 
12083 	if (ssc->ssc_flags & SSC_FLAGS_NEED_ASSESSMENT) {
12084 		ssc->ssc_flags &= ~SSC_FLAGS_NEED_ASSESSMENT;
12085 	} else {
12086 		/*
12087 		 * If enter here, it indicates that we have a wrong
12088 		 * calling sequence of sd_ssc_send and sd_ssc_assessment,
12089 		 * both of which should be called in a pair in case of
12090 		 * loss of FMA telemetries.
12091 		 */
12092 		if (ucmdp->uscsi_cdb != NULL) {
12093 			SD_INFO(SD_LOG_SDTEST, un,
12094 			    "sd_ssc_assessment is missing the "
12095 			    "alternative sd_ssc_send when running 0x%x, "
12096 			    "or there are superfluous sd_ssc_assessment for "
12097 			    "the same sd_ssc_send.\n",
12098 			    ucmdp->uscsi_cdb[0]);
12099 		}
12100 		/*
12101 		 * Set the ssc_flags to the initial value to avoid passing
12102 		 * down dirty flags to the following sd_ssc_send function.
12103 		 */
12104 		ssc->ssc_flags = SSC_FLAGS_UNKNOWN;
12105 		return;
12106 	}
12107 
12108 	/*
12109 	 * Only handle an issued command which is waiting for assessment.
12110 	 * A command which is not issued will not have
12111 	 * SSC_FLAGS_INVALID_DATA set, so it'ok we just return here.
12112 	 */
12113 	if (!(ssc->ssc_flags & SSC_FLAGS_CMD_ISSUED)) {
12114 		sd_ssc_print(ssc, SCSI_ERR_INFO);
12115 		return;
12116 	} else {
12117 		/*
12118 		 * For an issued command, we should clear this flag in
12119 		 * order to make the sd_ssc_t structure be used off
12120 		 * multiple uscsi commands.
12121 		 */
12122 		ssc->ssc_flags &= ~SSC_FLAGS_CMD_ISSUED;
12123 	}
12124 
12125 	/*
12126 	 * We will not deal with non-retryable(flag USCSI_DIAGNOSE set)
12127 	 * commands here. And we should clear the ssc_flags before return.
12128 	 */
12129 	if (ucmdp->uscsi_flags & USCSI_DIAGNOSE) {
12130 		ssc->ssc_flags = SSC_FLAGS_UNKNOWN;
12131 		return;
12132 	}
12133 
12134 	switch (tp_assess) {
12135 	case SD_FMT_IGNORE:
12136 	case SD_FMT_IGNORE_COMPROMISE:
12137 		break;
12138 	case SD_FMT_STATUS_CHECK:
12139 		/*
12140 		 * For a failed command(including the succeeded command
12141 		 * with invalid data sent back).
12142 		 */
12143 		sd_ssc_post(ssc, SD_FM_DRV_FATAL);
12144 		break;
12145 	case SD_FMT_STANDARD:
12146 		/*
12147 		 * Always for the succeeded commands probably with sense
12148 		 * data sent back.
12149 		 * Limitation:
12150 		 *	We can only handle a succeeded command with sense
12151 		 *	data sent back when auto-request-sense is enabled.
12152 		 */
12153 		senlen = ssc->ssc_uscsi_cmd->uscsi_rqlen -
12154 		    ssc->ssc_uscsi_cmd->uscsi_rqresid;
12155 		if ((ssc->ssc_uscsi_info->ui_pkt_state & STATE_ARQ_DONE) &&
12156 		    (un->un_f_arq_enabled == TRUE) &&
12157 		    senlen > 0 &&
12158 		    ssc->ssc_uscsi_cmd->uscsi_rqbuf != NULL) {
12159 			sd_ssc_post(ssc, SD_FM_DRV_NOTICE);
12160 		}
12161 		break;
12162 	default:
12163 		/*
12164 		 * Should not have other type of assessment.
12165 		 */
12166 		scsi_log(SD_DEVINFO(un), sd_label, CE_CONT,
12167 		    "sd_ssc_assessment got wrong "
12168 		    "sd_type_assessment %d.\n", tp_assess);
12169 		break;
12170 	}
12171 	/*
12172 	 * Clear up the ssc_flags before return.
12173 	 */
12174 	ssc->ssc_flags = SSC_FLAGS_UNKNOWN;
12175 }
12176 
12177 /*
12178  *    Function: sd_ssc_post
12179  *
12180  * Description: 1. read the driver property to get fm-scsi-log flag.
12181  *              2. print log if fm_log_capable is non-zero.
12182  *              3. call sd_ssc_ereport_post to post ereport if possible.
12183  *
12184  *    Context: May be called from kernel thread or interrupt context.
12185  */
12186 static void
12187 sd_ssc_post(sd_ssc_t *ssc, enum sd_driver_assessment sd_assess)
12188 {
12189 	struct sd_lun	*un;
12190 	int		sd_severity;
12191 
12192 	ASSERT(ssc != NULL);
12193 	un = ssc->ssc_un;
12194 	ASSERT(un != NULL);
12195 
12196 	/*
12197 	 * We may enter here from sd_ssc_assessment(for USCSI command) or
12198 	 * by directly called from sdintr context.
12199 	 * We don't handle a non-disk drive(CD-ROM, removable media).
12200 	 * Clear the ssc_flags before return in case we've set
12201 	 * SSC_FLAGS_INVALID_XXX which should be skipped for a non-disk
12202 	 * driver.
12203 	 */
12204 	if (ISCD(un) || un->un_f_has_removable_media) {
12205 		ssc->ssc_flags = SSC_FLAGS_UNKNOWN;
12206 		return;
12207 	}
12208 
12209 	switch (sd_assess) {
12210 		case SD_FM_DRV_FATAL:
12211 			sd_severity = SCSI_ERR_FATAL;
12212 			break;
12213 		case SD_FM_DRV_RECOVERY:
12214 			sd_severity = SCSI_ERR_RECOVERED;
12215 			break;
12216 		case SD_FM_DRV_RETRY:
12217 			sd_severity = SCSI_ERR_RETRYABLE;
12218 			break;
12219 		case SD_FM_DRV_NOTICE:
12220 			sd_severity = SCSI_ERR_INFO;
12221 			break;
12222 		default:
12223 			sd_severity = SCSI_ERR_UNKNOWN;
12224 	}
12225 	/* print log */
12226 	sd_ssc_print(ssc, sd_severity);
12227 
12228 	/* always post ereport */
12229 	sd_ssc_ereport_post(ssc, sd_assess);
12230 }
12231 
12232 /*
12233  *    Function: sd_ssc_set_info
12234  *
12235  * Description: Mark ssc_flags and set ssc_info which would be the
12236  *              payload of uderr ereport. This function will cause
12237  *              sd_ssc_ereport_post to post uderr ereport only.
12238  *              Besides, when ssc_flags == SSC_FLAGS_INVALID_DATA(USCSI),
12239  *              the function will also call SD_ERROR or scsi_log for a
12240  *              CDROM/removable-media/DDI_FM_NOT_CAPABLE device.
12241  *
12242  * Arguments: ssc - the struct of sd_ssc_t will bring uscsi_cmd and
12243  *                  sd_uscsi_info in.
12244  *            ssc_flags - indicate the sub-category of a uderr.
12245  *            comp - this argument is meaningful only when
12246  *                   ssc_flags == SSC_FLAGS_INVALID_DATA, and its possible
12247  *                   values include:
12248  *                   > 0, SD_ERROR is used with comp as the driver logging
12249  *                   component;
12250  *                   = 0, scsi-log is used to log error telemetries;
12251  *                   < 0, no log available for this telemetry.
12252  *
12253  *    Context: Kernel thread or interrupt context
12254  */
12255 static void
12256 sd_ssc_set_info(sd_ssc_t *ssc, int ssc_flags, uint_t comp, const char *fmt, ...)
12257 {
12258 	va_list	ap;
12259 
12260 	ASSERT(ssc != NULL);
12261 	ASSERT(ssc->ssc_un != NULL);
12262 
12263 	ssc->ssc_flags |= ssc_flags;
12264 	va_start(ap, fmt);
12265 	(void) vsnprintf(ssc->ssc_info, sizeof (ssc->ssc_info), fmt, ap);
12266 	va_end(ap);
12267 
12268 	/*
12269 	 * If SSC_FLAGS_INVALID_DATA is set, it should be a uscsi command
12270 	 * with invalid data sent back. For non-uscsi command, the
12271 	 * following code will be bypassed.
12272 	 */
12273 	if (ssc_flags & SSC_FLAGS_INVALID_DATA) {
12274 		if (SD_FM_LOG(ssc->ssc_un) == SD_FM_LOG_NSUP) {
12275 			/*
12276 			 * If the error belong to certain component and we
12277 			 * do not want it to show up on the console, we
12278 			 * will use SD_ERROR, otherwise scsi_log is
12279 			 * preferred.
12280 			 */
12281 			if (comp > 0) {
12282 				SD_ERROR(comp, ssc->ssc_un, ssc->ssc_info);
12283 			} else if (comp == 0) {
12284 				scsi_log(SD_DEVINFO(ssc->ssc_un), sd_label,
12285 				    CE_WARN, ssc->ssc_info);
12286 			}
12287 		}
12288 	}
12289 }
12290 
12291 /*
12292  *    Function: sd_buf_iodone
12293  *
12294  * Description: Frees the sd_xbuf & returns the buf to its originator.
12295  *
12296  *     Context: May be called from interrupt context.
12297  */
12298 /* ARGSUSED */
12299 static void
12300 sd_buf_iodone(int index, struct sd_lun *un, struct buf *bp)
12301 {
12302 	struct sd_xbuf *xp;
12303 
12304 	ASSERT(un != NULL);
12305 	ASSERT(bp != NULL);
12306 	ASSERT(!mutex_owned(SD_MUTEX(un)));
12307 
12308 	SD_TRACE(SD_LOG_IO_CORE, un, "sd_buf_iodone: entry.\n");
12309 
12310 	xp = SD_GET_XBUF(bp);
12311 	ASSERT(xp != NULL);
12312 
12313 	/* xbuf is gone after this */
12314 	if (ddi_xbuf_done(bp, un->un_xbuf_attr)) {
12315 		mutex_enter(SD_MUTEX(un));
12316 
12317 		/*
12318 		 * Grab time when the cmd completed.
12319 		 * This is used for determining if the system has been
12320 		 * idle long enough to make it idle to the PM framework.
12321 		 * This is for lowering the overhead, and therefore improving
12322 		 * performance per I/O operation.
12323 		 */
12324 		un->un_pm_idle_time = ddi_get_time();
12325 
12326 		un->un_ncmds_in_driver--;
12327 		ASSERT(un->un_ncmds_in_driver >= 0);
12328 		SD_INFO(SD_LOG_IO, un,
12329 		    "sd_buf_iodone: un_ncmds_in_driver = %ld\n",
12330 		    un->un_ncmds_in_driver);
12331 
12332 		mutex_exit(SD_MUTEX(un));
12333 	}
12334 
12335 	biodone(bp);				/* bp is gone after this */
12336 
12337 	SD_TRACE(SD_LOG_IO_CORE, un, "sd_buf_iodone: exit.\n");
12338 }
12339 
12340 
12341 /*
12342  *    Function: sd_uscsi_iodone
12343  *
12344  * Description: Frees the sd_xbuf & returns the buf to its originator.
12345  *
12346  *     Context: May be called from interrupt context.
12347  */
12348 /* ARGSUSED */
12349 static void
12350 sd_uscsi_iodone(int index, struct sd_lun *un, struct buf *bp)
12351 {
12352 	struct sd_xbuf *xp;
12353 
12354 	ASSERT(un != NULL);
12355 	ASSERT(bp != NULL);
12356 
12357 	xp = SD_GET_XBUF(bp);
12358 	ASSERT(xp != NULL);
12359 	ASSERT(!mutex_owned(SD_MUTEX(un)));
12360 
12361 	SD_INFO(SD_LOG_IO, un, "sd_uscsi_iodone: entry.\n");
12362 
12363 	bp->b_private = xp->xb_private;
12364 
12365 	mutex_enter(SD_MUTEX(un));
12366 
12367 	/*
12368 	 * Grab time when the cmd completed.
12369 	 * This is used for determining if the system has been
12370 	 * idle long enough to make it idle to the PM framework.
12371 	 * This is for lowering the overhead, and therefore improving
12372 	 * performance per I/O operation.
12373 	 */
12374 	un->un_pm_idle_time = ddi_get_time();
12375 
12376 	un->un_ncmds_in_driver--;
12377 	ASSERT(un->un_ncmds_in_driver >= 0);
12378 	SD_INFO(SD_LOG_IO, un, "sd_uscsi_iodone: un_ncmds_in_driver = %ld\n",
12379 	    un->un_ncmds_in_driver);
12380 
12381 	mutex_exit(SD_MUTEX(un));
12382 
12383 	if (((struct uscsi_cmd *)(xp->xb_pktinfo))->uscsi_rqlen >
12384 	    SENSE_LENGTH) {
12385 		kmem_free(xp, sizeof (struct sd_xbuf) - SENSE_LENGTH +
12386 		    MAX_SENSE_LENGTH);
12387 	} else {
12388 		kmem_free(xp, sizeof (struct sd_xbuf));
12389 	}
12390 
12391 	biodone(bp);
12392 
12393 	SD_INFO(SD_LOG_IO, un, "sd_uscsi_iodone: exit.\n");
12394 }
12395 
12396 
12397 /*
12398  *    Function: sd_mapblockaddr_iostart
12399  *
12400  * Description: Verify request lies within the partition limits for
12401  *		the indicated minor device.  Issue "overrun" buf if
12402  *		request would exceed partition range.  Converts
12403  *		partition-relative block address to absolute.
12404  *
12405  *              Upon exit of this function:
12406  *              1.I/O is aligned
12407  *                 xp->xb_blkno represents the absolute sector address
12408  *              2.I/O is misaligned
12409  *                 xp->xb_blkno represents the absolute logical block address
12410  *                 based on DEV_BSIZE. The logical block address will be
12411  *                 converted to physical sector address in sd_mapblocksize_\
12412  *                 iostart.
12413  *              3.I/O is misaligned but is aligned in "overrun" buf
12414  *                 xp->xb_blkno represents the absolute logical block address
12415  *                 based on DEV_BSIZE. The logical block address will be
12416  *                 converted to physical sector address in sd_mapblocksize_\
12417  *                 iostart. But no RMW will be issued in this case.
12418  *
12419  *     Context: Can sleep
12420  *
12421  *      Issues: This follows what the old code did, in terms of accessing
12422  *		some of the partition info in the unit struct without holding
12423  *		the mutext.  This is a general issue, if the partition info
12424  *		can be altered while IO is in progress... as soon as we send
12425  *		a buf, its partitioning can be invalid before it gets to the
12426  *		device.  Probably the right fix is to move partitioning out
12427  *		of the driver entirely.
12428  */
12429 
12430 static void
12431 sd_mapblockaddr_iostart(int index, struct sd_lun *un, struct buf *bp)
12432 {
12433 	diskaddr_t	nblocks;	/* #blocks in the given partition */
12434 	daddr_t	blocknum;	/* Block number specified by the buf */
12435 	size_t	requested_nblocks;
12436 	size_t	available_nblocks;
12437 	int	partition;
12438 	diskaddr_t	partition_offset;
12439 	struct sd_xbuf *xp;
12440 	int secmask = 0, blknomask = 0;
12441 	ushort_t is_aligned = TRUE;
12442 
12443 	ASSERT(un != NULL);
12444 	ASSERT(bp != NULL);
12445 	ASSERT(!mutex_owned(SD_MUTEX(un)));
12446 
12447 	SD_TRACE(SD_LOG_IO_PARTITION, un,
12448 	    "sd_mapblockaddr_iostart: entry: buf:0x%p\n", bp);
12449 
12450 	xp = SD_GET_XBUF(bp);
12451 	ASSERT(xp != NULL);
12452 
12453 	/*
12454 	 * If the geometry is not indicated as valid, attempt to access
12455 	 * the unit & verify the geometry/label. This can be the case for
12456 	 * removable-media devices, of if the device was opened in
12457 	 * NDELAY/NONBLOCK mode.
12458 	 */
12459 	partition = SDPART(bp->b_edev);
12460 
12461 	if (!SD_IS_VALID_LABEL(un)) {
12462 		sd_ssc_t *ssc;
12463 		/*
12464 		 * Initialize sd_ssc_t for internal uscsi commands
12465 		 * In case of potential porformance issue, we need
12466 		 * to alloc memory only if there is invalid label
12467 		 */
12468 		ssc = sd_ssc_init(un);
12469 
12470 		if (sd_ready_and_valid(ssc, partition) != SD_READY_VALID) {
12471 			/*
12472 			 * For removable devices it is possible to start an
12473 			 * I/O without a media by opening the device in nodelay
12474 			 * mode. Also for writable CDs there can be many
12475 			 * scenarios where there is no geometry yet but volume
12476 			 * manager is trying to issue a read() just because
12477 			 * it can see TOC on the CD. So do not print a message
12478 			 * for removables.
12479 			 */
12480 			if (!un->un_f_has_removable_media) {
12481 				scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
12482 				    "i/o to invalid geometry\n");
12483 			}
12484 			bioerror(bp, EIO);
12485 			bp->b_resid = bp->b_bcount;
12486 			SD_BEGIN_IODONE(index, un, bp);
12487 
12488 			sd_ssc_fini(ssc);
12489 			return;
12490 		}
12491 		sd_ssc_fini(ssc);
12492 	}
12493 
12494 	nblocks = 0;
12495 	(void) cmlb_partinfo(un->un_cmlbhandle, partition,
12496 	    &nblocks, &partition_offset, NULL, NULL, (void *)SD_PATH_DIRECT);
12497 
12498 	blknomask = (un->un_tgt_blocksize / DEV_BSIZE) - 1;
12499 	secmask = un->un_tgt_blocksize - 1;
12500 
12501 	if ((bp->b_lblkno & (blknomask)) || (bp->b_bcount & (secmask))) {
12502 		is_aligned = FALSE;
12503 	}
12504 
12505 	if (!(NOT_DEVBSIZE(un))) {
12506 		/*
12507 		 * If I/O is aligned, no need to involve RMW(Read Modify Write)
12508 		 * Convert the logical block number to target's physical sector
12509 		 * number.
12510 		 */
12511 		if (is_aligned) {
12512 			xp->xb_blkno = SD_SYS2TGTBLOCK(un, xp->xb_blkno);
12513 		} else {
12514 			switch (un->un_f_rmw_type) {
12515 			case SD_RMW_TYPE_RETURN_ERROR:
12516 				bp->b_flags |= B_ERROR;
12517 				goto error_exit;
12518 
12519 			case SD_RMW_TYPE_DEFAULT:
12520 				mutex_enter(SD_MUTEX(un));
12521 				if (un->un_rmw_msg_timeid == NULL) {
12522 					scsi_log(SD_DEVINFO(un), sd_label,
12523 					    CE_WARN, "I/O request is not "
12524 					    "aligned with %d disk sector size. "
12525 					    "It is handled through Read Modify "
12526 					    "Write but the performance is "
12527 					    "very low.\n",
12528 					    un->un_tgt_blocksize);
12529 					un->un_rmw_msg_timeid =
12530 					    timeout(sd_rmw_msg_print_handler,
12531 					    un, SD_RMW_MSG_PRINT_TIMEOUT);
12532 				} else {
12533 					un->un_rmw_incre_count ++;
12534 				}
12535 				mutex_exit(SD_MUTEX(un));
12536 				break;
12537 
12538 			case SD_RMW_TYPE_NO_WARNING:
12539 			default:
12540 				break;
12541 			}
12542 
12543 			nblocks = SD_TGT2SYSBLOCK(un, nblocks);
12544 			partition_offset = SD_TGT2SYSBLOCK(un,
12545 			    partition_offset);
12546 		}
12547 	}
12548 
12549 	/*
12550 	 * blocknum is the starting block number of the request. At this
12551 	 * point it is still relative to the start of the minor device.
12552 	 */
12553 	blocknum = xp->xb_blkno;
12554 
12555 	/*
12556 	 * Legacy: If the starting block number is one past the last block
12557 	 * in the partition, do not set B_ERROR in the buf.
12558 	 */
12559 	if (blocknum == nblocks)  {
12560 		goto error_exit;
12561 	}
12562 
12563 	/*
12564 	 * Confirm that the first block of the request lies within the
12565 	 * partition limits. Also the requested number of bytes must be
12566 	 * a multiple of the system block size.
12567 	 */
12568 	if ((blocknum < 0) || (blocknum >= nblocks) ||
12569 	    ((bp->b_bcount & (DEV_BSIZE - 1)) != 0)) {
12570 		bp->b_flags |= B_ERROR;
12571 		goto error_exit;
12572 	}
12573 
12574 	/*
12575 	 * If the requsted # blocks exceeds the available # blocks, that
12576 	 * is an overrun of the partition.
12577 	 */
12578 	if ((!NOT_DEVBSIZE(un)) && is_aligned) {
12579 		requested_nblocks = SD_BYTES2TGTBLOCKS(un, bp->b_bcount);
12580 	} else {
12581 		requested_nblocks = SD_BYTES2SYSBLOCKS(bp->b_bcount);
12582 	}
12583 
12584 	available_nblocks = (size_t)(nblocks - blocknum);
12585 	ASSERT(nblocks >= blocknum);
12586 
12587 	if (requested_nblocks > available_nblocks) {
12588 		size_t resid;
12589 
12590 		/*
12591 		 * Allocate an "overrun" buf to allow the request to proceed
12592 		 * for the amount of space available in the partition. The
12593 		 * amount not transferred will be added into the b_resid
12594 		 * when the operation is complete. The overrun buf
12595 		 * replaces the original buf here, and the original buf
12596 		 * is saved inside the overrun buf, for later use.
12597 		 */
12598 		if ((!NOT_DEVBSIZE(un)) && is_aligned) {
12599 			resid = SD_TGTBLOCKS2BYTES(un,
12600 			    (offset_t)(requested_nblocks - available_nblocks));
12601 		} else {
12602 			resid = SD_SYSBLOCKS2BYTES(
12603 			    (offset_t)(requested_nblocks - available_nblocks));
12604 		}
12605 
12606 		size_t count = bp->b_bcount - resid;
12607 		/*
12608 		 * Note: count is an unsigned entity thus it'll NEVER
12609 		 * be less than 0 so ASSERT the original values are
12610 		 * correct.
12611 		 */
12612 		ASSERT(bp->b_bcount >= resid);
12613 
12614 		bp = sd_bioclone_alloc(bp, count, blocknum,
12615 		    (int (*)(struct buf *)) sd_mapblockaddr_iodone);
12616 		xp = SD_GET_XBUF(bp); /* Update for 'new' bp! */
12617 		ASSERT(xp != NULL);
12618 	}
12619 
12620 	/* At this point there should be no residual for this buf. */
12621 	ASSERT(bp->b_resid == 0);
12622 
12623 	/* Convert the block number to an absolute address. */
12624 	xp->xb_blkno += partition_offset;
12625 
12626 	SD_NEXT_IOSTART(index, un, bp);
12627 
12628 	SD_TRACE(SD_LOG_IO_PARTITION, un,
12629 	    "sd_mapblockaddr_iostart: exit 0: buf:0x%p\n", bp);
12630 
12631 	return;
12632 
12633 error_exit:
12634 	bp->b_resid = bp->b_bcount;
12635 	SD_BEGIN_IODONE(index, un, bp);
12636 	SD_TRACE(SD_LOG_IO_PARTITION, un,
12637 	    "sd_mapblockaddr_iostart: exit 1: buf:0x%p\n", bp);
12638 }
12639 
12640 
12641 /*
12642  *    Function: sd_mapblockaddr_iodone
12643  *
12644  * Description: Completion-side processing for partition management.
12645  *
12646  *     Context: May be called under interrupt context
12647  */
12648 
12649 static void
12650 sd_mapblockaddr_iodone(int index, struct sd_lun *un, struct buf *bp)
12651 {
12652 	/* int	partition; */	/* Not used, see below. */
12653 	ASSERT(un != NULL);
12654 	ASSERT(bp != NULL);
12655 	ASSERT(!mutex_owned(SD_MUTEX(un)));
12656 
12657 	SD_TRACE(SD_LOG_IO_PARTITION, un,
12658 	    "sd_mapblockaddr_iodone: entry: buf:0x%p\n", bp);
12659 
12660 	if (bp->b_iodone == (int (*)(struct buf *)) sd_mapblockaddr_iodone) {
12661 		/*
12662 		 * We have an "overrun" buf to deal with...
12663 		 */
12664 		struct sd_xbuf	*xp;
12665 		struct buf	*obp;	/* ptr to the original buf */
12666 
12667 		xp = SD_GET_XBUF(bp);
12668 		ASSERT(xp != NULL);
12669 
12670 		/* Retrieve the pointer to the original buf */
12671 		obp = (struct buf *)xp->xb_private;
12672 		ASSERT(obp != NULL);
12673 
12674 		obp->b_resid = obp->b_bcount - (bp->b_bcount - bp->b_resid);
12675 		bioerror(obp, bp->b_error);
12676 
12677 		sd_bioclone_free(bp);
12678 
12679 		/*
12680 		 * Get back the original buf.
12681 		 * Note that since the restoration of xb_blkno below
12682 		 * was removed, the sd_xbuf is not needed.
12683 		 */
12684 		bp = obp;
12685 		/*
12686 		 * xp = SD_GET_XBUF(bp);
12687 		 * ASSERT(xp != NULL);
12688 		 */
12689 	}
12690 
12691 	/*
12692 	 * Convert sd->xb_blkno back to a minor-device relative value.
12693 	 * Note: this has been commented out, as it is not needed in the
12694 	 * current implementation of the driver (ie, since this function
12695 	 * is at the top of the layering chains, so the info will be
12696 	 * discarded) and it is in the "hot" IO path.
12697 	 *
12698 	 * partition = getminor(bp->b_edev) & SDPART_MASK;
12699 	 * xp->xb_blkno -= un->un_offset[partition];
12700 	 */
12701 
12702 	SD_NEXT_IODONE(index, un, bp);
12703 
12704 	SD_TRACE(SD_LOG_IO_PARTITION, un,
12705 	    "sd_mapblockaddr_iodone: exit: buf:0x%p\n", bp);
12706 }
12707 
12708 
12709 /*
12710  *    Function: sd_mapblocksize_iostart
12711  *
12712  * Description: Convert between system block size (un->un_sys_blocksize)
12713  *		and target block size (un->un_tgt_blocksize).
12714  *
12715  *     Context: Can sleep to allocate resources.
12716  *
12717  * Assumptions: A higher layer has already performed any partition validation,
12718  *		and converted the xp->xb_blkno to an absolute value relative
12719  *		to the start of the device.
12720  *
12721  *		It is also assumed that the higher layer has implemented
12722  *		an "overrun" mechanism for the case where the request would
12723  *		read/write beyond the end of a partition.  In this case we
12724  *		assume (and ASSERT) that bp->b_resid == 0.
12725  *
12726  *		Note: The implementation for this routine assumes the target
12727  *		block size remains constant between allocation and transport.
12728  */
12729 
12730 static void
12731 sd_mapblocksize_iostart(int index, struct sd_lun *un, struct buf *bp)
12732 {
12733 	struct sd_mapblocksize_info	*bsp;
12734 	struct sd_xbuf			*xp;
12735 	offset_t first_byte;
12736 	daddr_t	start_block, end_block;
12737 	daddr_t	request_bytes;
12738 	ushort_t is_aligned = FALSE;
12739 
12740 	ASSERT(un != NULL);
12741 	ASSERT(bp != NULL);
12742 	ASSERT(!mutex_owned(SD_MUTEX(un)));
12743 	ASSERT(bp->b_resid == 0);
12744 
12745 	SD_TRACE(SD_LOG_IO_RMMEDIA, un,
12746 	    "sd_mapblocksize_iostart: entry: buf:0x%p\n", bp);
12747 
12748 	/*
12749 	 * For a non-writable CD, a write request is an error
12750 	 */
12751 	if (ISCD(un) && ((bp->b_flags & B_READ) == 0) &&
12752 	    (un->un_f_mmc_writable_media == FALSE)) {
12753 		bioerror(bp, EIO);
12754 		bp->b_resid = bp->b_bcount;
12755 		SD_BEGIN_IODONE(index, un, bp);
12756 		return;
12757 	}
12758 
12759 	/*
12760 	 * We do not need a shadow buf if the device is using
12761 	 * un->un_sys_blocksize as its block size or if bcount == 0.
12762 	 * In this case there is no layer-private data block allocated.
12763 	 */
12764 	if ((un->un_tgt_blocksize == DEV_BSIZE) ||
12765 	    (bp->b_bcount == 0)) {
12766 		goto done;
12767 	}
12768 
12769 #if defined(__i386) || defined(__amd64)
12770 	/* We do not support non-block-aligned transfers for ROD devices */
12771 	ASSERT(!ISROD(un));
12772 #endif
12773 
12774 	xp = SD_GET_XBUF(bp);
12775 	ASSERT(xp != NULL);
12776 
12777 	SD_INFO(SD_LOG_IO_RMMEDIA, un, "sd_mapblocksize_iostart: "
12778 	    "tgt_blocksize:0x%x sys_blocksize: 0x%x\n",
12779 	    un->un_tgt_blocksize, DEV_BSIZE);
12780 	SD_INFO(SD_LOG_IO_RMMEDIA, un, "sd_mapblocksize_iostart: "
12781 	    "request start block:0x%x\n", xp->xb_blkno);
12782 	SD_INFO(SD_LOG_IO_RMMEDIA, un, "sd_mapblocksize_iostart: "
12783 	    "request len:0x%x\n", bp->b_bcount);
12784 
12785 	/*
12786 	 * Allocate the layer-private data area for the mapblocksize layer.
12787 	 * Layers are allowed to use the xp_private member of the sd_xbuf
12788 	 * struct to store the pointer to their layer-private data block, but
12789 	 * each layer also has the responsibility of restoring the prior
12790 	 * contents of xb_private before returning the buf/xbuf to the
12791 	 * higher layer that sent it.
12792 	 *
12793 	 * Here we save the prior contents of xp->xb_private into the
12794 	 * bsp->mbs_oprivate field of our layer-private data area. This value
12795 	 * is restored by sd_mapblocksize_iodone() just prior to freeing up
12796 	 * the layer-private area and returning the buf/xbuf to the layer
12797 	 * that sent it.
12798 	 *
12799 	 * Note that here we use kmem_zalloc for the allocation as there are
12800 	 * parts of the mapblocksize code that expect certain fields to be
12801 	 * zero unless explicitly set to a required value.
12802 	 */
12803 	bsp = kmem_zalloc(sizeof (struct sd_mapblocksize_info), KM_SLEEP);
12804 	bsp->mbs_oprivate = xp->xb_private;
12805 	xp->xb_private = bsp;
12806 
12807 	/*
12808 	 * This treats the data on the disk (target) as an array of bytes.
12809 	 * first_byte is the byte offset, from the beginning of the device,
12810 	 * to the location of the request. This is converted from a
12811 	 * un->un_sys_blocksize block address to a byte offset, and then back
12812 	 * to a block address based upon a un->un_tgt_blocksize block size.
12813 	 *
12814 	 * xp->xb_blkno should be absolute upon entry into this function,
12815 	 * but, but it is based upon partitions that use the "system"
12816 	 * block size. It must be adjusted to reflect the block size of
12817 	 * the target.
12818 	 *
12819 	 * Note that end_block is actually the block that follows the last
12820 	 * block of the request, but that's what is needed for the computation.
12821 	 */
12822 	first_byte  = SD_SYSBLOCKS2BYTES((offset_t)xp->xb_blkno);
12823 	start_block = xp->xb_blkno = first_byte / un->un_tgt_blocksize;
12824 	end_block   = (first_byte + bp->b_bcount + un->un_tgt_blocksize - 1) /
12825 	    un->un_tgt_blocksize;
12826 
12827 	/* request_bytes is rounded up to a multiple of the target block size */
12828 	request_bytes = (end_block - start_block) * un->un_tgt_blocksize;
12829 
12830 	/*
12831 	 * See if the starting address of the request and the request
12832 	 * length are aligned on a un->un_tgt_blocksize boundary. If aligned
12833 	 * then we do not need to allocate a shadow buf to handle the request.
12834 	 */
12835 	if (((first_byte   % un->un_tgt_blocksize) == 0) &&
12836 	    ((bp->b_bcount % un->un_tgt_blocksize) == 0)) {
12837 		is_aligned = TRUE;
12838 	}
12839 
12840 	if ((bp->b_flags & B_READ) == 0) {
12841 		/*
12842 		 * Lock the range for a write operation. An aligned request is
12843 		 * considered a simple write; otherwise the request must be a
12844 		 * read-modify-write.
12845 		 */
12846 		bsp->mbs_wmp = sd_range_lock(un, start_block, end_block - 1,
12847 		    (is_aligned == TRUE) ? SD_WTYPE_SIMPLE : SD_WTYPE_RMW);
12848 	}
12849 
12850 	/*
12851 	 * Alloc a shadow buf if the request is not aligned. Also, this is
12852 	 * where the READ command is generated for a read-modify-write. (The
12853 	 * write phase is deferred until after the read completes.)
12854 	 */
12855 	if (is_aligned == FALSE) {
12856 
12857 		struct sd_mapblocksize_info	*shadow_bsp;
12858 		struct sd_xbuf	*shadow_xp;
12859 		struct buf	*shadow_bp;
12860 
12861 		/*
12862 		 * Allocate the shadow buf and it associated xbuf. Note that
12863 		 * after this call the xb_blkno value in both the original
12864 		 * buf's sd_xbuf _and_ the shadow buf's sd_xbuf will be the
12865 		 * same: absolute relative to the start of the device, and
12866 		 * adjusted for the target block size. The b_blkno in the
12867 		 * shadow buf will also be set to this value. We should never
12868 		 * change b_blkno in the original bp however.
12869 		 *
12870 		 * Note also that the shadow buf will always need to be a
12871 		 * READ command, regardless of whether the incoming command
12872 		 * is a READ or a WRITE.
12873 		 */
12874 		shadow_bp = sd_shadow_buf_alloc(bp, request_bytes, B_READ,
12875 		    xp->xb_blkno,
12876 		    (int (*)(struct buf *)) sd_mapblocksize_iodone);
12877 
12878 		shadow_xp = SD_GET_XBUF(shadow_bp);
12879 
12880 		/*
12881 		 * Allocate the layer-private data for the shadow buf.
12882 		 * (No need to preserve xb_private in the shadow xbuf.)
12883 		 */
12884 		shadow_xp->xb_private = shadow_bsp =
12885 		    kmem_zalloc(sizeof (struct sd_mapblocksize_info), KM_SLEEP);
12886 
12887 		/*
12888 		 * bsp->mbs_copy_offset is used later by sd_mapblocksize_iodone
12889 		 * to figure out where the start of the user data is (based upon
12890 		 * the system block size) in the data returned by the READ
12891 		 * command (which will be based upon the target blocksize). Note
12892 		 * that this is only really used if the request is unaligned.
12893 		 */
12894 		bsp->mbs_copy_offset = (ssize_t)(first_byte -
12895 		    ((offset_t)xp->xb_blkno * un->un_tgt_blocksize));
12896 		ASSERT((bsp->mbs_copy_offset >= 0) &&
12897 		    (bsp->mbs_copy_offset < un->un_tgt_blocksize));
12898 
12899 		shadow_bsp->mbs_copy_offset = bsp->mbs_copy_offset;
12900 
12901 		shadow_bsp->mbs_layer_index = bsp->mbs_layer_index = index;
12902 
12903 		/* Transfer the wmap (if any) to the shadow buf */
12904 		shadow_bsp->mbs_wmp = bsp->mbs_wmp;
12905 		bsp->mbs_wmp = NULL;
12906 
12907 		/*
12908 		 * The shadow buf goes on from here in place of the
12909 		 * original buf.
12910 		 */
12911 		shadow_bsp->mbs_orig_bp = bp;
12912 		bp = shadow_bp;
12913 	}
12914 
12915 	SD_INFO(SD_LOG_IO_RMMEDIA, un,
12916 	    "sd_mapblocksize_iostart: tgt start block:0x%x\n", xp->xb_blkno);
12917 	SD_INFO(SD_LOG_IO_RMMEDIA, un,
12918 	    "sd_mapblocksize_iostart: tgt request len:0x%x\n",
12919 	    request_bytes);
12920 	SD_INFO(SD_LOG_IO_RMMEDIA, un,
12921 	    "sd_mapblocksize_iostart: shadow buf:0x%x\n", bp);
12922 
12923 done:
12924 	SD_NEXT_IOSTART(index, un, bp);
12925 
12926 	SD_TRACE(SD_LOG_IO_RMMEDIA, un,
12927 	    "sd_mapblocksize_iostart: exit: buf:0x%p\n", bp);
12928 }
12929 
12930 
12931 /*
12932  *    Function: sd_mapblocksize_iodone
12933  *
12934  * Description: Completion side processing for block-size mapping.
12935  *
12936  *     Context: May be called under interrupt context
12937  */
12938 
12939 static void
12940 sd_mapblocksize_iodone(int index, struct sd_lun *un, struct buf *bp)
12941 {
12942 	struct sd_mapblocksize_info	*bsp;
12943 	struct sd_xbuf	*xp;
12944 	struct sd_xbuf	*orig_xp;	/* sd_xbuf for the original buf */
12945 	struct buf	*orig_bp;	/* ptr to the original buf */
12946 	offset_t	shadow_end;
12947 	offset_t	request_end;
12948 	offset_t	shadow_start;
12949 	ssize_t		copy_offset;
12950 	size_t		copy_length;
12951 	size_t		shortfall;
12952 	uint_t		is_write;	/* TRUE if this bp is a WRITE */
12953 	uint_t		has_wmap;	/* TRUE is this bp has a wmap */
12954 
12955 	ASSERT(un != NULL);
12956 	ASSERT(bp != NULL);
12957 
12958 	SD_TRACE(SD_LOG_IO_RMMEDIA, un,
12959 	    "sd_mapblocksize_iodone: entry: buf:0x%p\n", bp);
12960 
12961 	/*
12962 	 * There is no shadow buf or layer-private data if the target is
12963 	 * using un->un_sys_blocksize as its block size or if bcount == 0.
12964 	 */
12965 	if ((un->un_tgt_blocksize == DEV_BSIZE) ||
12966 	    (bp->b_bcount == 0)) {
12967 		goto exit;
12968 	}
12969 
12970 	xp = SD_GET_XBUF(bp);
12971 	ASSERT(xp != NULL);
12972 
12973 	/* Retrieve the pointer to the layer-private data area from the xbuf. */
12974 	bsp = xp->xb_private;
12975 
12976 	is_write = ((bp->b_flags & B_READ) == 0) ? TRUE : FALSE;
12977 	has_wmap = (bsp->mbs_wmp != NULL) ? TRUE : FALSE;
12978 
12979 	if (is_write) {
12980 		/*
12981 		 * For a WRITE request we must free up the block range that
12982 		 * we have locked up.  This holds regardless of whether this is
12983 		 * an aligned write request or a read-modify-write request.
12984 		 */
12985 		sd_range_unlock(un, bsp->mbs_wmp);
12986 		bsp->mbs_wmp = NULL;
12987 	}
12988 
12989 	if ((bp->b_iodone != (int(*)(struct buf *))sd_mapblocksize_iodone)) {
12990 		/*
12991 		 * An aligned read or write command will have no shadow buf;
12992 		 * there is not much else to do with it.
12993 		 */
12994 		goto done;
12995 	}
12996 
12997 	orig_bp = bsp->mbs_orig_bp;
12998 	ASSERT(orig_bp != NULL);
12999 	orig_xp = SD_GET_XBUF(orig_bp);
13000 	ASSERT(orig_xp != NULL);
13001 	ASSERT(!mutex_owned(SD_MUTEX(un)));
13002 
13003 	if (!is_write && has_wmap) {
13004 		/*
13005 		 * A READ with a wmap means this is the READ phase of a
13006 		 * read-modify-write. If an error occurred on the READ then
13007 		 * we do not proceed with the WRITE phase or copy any data.
13008 		 * Just release the write maps and return with an error.
13009 		 */
13010 		if ((bp->b_resid != 0) || (bp->b_error != 0)) {
13011 			orig_bp->b_resid = orig_bp->b_bcount;
13012 			bioerror(orig_bp, bp->b_error);
13013 			sd_range_unlock(un, bsp->mbs_wmp);
13014 			goto freebuf_done;
13015 		}
13016 	}
13017 
13018 	/*
13019 	 * Here is where we set up to copy the data from the shadow buf
13020 	 * into the space associated with the original buf.
13021 	 *
13022 	 * To deal with the conversion between block sizes, these
13023 	 * computations treat the data as an array of bytes, with the
13024 	 * first byte (byte 0) corresponding to the first byte in the
13025 	 * first block on the disk.
13026 	 */
13027 
13028 	/*
13029 	 * shadow_start and shadow_len indicate the location and size of
13030 	 * the data returned with the shadow IO request.
13031 	 */
13032 	shadow_start  = SD_TGTBLOCKS2BYTES(un, (offset_t)xp->xb_blkno);
13033 	shadow_end    = shadow_start + bp->b_bcount - bp->b_resid;
13034 
13035 	/*
13036 	 * copy_offset gives the offset (in bytes) from the start of the first
13037 	 * block of the READ request to the beginning of the data.  We retrieve
13038 	 * this value from xb_pktp in the ORIGINAL xbuf, as it has been saved
13039 	 * there by sd_mapblockize_iostart(). copy_length gives the amount of
13040 	 * data to be copied (in bytes).
13041 	 */
13042 	copy_offset  = bsp->mbs_copy_offset;
13043 	ASSERT((copy_offset >= 0) && (copy_offset < un->un_tgt_blocksize));
13044 	copy_length  = orig_bp->b_bcount;
13045 	request_end  = shadow_start + copy_offset + orig_bp->b_bcount;
13046 
13047 	/*
13048 	 * Set up the resid and error fields of orig_bp as appropriate.
13049 	 */
13050 	if (shadow_end >= request_end) {
13051 		/* We got all the requested data; set resid to zero */
13052 		orig_bp->b_resid = 0;
13053 	} else {
13054 		/*
13055 		 * We failed to get enough data to fully satisfy the original
13056 		 * request. Just copy back whatever data we got and set
13057 		 * up the residual and error code as required.
13058 		 *
13059 		 * 'shortfall' is the amount by which the data received with the
13060 		 * shadow buf has "fallen short" of the requested amount.
13061 		 */
13062 		shortfall = (size_t)(request_end - shadow_end);
13063 
13064 		if (shortfall > orig_bp->b_bcount) {
13065 			/*
13066 			 * We did not get enough data to even partially
13067 			 * fulfill the original request.  The residual is
13068 			 * equal to the amount requested.
13069 			 */
13070 			orig_bp->b_resid = orig_bp->b_bcount;
13071 		} else {
13072 			/*
13073 			 * We did not get all the data that we requested
13074 			 * from the device, but we will try to return what
13075 			 * portion we did get.
13076 			 */
13077 			orig_bp->b_resid = shortfall;
13078 		}
13079 		ASSERT(copy_length >= orig_bp->b_resid);
13080 		copy_length  -= orig_bp->b_resid;
13081 	}
13082 
13083 	/* Propagate the error code from the shadow buf to the original buf */
13084 	bioerror(orig_bp, bp->b_error);
13085 
13086 	if (is_write) {
13087 		goto freebuf_done;	/* No data copying for a WRITE */
13088 	}
13089 
13090 	if (has_wmap) {
13091 		/*
13092 		 * This is a READ command from the READ phase of a
13093 		 * read-modify-write request. We have to copy the data given
13094 		 * by the user OVER the data returned by the READ command,
13095 		 * then convert the command from a READ to a WRITE and send
13096 		 * it back to the target.
13097 		 */
13098 		bcopy(orig_bp->b_un.b_addr, bp->b_un.b_addr + copy_offset,
13099 		    copy_length);
13100 
13101 		bp->b_flags &= ~((int)B_READ);	/* Convert to a WRITE */
13102 
13103 		/*
13104 		 * Dispatch the WRITE command to the taskq thread, which
13105 		 * will in turn send the command to the target. When the
13106 		 * WRITE command completes, we (sd_mapblocksize_iodone())
13107 		 * will get called again as part of the iodone chain
13108 		 * processing for it. Note that we will still be dealing
13109 		 * with the shadow buf at that point.
13110 		 */
13111 		if (taskq_dispatch(sd_wmr_tq, sd_read_modify_write_task, bp,
13112 		    KM_NOSLEEP) != 0) {
13113 			/*
13114 			 * Dispatch was successful so we are done. Return
13115 			 * without going any higher up the iodone chain. Do
13116 			 * not free up any layer-private data until after the
13117 			 * WRITE completes.
13118 			 */
13119 			return;
13120 		}
13121 
13122 		/*
13123 		 * Dispatch of the WRITE command failed; set up the error
13124 		 * condition and send this IO back up the iodone chain.
13125 		 */
13126 		bioerror(orig_bp, EIO);
13127 		orig_bp->b_resid = orig_bp->b_bcount;
13128 
13129 	} else {
13130 		/*
13131 		 * This is a regular READ request (ie, not a RMW). Copy the
13132 		 * data from the shadow buf into the original buf. The
13133 		 * copy_offset compensates for any "misalignment" between the
13134 		 * shadow buf (with its un->un_tgt_blocksize blocks) and the
13135 		 * original buf (with its un->un_sys_blocksize blocks).
13136 		 */
13137 		bcopy(bp->b_un.b_addr + copy_offset, orig_bp->b_un.b_addr,
13138 		    copy_length);
13139 	}
13140 
13141 freebuf_done:
13142 
13143 	/*
13144 	 * At this point we still have both the shadow buf AND the original
13145 	 * buf to deal with, as well as the layer-private data area in each.
13146 	 * Local variables are as follows:
13147 	 *
13148 	 * bp -- points to shadow buf
13149 	 * xp -- points to xbuf of shadow buf
13150 	 * bsp -- points to layer-private data area of shadow buf
13151 	 * orig_bp -- points to original buf
13152 	 *
13153 	 * First free the shadow buf and its associated xbuf, then free the
13154 	 * layer-private data area from the shadow buf. There is no need to
13155 	 * restore xb_private in the shadow xbuf.
13156 	 */
13157 	sd_shadow_buf_free(bp);
13158 	kmem_free(bsp, sizeof (struct sd_mapblocksize_info));
13159 
13160 	/*
13161 	 * Now update the local variables to point to the original buf, xbuf,
13162 	 * and layer-private area.
13163 	 */
13164 	bp = orig_bp;
13165 	xp = SD_GET_XBUF(bp);
13166 	ASSERT(xp != NULL);
13167 	ASSERT(xp == orig_xp);
13168 	bsp = xp->xb_private;
13169 	ASSERT(bsp != NULL);
13170 
13171 done:
13172 	/*
13173 	 * Restore xb_private to whatever it was set to by the next higher
13174 	 * layer in the chain, then free the layer-private data area.
13175 	 */
13176 	xp->xb_private = bsp->mbs_oprivate;
13177 	kmem_free(bsp, sizeof (struct sd_mapblocksize_info));
13178 
13179 exit:
13180 	SD_TRACE(SD_LOG_IO_RMMEDIA, SD_GET_UN(bp),
13181 	    "sd_mapblocksize_iodone: calling SD_NEXT_IODONE: buf:0x%p\n", bp);
13182 
13183 	SD_NEXT_IODONE(index, un, bp);
13184 }
13185 
13186 
13187 /*
13188  *    Function: sd_checksum_iostart
13189  *
13190  * Description: A stub function for a layer that's currently not used.
13191  *		For now just a placeholder.
13192  *
13193  *     Context: Kernel thread context
13194  */
13195 
13196 static void
13197 sd_checksum_iostart(int index, struct sd_lun *un, struct buf *bp)
13198 {
13199 	ASSERT(un != NULL);
13200 	ASSERT(bp != NULL);
13201 	ASSERT(!mutex_owned(SD_MUTEX(un)));
13202 	SD_NEXT_IOSTART(index, un, bp);
13203 }
13204 
13205 
13206 /*
13207  *    Function: sd_checksum_iodone
13208  *
13209  * Description: A stub function for a layer that's currently not used.
13210  *		For now just a placeholder.
13211  *
13212  *     Context: May be called under interrupt context
13213  */
13214 
13215 static void
13216 sd_checksum_iodone(int index, struct sd_lun *un, struct buf *bp)
13217 {
13218 	ASSERT(un != NULL);
13219 	ASSERT(bp != NULL);
13220 	ASSERT(!mutex_owned(SD_MUTEX(un)));
13221 	SD_NEXT_IODONE(index, un, bp);
13222 }
13223 
13224 
13225 /*
13226  *    Function: sd_checksum_uscsi_iostart
13227  *
13228  * Description: A stub function for a layer that's currently not used.
13229  *		For now just a placeholder.
13230  *
13231  *     Context: Kernel thread context
13232  */
13233 
13234 static void
13235 sd_checksum_uscsi_iostart(int index, struct sd_lun *un, struct buf *bp)
13236 {
13237 	ASSERT(un != NULL);
13238 	ASSERT(bp != NULL);
13239 	ASSERT(!mutex_owned(SD_MUTEX(un)));
13240 	SD_NEXT_IOSTART(index, un, bp);
13241 }
13242 
13243 
13244 /*
13245  *    Function: sd_checksum_uscsi_iodone
13246  *
13247  * Description: A stub function for a layer that's currently not used.
13248  *		For now just a placeholder.
13249  *
13250  *     Context: May be called under interrupt context
13251  */
13252 
13253 static void
13254 sd_checksum_uscsi_iodone(int index, struct sd_lun *un, struct buf *bp)
13255 {
13256 	ASSERT(un != NULL);
13257 	ASSERT(bp != NULL);
13258 	ASSERT(!mutex_owned(SD_MUTEX(un)));
13259 	SD_NEXT_IODONE(index, un, bp);
13260 }
13261 
13262 
13263 /*
13264  *    Function: sd_pm_iostart
13265  *
13266  * Description: iostart-side routine for Power mangement.
13267  *
13268  *     Context: Kernel thread context
13269  */
13270 
13271 static void
13272 sd_pm_iostart(int index, struct sd_lun *un, struct buf *bp)
13273 {
13274 	ASSERT(un != NULL);
13275 	ASSERT(bp != NULL);
13276 	ASSERT(!mutex_owned(SD_MUTEX(un)));
13277 	ASSERT(!mutex_owned(&un->un_pm_mutex));
13278 
13279 	SD_TRACE(SD_LOG_IO_PM, un, "sd_pm_iostart: entry\n");
13280 
13281 	if (sd_pm_entry(un) != DDI_SUCCESS) {
13282 		/*
13283 		 * Set up to return the failed buf back up the 'iodone'
13284 		 * side of the calling chain.
13285 		 */
13286 		bioerror(bp, EIO);
13287 		bp->b_resid = bp->b_bcount;
13288 
13289 		SD_BEGIN_IODONE(index, un, bp);
13290 
13291 		SD_TRACE(SD_LOG_IO_PM, un, "sd_pm_iostart: exit\n");
13292 		return;
13293 	}
13294 
13295 	SD_NEXT_IOSTART(index, un, bp);
13296 
13297 	SD_TRACE(SD_LOG_IO_PM, un, "sd_pm_iostart: exit\n");
13298 }
13299 
13300 
13301 /*
13302  *    Function: sd_pm_iodone
13303  *
13304  * Description: iodone-side routine for power mangement.
13305  *
13306  *     Context: may be called from interrupt context
13307  */
13308 
13309 static void
13310 sd_pm_iodone(int index, struct sd_lun *un, struct buf *bp)
13311 {
13312 	ASSERT(un != NULL);
13313 	ASSERT(bp != NULL);
13314 	ASSERT(!mutex_owned(&un->un_pm_mutex));
13315 
13316 	SD_TRACE(SD_LOG_IO_PM, un, "sd_pm_iodone: entry\n");
13317 
13318 	/*
13319 	 * After attach the following flag is only read, so don't
13320 	 * take the penalty of acquiring a mutex for it.
13321 	 */
13322 	if (un->un_f_pm_is_enabled == TRUE) {
13323 		sd_pm_exit(un);
13324 	}
13325 
13326 	SD_NEXT_IODONE(index, un, bp);
13327 
13328 	SD_TRACE(SD_LOG_IO_PM, un, "sd_pm_iodone: exit\n");
13329 }
13330 
13331 
13332 /*
13333  *    Function: sd_core_iostart
13334  *
13335  * Description: Primary driver function for enqueuing buf(9S) structs from
13336  *		the system and initiating IO to the target device
13337  *
13338  *     Context: Kernel thread context. Can sleep.
13339  *
13340  * Assumptions:  - The given xp->xb_blkno is absolute
13341  *		   (ie, relative to the start of the device).
13342  *		 - The IO is to be done using the native blocksize of
13343  *		   the device, as specified in un->un_tgt_blocksize.
13344  */
13345 /* ARGSUSED */
13346 static void
13347 sd_core_iostart(int index, struct sd_lun *un, struct buf *bp)
13348 {
13349 	struct sd_xbuf *xp;
13350 
13351 	ASSERT(un != NULL);
13352 	ASSERT(bp != NULL);
13353 	ASSERT(!mutex_owned(SD_MUTEX(un)));
13354 	ASSERT(bp->b_resid == 0);
13355 
13356 	SD_TRACE(SD_LOG_IO_CORE, un, "sd_core_iostart: entry: bp:0x%p\n", bp);
13357 
13358 	xp = SD_GET_XBUF(bp);
13359 	ASSERT(xp != NULL);
13360 
13361 	mutex_enter(SD_MUTEX(un));
13362 
13363 	/*
13364 	 * If we are currently in the failfast state, fail any new IO
13365 	 * that has B_FAILFAST set, then return.
13366 	 */
13367 	if ((bp->b_flags & B_FAILFAST) &&
13368 	    (un->un_failfast_state == SD_FAILFAST_ACTIVE)) {
13369 		mutex_exit(SD_MUTEX(un));
13370 		bioerror(bp, EIO);
13371 		bp->b_resid = bp->b_bcount;
13372 		SD_BEGIN_IODONE(index, un, bp);
13373 		return;
13374 	}
13375 
13376 	if (SD_IS_DIRECT_PRIORITY(xp)) {
13377 		/*
13378 		 * Priority command -- transport it immediately.
13379 		 *
13380 		 * Note: We may want to assert that USCSI_DIAGNOSE is set,
13381 		 * because all direct priority commands should be associated
13382 		 * with error recovery actions which we don't want to retry.
13383 		 */
13384 		sd_start_cmds(un, bp);
13385 	} else {
13386 		/*
13387 		 * Normal command -- add it to the wait queue, then start
13388 		 * transporting commands from the wait queue.
13389 		 */
13390 		sd_add_buf_to_waitq(un, bp);
13391 		SD_UPDATE_KSTATS(un, kstat_waitq_enter, bp);
13392 		sd_start_cmds(un, NULL);
13393 	}
13394 
13395 	mutex_exit(SD_MUTEX(un));
13396 
13397 	SD_TRACE(SD_LOG_IO_CORE, un, "sd_core_iostart: exit: bp:0x%p\n", bp);
13398 }
13399 
13400 
13401 /*
13402  *    Function: sd_init_cdb_limits
13403  *
13404  * Description: This is to handle scsi_pkt initialization differences
13405  *		between the driver platforms.
13406  *
13407  *		Legacy behaviors:
13408  *
13409  *		If the block number or the sector count exceeds the
13410  *		capabilities of a Group 0 command, shift over to a
13411  *		Group 1 command. We don't blindly use Group 1
13412  *		commands because a) some drives (CDC Wren IVs) get a
13413  *		bit confused, and b) there is probably a fair amount
13414  *		of speed difference for a target to receive and decode
13415  *		a 10 byte command instead of a 6 byte command.
13416  *
13417  *		The xfer time difference of 6 vs 10 byte CDBs is
13418  *		still significant so this code is still worthwhile.
13419  *		10 byte CDBs are very inefficient with the fas HBA driver
13420  *		and older disks. Each CDB byte took 1 usec with some
13421  *		popular disks.
13422  *
13423  *     Context: Must be called at attach time
13424  */
13425 
13426 static void
13427 sd_init_cdb_limits(struct sd_lun *un)
13428 {
13429 	int hba_cdb_limit;
13430 
13431 	/*
13432 	 * Use CDB_GROUP1 commands for most devices except for
13433 	 * parallel SCSI fixed drives in which case we get better
13434 	 * performance using CDB_GROUP0 commands (where applicable).
13435 	 */
13436 	un->un_mincdb = SD_CDB_GROUP1;
13437 #if !defined(__fibre)
13438 	if (!un->un_f_is_fibre && !un->un_f_cfg_is_atapi && !ISROD(un) &&
13439 	    !un->un_f_has_removable_media) {
13440 		un->un_mincdb = SD_CDB_GROUP0;
13441 	}
13442 #endif
13443 
13444 	/*
13445 	 * Try to read the max-cdb-length supported by HBA.
13446 	 */
13447 	un->un_max_hba_cdb = scsi_ifgetcap(SD_ADDRESS(un), "max-cdb-length", 1);
13448 	if (0 >= un->un_max_hba_cdb) {
13449 		un->un_max_hba_cdb = CDB_GROUP4;
13450 		hba_cdb_limit = SD_CDB_GROUP4;
13451 	} else if (0 < un->un_max_hba_cdb &&
13452 	    un->un_max_hba_cdb < CDB_GROUP1) {
13453 		hba_cdb_limit = SD_CDB_GROUP0;
13454 	} else if (CDB_GROUP1 <= un->un_max_hba_cdb &&
13455 	    un->un_max_hba_cdb < CDB_GROUP5) {
13456 		hba_cdb_limit = SD_CDB_GROUP1;
13457 	} else if (CDB_GROUP5 <= un->un_max_hba_cdb &&
13458 	    un->un_max_hba_cdb < CDB_GROUP4) {
13459 		hba_cdb_limit = SD_CDB_GROUP5;
13460 	} else {
13461 		hba_cdb_limit = SD_CDB_GROUP4;
13462 	}
13463 
13464 	/*
13465 	 * Use CDB_GROUP5 commands for removable devices.  Use CDB_GROUP4
13466 	 * commands for fixed disks unless we are building for a 32 bit
13467 	 * kernel.
13468 	 */
13469 #ifdef _LP64
13470 	un->un_maxcdb = (un->un_f_has_removable_media) ? SD_CDB_GROUP5 :
13471 	    min(hba_cdb_limit, SD_CDB_GROUP4);
13472 #else
13473 	un->un_maxcdb = (un->un_f_has_removable_media) ? SD_CDB_GROUP5 :
13474 	    min(hba_cdb_limit, SD_CDB_GROUP1);
13475 #endif
13476 
13477 	un->un_status_len = (int)((un->un_f_arq_enabled == TRUE)
13478 	    ? sizeof (struct scsi_arq_status) : 1);
13479 	un->un_cmd_timeout = (ushort_t)sd_io_time;
13480 	un->un_uscsi_timeout = ((ISCD(un)) ? 2 : 1) * un->un_cmd_timeout;
13481 }
13482 
13483 
13484 /*
13485  *    Function: sd_initpkt_for_buf
13486  *
13487  * Description: Allocate and initialize for transport a scsi_pkt struct,
13488  *		based upon the info specified in the given buf struct.
13489  *
13490  *		Assumes the xb_blkno in the request is absolute (ie,
13491  *		relative to the start of the device (NOT partition!).
13492  *		Also assumes that the request is using the native block
13493  *		size of the device (as returned by the READ CAPACITY
13494  *		command).
13495  *
13496  * Return Code: SD_PKT_ALLOC_SUCCESS
13497  *		SD_PKT_ALLOC_FAILURE
13498  *		SD_PKT_ALLOC_FAILURE_NO_DMA
13499  *		SD_PKT_ALLOC_FAILURE_CDB_TOO_SMALL
13500  *
13501  *     Context: Kernel thread and may be called from software interrupt context
13502  *		as part of a sdrunout callback. This function may not block or
13503  *		call routines that block
13504  */
13505 
13506 static int
13507 sd_initpkt_for_buf(struct buf *bp, struct scsi_pkt **pktpp)
13508 {
13509 	struct sd_xbuf	*xp;
13510 	struct scsi_pkt *pktp = NULL;
13511 	struct sd_lun	*un;
13512 	size_t		blockcount;
13513 	daddr_t		startblock;
13514 	int		rval;
13515 	int		cmd_flags;
13516 
13517 	ASSERT(bp != NULL);
13518 	ASSERT(pktpp != NULL);
13519 	xp = SD_GET_XBUF(bp);
13520 	ASSERT(xp != NULL);
13521 	un = SD_GET_UN(bp);
13522 	ASSERT(un != NULL);
13523 	ASSERT(mutex_owned(SD_MUTEX(un)));
13524 	ASSERT(bp->b_resid == 0);
13525 
13526 	SD_TRACE(SD_LOG_IO_CORE, un,
13527 	    "sd_initpkt_for_buf: entry: buf:0x%p\n", bp);
13528 
13529 	mutex_exit(SD_MUTEX(un));
13530 
13531 #if defined(__i386) || defined(__amd64)	/* DMAFREE for x86 only */
13532 	if (xp->xb_pkt_flags & SD_XB_DMA_FREED) {
13533 		/*
13534 		 * Already have a scsi_pkt -- just need DMA resources.
13535 		 * We must recompute the CDB in case the mapping returns
13536 		 * a nonzero pkt_resid.
13537 		 * Note: if this is a portion of a PKT_DMA_PARTIAL transfer
13538 		 * that is being retried, the unmap/remap of the DMA resouces
13539 		 * will result in the entire transfer starting over again
13540 		 * from the very first block.
13541 		 */
13542 		ASSERT(xp->xb_pktp != NULL);
13543 		pktp = xp->xb_pktp;
13544 	} else {
13545 		pktp = NULL;
13546 	}
13547 #endif /* __i386 || __amd64 */
13548 
13549 	startblock = xp->xb_blkno;	/* Absolute block num. */
13550 	blockcount = SD_BYTES2TGTBLOCKS(un, bp->b_bcount);
13551 
13552 	cmd_flags = un->un_pkt_flags | (xp->xb_pkt_flags & SD_XB_INITPKT_MASK);
13553 
13554 	/*
13555 	 * sd_setup_rw_pkt will determine the appropriate CDB group to use,
13556 	 * call scsi_init_pkt, and build the CDB.
13557 	 */
13558 	rval = sd_setup_rw_pkt(un, &pktp, bp,
13559 	    cmd_flags, sdrunout, (caddr_t)un,
13560 	    startblock, blockcount);
13561 
13562 	if (rval == 0) {
13563 		/*
13564 		 * Success.
13565 		 *
13566 		 * If partial DMA is being used and required for this transfer.
13567 		 * set it up here.
13568 		 */
13569 		if ((un->un_pkt_flags & PKT_DMA_PARTIAL) != 0 &&
13570 		    (pktp->pkt_resid != 0)) {
13571 
13572 			/*
13573 			 * Save the CDB length and pkt_resid for the
13574 			 * next xfer
13575 			 */
13576 			xp->xb_dma_resid = pktp->pkt_resid;
13577 
13578 			/* rezero resid */
13579 			pktp->pkt_resid = 0;
13580 
13581 		} else {
13582 			xp->xb_dma_resid = 0;
13583 		}
13584 
13585 		pktp->pkt_flags = un->un_tagflags;
13586 		pktp->pkt_time  = un->un_cmd_timeout;
13587 		pktp->pkt_comp  = sdintr;
13588 
13589 		pktp->pkt_private = bp;
13590 		*pktpp = pktp;
13591 
13592 		SD_TRACE(SD_LOG_IO_CORE, un,
13593 		    "sd_initpkt_for_buf: exit: buf:0x%p\n", bp);
13594 
13595 #if defined(__i386) || defined(__amd64)	/* DMAFREE for x86 only */
13596 		xp->xb_pkt_flags &= ~SD_XB_DMA_FREED;
13597 #endif
13598 
13599 		mutex_enter(SD_MUTEX(un));
13600 		return (SD_PKT_ALLOC_SUCCESS);
13601 
13602 	}
13603 
13604 	/*
13605 	 * SD_PKT_ALLOC_FAILURE is the only expected failure code
13606 	 * from sd_setup_rw_pkt.
13607 	 */
13608 	ASSERT(rval == SD_PKT_ALLOC_FAILURE);
13609 
13610 	if (rval == SD_PKT_ALLOC_FAILURE) {
13611 		*pktpp = NULL;
13612 		/*
13613 		 * Set the driver state to RWAIT to indicate the driver
13614 		 * is waiting on resource allocations. The driver will not
13615 		 * suspend, pm_suspend, or detatch while the state is RWAIT.
13616 		 */
13617 		mutex_enter(SD_MUTEX(un));
13618 		New_state(un, SD_STATE_RWAIT);
13619 
13620 		SD_ERROR(SD_LOG_IO_CORE, un,
13621 		    "sd_initpkt_for_buf: No pktp. exit bp:0x%p\n", bp);
13622 
13623 		if ((bp->b_flags & B_ERROR) != 0) {
13624 			return (SD_PKT_ALLOC_FAILURE_NO_DMA);
13625 		}
13626 		return (SD_PKT_ALLOC_FAILURE);
13627 	} else {
13628 		/*
13629 		 * PKT_ALLOC_FAILURE_CDB_TOO_SMALL
13630 		 *
13631 		 * This should never happen.  Maybe someone messed with the
13632 		 * kernel's minphys?
13633 		 */
13634 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
13635 		    "Request rejected: too large for CDB: "
13636 		    "lba:0x%08lx  len:0x%08lx\n", startblock, blockcount);
13637 		SD_ERROR(SD_LOG_IO_CORE, un,
13638 		    "sd_initpkt_for_buf: No cp. exit bp:0x%p\n", bp);
13639 		mutex_enter(SD_MUTEX(un));
13640 		return (SD_PKT_ALLOC_FAILURE_CDB_TOO_SMALL);
13641 
13642 	}
13643 }
13644 
13645 
13646 /*
13647  *    Function: sd_destroypkt_for_buf
13648  *
13649  * Description: Free the scsi_pkt(9S) for the given bp (buf IO processing).
13650  *
13651  *     Context: Kernel thread or interrupt context
13652  */
13653 
13654 static void
13655 sd_destroypkt_for_buf(struct buf *bp)
13656 {
13657 	ASSERT(bp != NULL);
13658 	ASSERT(SD_GET_UN(bp) != NULL);
13659 
13660 	SD_TRACE(SD_LOG_IO_CORE, SD_GET_UN(bp),
13661 	    "sd_destroypkt_for_buf: entry: buf:0x%p\n", bp);
13662 
13663 	ASSERT(SD_GET_PKTP(bp) != NULL);
13664 	scsi_destroy_pkt(SD_GET_PKTP(bp));
13665 
13666 	SD_TRACE(SD_LOG_IO_CORE, SD_GET_UN(bp),
13667 	    "sd_destroypkt_for_buf: exit: buf:0x%p\n", bp);
13668 }
13669 
13670 /*
13671  *    Function: sd_setup_rw_pkt
13672  *
13673  * Description: Determines appropriate CDB group for the requested LBA
13674  *		and transfer length, calls scsi_init_pkt, and builds
13675  *		the CDB.  Do not use for partial DMA transfers except
13676  *		for the initial transfer since the CDB size must
13677  *		remain constant.
13678  *
13679  *     Context: Kernel thread and may be called from software interrupt
13680  *		context as part of a sdrunout callback. This function may not
13681  *		block or call routines that block
13682  */
13683 
13684 
13685 int
13686 sd_setup_rw_pkt(struct sd_lun *un,
13687     struct scsi_pkt **pktpp, struct buf *bp, int flags,
13688     int (*callback)(caddr_t), caddr_t callback_arg,
13689     diskaddr_t lba, uint32_t blockcount)
13690 {
13691 	struct scsi_pkt *return_pktp;
13692 	union scsi_cdb *cdbp;
13693 	struct sd_cdbinfo *cp = NULL;
13694 	int i;
13695 
13696 	/*
13697 	 * See which size CDB to use, based upon the request.
13698 	 */
13699 	for (i = un->un_mincdb; i <= un->un_maxcdb; i++) {
13700 
13701 		/*
13702 		 * Check lba and block count against sd_cdbtab limits.
13703 		 * In the partial DMA case, we have to use the same size
13704 		 * CDB for all the transfers.  Check lba + blockcount
13705 		 * against the max LBA so we know that segment of the
13706 		 * transfer can use the CDB we select.
13707 		 */
13708 		if ((lba + blockcount - 1 <= sd_cdbtab[i].sc_maxlba) &&
13709 		    (blockcount <= sd_cdbtab[i].sc_maxlen)) {
13710 
13711 			/*
13712 			 * The command will fit into the CDB type
13713 			 * specified by sd_cdbtab[i].
13714 			 */
13715 			cp = sd_cdbtab + i;
13716 
13717 			/*
13718 			 * Call scsi_init_pkt so we can fill in the
13719 			 * CDB.
13720 			 */
13721 			return_pktp = scsi_init_pkt(SD_ADDRESS(un), *pktpp,
13722 			    bp, cp->sc_grpcode, un->un_status_len, 0,
13723 			    flags, callback, callback_arg);
13724 
13725 			if (return_pktp != NULL) {
13726 
13727 				/*
13728 				 * Return new value of pkt
13729 				 */
13730 				*pktpp = return_pktp;
13731 
13732 				/*
13733 				 * To be safe, zero the CDB insuring there is
13734 				 * no leftover data from a previous command.
13735 				 */
13736 				bzero(return_pktp->pkt_cdbp, cp->sc_grpcode);
13737 
13738 				/*
13739 				 * Handle partial DMA mapping
13740 				 */
13741 				if (return_pktp->pkt_resid != 0) {
13742 
13743 					/*
13744 					 * Not going to xfer as many blocks as
13745 					 * originally expected
13746 					 */
13747 					blockcount -=
13748 					    SD_BYTES2TGTBLOCKS(un,
13749 					    return_pktp->pkt_resid);
13750 				}
13751 
13752 				cdbp = (union scsi_cdb *)return_pktp->pkt_cdbp;
13753 
13754 				/*
13755 				 * Set command byte based on the CDB
13756 				 * type we matched.
13757 				 */
13758 				cdbp->scc_cmd = cp->sc_grpmask |
13759 				    ((bp->b_flags & B_READ) ?
13760 				    SCMD_READ : SCMD_WRITE);
13761 
13762 				SD_FILL_SCSI1_LUN(un, return_pktp);
13763 
13764 				/*
13765 				 * Fill in LBA and length
13766 				 */
13767 				ASSERT((cp->sc_grpcode == CDB_GROUP1) ||
13768 				    (cp->sc_grpcode == CDB_GROUP4) ||
13769 				    (cp->sc_grpcode == CDB_GROUP0) ||
13770 				    (cp->sc_grpcode == CDB_GROUP5));
13771 
13772 				if (cp->sc_grpcode == CDB_GROUP1) {
13773 					FORMG1ADDR(cdbp, lba);
13774 					FORMG1COUNT(cdbp, blockcount);
13775 					return (0);
13776 				} else if (cp->sc_grpcode == CDB_GROUP4) {
13777 					FORMG4LONGADDR(cdbp, lba);
13778 					FORMG4COUNT(cdbp, blockcount);
13779 					return (0);
13780 				} else if (cp->sc_grpcode == CDB_GROUP0) {
13781 					FORMG0ADDR(cdbp, lba);
13782 					FORMG0COUNT(cdbp, blockcount);
13783 					return (0);
13784 				} else if (cp->sc_grpcode == CDB_GROUP5) {
13785 					FORMG5ADDR(cdbp, lba);
13786 					FORMG5COUNT(cdbp, blockcount);
13787 					return (0);
13788 				}
13789 
13790 				/*
13791 				 * It should be impossible to not match one
13792 				 * of the CDB types above, so we should never
13793 				 * reach this point.  Set the CDB command byte
13794 				 * to test-unit-ready to avoid writing
13795 				 * to somewhere we don't intend.
13796 				 */
13797 				cdbp->scc_cmd = SCMD_TEST_UNIT_READY;
13798 				return (SD_PKT_ALLOC_FAILURE_CDB_TOO_SMALL);
13799 			} else {
13800 				/*
13801 				 * Couldn't get scsi_pkt
13802 				 */
13803 				return (SD_PKT_ALLOC_FAILURE);
13804 			}
13805 		}
13806 	}
13807 
13808 	/*
13809 	 * None of the available CDB types were suitable.  This really
13810 	 * should never happen:  on a 64 bit system we support
13811 	 * READ16/WRITE16 which will hold an entire 64 bit disk address
13812 	 * and on a 32 bit system we will refuse to bind to a device
13813 	 * larger than 2TB so addresses will never be larger than 32 bits.
13814 	 */
13815 	return (SD_PKT_ALLOC_FAILURE_CDB_TOO_SMALL);
13816 }
13817 
13818 /*
13819  *    Function: sd_setup_next_rw_pkt
13820  *
13821  * Description: Setup packet for partial DMA transfers, except for the
13822  * 		initial transfer.  sd_setup_rw_pkt should be used for
13823  *		the initial transfer.
13824  *
13825  *     Context: Kernel thread and may be called from interrupt context.
13826  */
13827 
13828 int
13829 sd_setup_next_rw_pkt(struct sd_lun *un,
13830     struct scsi_pkt *pktp, struct buf *bp,
13831     diskaddr_t lba, uint32_t blockcount)
13832 {
13833 	uchar_t com;
13834 	union scsi_cdb *cdbp;
13835 	uchar_t cdb_group_id;
13836 
13837 	ASSERT(pktp != NULL);
13838 	ASSERT(pktp->pkt_cdbp != NULL);
13839 
13840 	cdbp = (union scsi_cdb *)pktp->pkt_cdbp;
13841 	com = cdbp->scc_cmd;
13842 	cdb_group_id = CDB_GROUPID(com);
13843 
13844 	ASSERT((cdb_group_id == CDB_GROUPID_0) ||
13845 	    (cdb_group_id == CDB_GROUPID_1) ||
13846 	    (cdb_group_id == CDB_GROUPID_4) ||
13847 	    (cdb_group_id == CDB_GROUPID_5));
13848 
13849 	/*
13850 	 * Move pkt to the next portion of the xfer.
13851 	 * func is NULL_FUNC so we do not have to release
13852 	 * the disk mutex here.
13853 	 */
13854 	if (scsi_init_pkt(SD_ADDRESS(un), pktp, bp, 0, 0, 0, 0,
13855 	    NULL_FUNC, NULL) == pktp) {
13856 		/* Success.  Handle partial DMA */
13857 		if (pktp->pkt_resid != 0) {
13858 			blockcount -=
13859 			    SD_BYTES2TGTBLOCKS(un, pktp->pkt_resid);
13860 		}
13861 
13862 		cdbp->scc_cmd = com;
13863 		SD_FILL_SCSI1_LUN(un, pktp);
13864 		if (cdb_group_id == CDB_GROUPID_1) {
13865 			FORMG1ADDR(cdbp, lba);
13866 			FORMG1COUNT(cdbp, blockcount);
13867 			return (0);
13868 		} else if (cdb_group_id == CDB_GROUPID_4) {
13869 			FORMG4LONGADDR(cdbp, lba);
13870 			FORMG4COUNT(cdbp, blockcount);
13871 			return (0);
13872 		} else if (cdb_group_id == CDB_GROUPID_0) {
13873 			FORMG0ADDR(cdbp, lba);
13874 			FORMG0COUNT(cdbp, blockcount);
13875 			return (0);
13876 		} else if (cdb_group_id == CDB_GROUPID_5) {
13877 			FORMG5ADDR(cdbp, lba);
13878 			FORMG5COUNT(cdbp, blockcount);
13879 			return (0);
13880 		}
13881 
13882 		/* Unreachable */
13883 		return (SD_PKT_ALLOC_FAILURE_CDB_TOO_SMALL);
13884 	}
13885 
13886 	/*
13887 	 * Error setting up next portion of cmd transfer.
13888 	 * Something is definitely very wrong and this
13889 	 * should not happen.
13890 	 */
13891 	return (SD_PKT_ALLOC_FAILURE);
13892 }
13893 
13894 /*
13895  *    Function: sd_initpkt_for_uscsi
13896  *
13897  * Description: Allocate and initialize for transport a scsi_pkt struct,
13898  *		based upon the info specified in the given uscsi_cmd struct.
13899  *
13900  * Return Code: SD_PKT_ALLOC_SUCCESS
13901  *		SD_PKT_ALLOC_FAILURE
13902  *		SD_PKT_ALLOC_FAILURE_NO_DMA
13903  *		SD_PKT_ALLOC_FAILURE_CDB_TOO_SMALL
13904  *
13905  *     Context: Kernel thread and may be called from software interrupt context
13906  *		as part of a sdrunout callback. This function may not block or
13907  *		call routines that block
13908  */
13909 
13910 static int
13911 sd_initpkt_for_uscsi(struct buf *bp, struct scsi_pkt **pktpp)
13912 {
13913 	struct uscsi_cmd *uscmd;
13914 	struct sd_xbuf	*xp;
13915 	struct scsi_pkt	*pktp;
13916 	struct sd_lun	*un;
13917 	uint32_t	flags = 0;
13918 
13919 	ASSERT(bp != NULL);
13920 	ASSERT(pktpp != NULL);
13921 	xp = SD_GET_XBUF(bp);
13922 	ASSERT(xp != NULL);
13923 	un = SD_GET_UN(bp);
13924 	ASSERT(un != NULL);
13925 	ASSERT(mutex_owned(SD_MUTEX(un)));
13926 
13927 	/* The pointer to the uscsi_cmd struct is expected in xb_pktinfo */
13928 	uscmd = (struct uscsi_cmd *)xp->xb_pktinfo;
13929 	ASSERT(uscmd != NULL);
13930 
13931 	SD_TRACE(SD_LOG_IO_CORE, un,
13932 	    "sd_initpkt_for_uscsi: entry: buf:0x%p\n", bp);
13933 
13934 	/*
13935 	 * Allocate the scsi_pkt for the command.
13936 	 * Note: If PKT_DMA_PARTIAL flag is set, scsi_vhci binds a path
13937 	 *	 during scsi_init_pkt time and will continue to use the
13938 	 *	 same path as long as the same scsi_pkt is used without
13939 	 *	 intervening scsi_dma_free(). Since uscsi command does
13940 	 *	 not call scsi_dmafree() before retry failed command, it
13941 	 *	 is necessary to make sure PKT_DMA_PARTIAL flag is NOT
13942 	 *	 set such that scsi_vhci can use other available path for
13943 	 *	 retry. Besides, ucsci command does not allow DMA breakup,
13944 	 *	 so there is no need to set PKT_DMA_PARTIAL flag.
13945 	 */
13946 	if (uscmd->uscsi_rqlen > SENSE_LENGTH) {
13947 		pktp = scsi_init_pkt(SD_ADDRESS(un), NULL,
13948 		    ((bp->b_bcount != 0) ? bp : NULL), uscmd->uscsi_cdblen,
13949 		    ((int)(uscmd->uscsi_rqlen) + sizeof (struct scsi_arq_status)
13950 		    - sizeof (struct scsi_extended_sense)), 0,
13951 		    (un->un_pkt_flags & ~PKT_DMA_PARTIAL) | PKT_XARQ,
13952 		    sdrunout, (caddr_t)un);
13953 	} else {
13954 		pktp = scsi_init_pkt(SD_ADDRESS(un), NULL,
13955 		    ((bp->b_bcount != 0) ? bp : NULL), uscmd->uscsi_cdblen,
13956 		    sizeof (struct scsi_arq_status), 0,
13957 		    (un->un_pkt_flags & ~PKT_DMA_PARTIAL),
13958 		    sdrunout, (caddr_t)un);
13959 	}
13960 
13961 	if (pktp == NULL) {
13962 		*pktpp = NULL;
13963 		/*
13964 		 * Set the driver state to RWAIT to indicate the driver
13965 		 * is waiting on resource allocations. The driver will not
13966 		 * suspend, pm_suspend, or detatch while the state is RWAIT.
13967 		 */
13968 		New_state(un, SD_STATE_RWAIT);
13969 
13970 		SD_ERROR(SD_LOG_IO_CORE, un,
13971 		    "sd_initpkt_for_uscsi: No pktp. exit bp:0x%p\n", bp);
13972 
13973 		if ((bp->b_flags & B_ERROR) != 0) {
13974 			return (SD_PKT_ALLOC_FAILURE_NO_DMA);
13975 		}
13976 		return (SD_PKT_ALLOC_FAILURE);
13977 	}
13978 
13979 	/*
13980 	 * We do not do DMA breakup for USCSI commands, so return failure
13981 	 * here if all the needed DMA resources were not allocated.
13982 	 */
13983 	if ((un->un_pkt_flags & PKT_DMA_PARTIAL) &&
13984 	    (bp->b_bcount != 0) && (pktp->pkt_resid != 0)) {
13985 		scsi_destroy_pkt(pktp);
13986 		SD_ERROR(SD_LOG_IO_CORE, un, "sd_initpkt_for_uscsi: "
13987 		    "No partial DMA for USCSI. exit: buf:0x%p\n", bp);
13988 		return (SD_PKT_ALLOC_FAILURE_PKT_TOO_SMALL);
13989 	}
13990 
13991 	/* Init the cdb from the given uscsi struct */
13992 	(void) scsi_setup_cdb((union scsi_cdb *)pktp->pkt_cdbp,
13993 	    uscmd->uscsi_cdb[0], 0, 0, 0);
13994 
13995 	SD_FILL_SCSI1_LUN(un, pktp);
13996 
13997 	/*
13998 	 * Set up the optional USCSI flags. See the uscsi (7I) man page
13999 	 * for listing of the supported flags.
14000 	 */
14001 
14002 	if (uscmd->uscsi_flags & USCSI_SILENT) {
14003 		flags |= FLAG_SILENT;
14004 	}
14005 
14006 	if (uscmd->uscsi_flags & USCSI_DIAGNOSE) {
14007 		flags |= FLAG_DIAGNOSE;
14008 	}
14009 
14010 	if (uscmd->uscsi_flags & USCSI_ISOLATE) {
14011 		flags |= FLAG_ISOLATE;
14012 	}
14013 
14014 	if (un->un_f_is_fibre == FALSE) {
14015 		if (uscmd->uscsi_flags & USCSI_RENEGOT) {
14016 			flags |= FLAG_RENEGOTIATE_WIDE_SYNC;
14017 		}
14018 	}
14019 
14020 	/*
14021 	 * Set the pkt flags here so we save time later.
14022 	 * Note: These flags are NOT in the uscsi man page!!!
14023 	 */
14024 	if (uscmd->uscsi_flags & USCSI_HEAD) {
14025 		flags |= FLAG_HEAD;
14026 	}
14027 
14028 	if (uscmd->uscsi_flags & USCSI_NOINTR) {
14029 		flags |= FLAG_NOINTR;
14030 	}
14031 
14032 	/*
14033 	 * For tagged queueing, things get a bit complicated.
14034 	 * Check first for head of queue and last for ordered queue.
14035 	 * If neither head nor order, use the default driver tag flags.
14036 	 */
14037 	if ((uscmd->uscsi_flags & USCSI_NOTAG) == 0) {
14038 		if (uscmd->uscsi_flags & USCSI_HTAG) {
14039 			flags |= FLAG_HTAG;
14040 		} else if (uscmd->uscsi_flags & USCSI_OTAG) {
14041 			flags |= FLAG_OTAG;
14042 		} else {
14043 			flags |= un->un_tagflags & FLAG_TAGMASK;
14044 		}
14045 	}
14046 
14047 	if (uscmd->uscsi_flags & USCSI_NODISCON) {
14048 		flags = (flags & ~FLAG_TAGMASK) | FLAG_NODISCON;
14049 	}
14050 
14051 	pktp->pkt_flags = flags;
14052 
14053 	/* Transfer uscsi information to scsi_pkt */
14054 	(void) scsi_uscsi_pktinit(uscmd, pktp);
14055 
14056 	/* Copy the caller's CDB into the pkt... */
14057 	bcopy(uscmd->uscsi_cdb, pktp->pkt_cdbp, uscmd->uscsi_cdblen);
14058 
14059 	if (uscmd->uscsi_timeout == 0) {
14060 		pktp->pkt_time = un->un_uscsi_timeout;
14061 	} else {
14062 		pktp->pkt_time = uscmd->uscsi_timeout;
14063 	}
14064 
14065 	/* need it later to identify USCSI request in sdintr */
14066 	xp->xb_pkt_flags |= SD_XB_USCSICMD;
14067 
14068 	xp->xb_sense_resid = uscmd->uscsi_rqresid;
14069 
14070 	pktp->pkt_private = bp;
14071 	pktp->pkt_comp = sdintr;
14072 	*pktpp = pktp;
14073 
14074 	SD_TRACE(SD_LOG_IO_CORE, un,
14075 	    "sd_initpkt_for_uscsi: exit: buf:0x%p\n", bp);
14076 
14077 	return (SD_PKT_ALLOC_SUCCESS);
14078 }
14079 
14080 
14081 /*
14082  *    Function: sd_destroypkt_for_uscsi
14083  *
14084  * Description: Free the scsi_pkt(9S) struct for the given bp, for uscsi
14085  *		IOs.. Also saves relevant info into the associated uscsi_cmd
14086  *		struct.
14087  *
14088  *     Context: May be called under interrupt context
14089  */
14090 
14091 static void
14092 sd_destroypkt_for_uscsi(struct buf *bp)
14093 {
14094 	struct uscsi_cmd *uscmd;
14095 	struct sd_xbuf	*xp;
14096 	struct scsi_pkt	*pktp;
14097 	struct sd_lun	*un;
14098 	struct sd_uscsi_info *suip;
14099 
14100 	ASSERT(bp != NULL);
14101 	xp = SD_GET_XBUF(bp);
14102 	ASSERT(xp != NULL);
14103 	un = SD_GET_UN(bp);
14104 	ASSERT(un != NULL);
14105 	ASSERT(!mutex_owned(SD_MUTEX(un)));
14106 	pktp = SD_GET_PKTP(bp);
14107 	ASSERT(pktp != NULL);
14108 
14109 	SD_TRACE(SD_LOG_IO_CORE, un,
14110 	    "sd_destroypkt_for_uscsi: entry: buf:0x%p\n", bp);
14111 
14112 	/* The pointer to the uscsi_cmd struct is expected in xb_pktinfo */
14113 	uscmd = (struct uscsi_cmd *)xp->xb_pktinfo;
14114 	ASSERT(uscmd != NULL);
14115 
14116 	/* Save the status and the residual into the uscsi_cmd struct */
14117 	uscmd->uscsi_status = ((*(pktp)->pkt_scbp) & STATUS_MASK);
14118 	uscmd->uscsi_resid  = bp->b_resid;
14119 
14120 	/* Transfer scsi_pkt information to uscsi */
14121 	(void) scsi_uscsi_pktfini(pktp, uscmd);
14122 
14123 	/*
14124 	 * If enabled, copy any saved sense data into the area specified
14125 	 * by the uscsi command.
14126 	 */
14127 	if (((uscmd->uscsi_flags & USCSI_RQENABLE) != 0) &&
14128 	    (uscmd->uscsi_rqlen != 0) && (uscmd->uscsi_rqbuf != NULL)) {
14129 		/*
14130 		 * Note: uscmd->uscsi_rqbuf should always point to a buffer
14131 		 * at least SENSE_LENGTH bytes in size (see sd_send_scsi_cmd())
14132 		 */
14133 		uscmd->uscsi_rqstatus = xp->xb_sense_status;
14134 		uscmd->uscsi_rqresid  = xp->xb_sense_resid;
14135 		if (uscmd->uscsi_rqlen > SENSE_LENGTH) {
14136 			bcopy(xp->xb_sense_data, uscmd->uscsi_rqbuf,
14137 			    MAX_SENSE_LENGTH);
14138 		} else {
14139 			bcopy(xp->xb_sense_data, uscmd->uscsi_rqbuf,
14140 			    SENSE_LENGTH);
14141 		}
14142 	}
14143 	/*
14144 	 * The following assignments are for SCSI FMA.
14145 	 */
14146 	ASSERT(xp->xb_private != NULL);
14147 	suip = (struct sd_uscsi_info *)xp->xb_private;
14148 	suip->ui_pkt_reason = pktp->pkt_reason;
14149 	suip->ui_pkt_state = pktp->pkt_state;
14150 	suip->ui_pkt_statistics = pktp->pkt_statistics;
14151 	suip->ui_lba = (uint64_t)SD_GET_BLKNO(bp);
14152 
14153 	/* We are done with the scsi_pkt; free it now */
14154 	ASSERT(SD_GET_PKTP(bp) != NULL);
14155 	scsi_destroy_pkt(SD_GET_PKTP(bp));
14156 
14157 	SD_TRACE(SD_LOG_IO_CORE, un,
14158 	    "sd_destroypkt_for_uscsi: exit: buf:0x%p\n", bp);
14159 }
14160 
14161 
14162 /*
14163  *    Function: sd_bioclone_alloc
14164  *
14165  * Description: Allocate a buf(9S) and init it as per the given buf
14166  *		and the various arguments.  The associated sd_xbuf
14167  *		struct is (nearly) duplicated.  The struct buf *bp
14168  *		argument is saved in new_xp->xb_private.
14169  *
14170  *   Arguments: bp - ptr the the buf(9S) to be "shadowed"
14171  *		datalen - size of data area for the shadow bp
14172  *		blkno - starting LBA
14173  *		func - function pointer for b_iodone in the shadow buf. (May
14174  *			be NULL if none.)
14175  *
14176  * Return Code: Pointer to allocates buf(9S) struct
14177  *
14178  *     Context: Can sleep.
14179  */
14180 
14181 static struct buf *
14182 sd_bioclone_alloc(struct buf *bp, size_t datalen,
14183 	daddr_t blkno, int (*func)(struct buf *))
14184 {
14185 	struct	sd_lun	*un;
14186 	struct	sd_xbuf	*xp;
14187 	struct	sd_xbuf	*new_xp;
14188 	struct	buf	*new_bp;
14189 
14190 	ASSERT(bp != NULL);
14191 	xp = SD_GET_XBUF(bp);
14192 	ASSERT(xp != NULL);
14193 	un = SD_GET_UN(bp);
14194 	ASSERT(un != NULL);
14195 	ASSERT(!mutex_owned(SD_MUTEX(un)));
14196 
14197 	new_bp = bioclone(bp, 0, datalen, SD_GET_DEV(un), blkno, func,
14198 	    NULL, KM_SLEEP);
14199 
14200 	new_bp->b_lblkno	= blkno;
14201 
14202 	/*
14203 	 * Allocate an xbuf for the shadow bp and copy the contents of the
14204 	 * original xbuf into it.
14205 	 */
14206 	new_xp = kmem_alloc(sizeof (struct sd_xbuf), KM_SLEEP);
14207 	bcopy(xp, new_xp, sizeof (struct sd_xbuf));
14208 
14209 	/*
14210 	 * The given bp is automatically saved in the xb_private member
14211 	 * of the new xbuf.  Callers are allowed to depend on this.
14212 	 */
14213 	new_xp->xb_private = bp;
14214 
14215 	new_bp->b_private  = new_xp;
14216 
14217 	return (new_bp);
14218 }
14219 
14220 /*
14221  *    Function: sd_shadow_buf_alloc
14222  *
14223  * Description: Allocate a buf(9S) and init it as per the given buf
14224  *		and the various arguments.  The associated sd_xbuf
14225  *		struct is (nearly) duplicated.  The struct buf *bp
14226  *		argument is saved in new_xp->xb_private.
14227  *
14228  *   Arguments: bp - ptr the the buf(9S) to be "shadowed"
14229  *		datalen - size of data area for the shadow bp
14230  *		bflags - B_READ or B_WRITE (pseudo flag)
14231  *		blkno - starting LBA
14232  *		func - function pointer for b_iodone in the shadow buf. (May
14233  *			be NULL if none.)
14234  *
14235  * Return Code: Pointer to allocates buf(9S) struct
14236  *
14237  *     Context: Can sleep.
14238  */
14239 
14240 static struct buf *
14241 sd_shadow_buf_alloc(struct buf *bp, size_t datalen, uint_t bflags,
14242 	daddr_t blkno, int (*func)(struct buf *))
14243 {
14244 	struct	sd_lun	*un;
14245 	struct	sd_xbuf	*xp;
14246 	struct	sd_xbuf	*new_xp;
14247 	struct	buf	*new_bp;
14248 
14249 	ASSERT(bp != NULL);
14250 	xp = SD_GET_XBUF(bp);
14251 	ASSERT(xp != NULL);
14252 	un = SD_GET_UN(bp);
14253 	ASSERT(un != NULL);
14254 	ASSERT(!mutex_owned(SD_MUTEX(un)));
14255 
14256 	if (bp->b_flags & (B_PAGEIO | B_PHYS)) {
14257 		bp_mapin(bp);
14258 	}
14259 
14260 	bflags &= (B_READ | B_WRITE);
14261 #if defined(__i386) || defined(__amd64)
14262 	new_bp = getrbuf(KM_SLEEP);
14263 	new_bp->b_un.b_addr = kmem_zalloc(datalen, KM_SLEEP);
14264 	new_bp->b_bcount = datalen;
14265 	new_bp->b_flags = bflags |
14266 	    (bp->b_flags & ~(B_PAGEIO | B_PHYS | B_REMAPPED | B_SHADOW));
14267 #else
14268 	new_bp = scsi_alloc_consistent_buf(SD_ADDRESS(un), NULL,
14269 	    datalen, bflags, SLEEP_FUNC, NULL);
14270 #endif
14271 	new_bp->av_forw	= NULL;
14272 	new_bp->av_back	= NULL;
14273 	new_bp->b_dev	= bp->b_dev;
14274 	new_bp->b_blkno	= blkno;
14275 	new_bp->b_iodone = func;
14276 	new_bp->b_edev	= bp->b_edev;
14277 	new_bp->b_resid	= 0;
14278 
14279 	/* We need to preserve the B_FAILFAST flag */
14280 	if (bp->b_flags & B_FAILFAST) {
14281 		new_bp->b_flags |= B_FAILFAST;
14282 	}
14283 
14284 	/*
14285 	 * Allocate an xbuf for the shadow bp and copy the contents of the
14286 	 * original xbuf into it.
14287 	 */
14288 	new_xp = kmem_alloc(sizeof (struct sd_xbuf), KM_SLEEP);
14289 	bcopy(xp, new_xp, sizeof (struct sd_xbuf));
14290 
14291 	/* Need later to copy data between the shadow buf & original buf! */
14292 	new_xp->xb_pkt_flags |= PKT_CONSISTENT;
14293 
14294 	/*
14295 	 * The given bp is automatically saved in the xb_private member
14296 	 * of the new xbuf.  Callers are allowed to depend on this.
14297 	 */
14298 	new_xp->xb_private = bp;
14299 
14300 	new_bp->b_private  = new_xp;
14301 
14302 	return (new_bp);
14303 }
14304 
14305 /*
14306  *    Function: sd_bioclone_free
14307  *
14308  * Description: Deallocate a buf(9S) that was used for 'shadow' IO operations
14309  *		in the larger than partition operation.
14310  *
14311  *     Context: May be called under interrupt context
14312  */
14313 
14314 static void
14315 sd_bioclone_free(struct buf *bp)
14316 {
14317 	struct sd_xbuf	*xp;
14318 
14319 	ASSERT(bp != NULL);
14320 	xp = SD_GET_XBUF(bp);
14321 	ASSERT(xp != NULL);
14322 
14323 	/*
14324 	 * Call bp_mapout() before freeing the buf,  in case a lower
14325 	 * layer or HBA  had done a bp_mapin().  we must do this here
14326 	 * as we are the "originator" of the shadow buf.
14327 	 */
14328 	bp_mapout(bp);
14329 
14330 	/*
14331 	 * Null out b_iodone before freeing the bp, to ensure that the driver
14332 	 * never gets confused by a stale value in this field. (Just a little
14333 	 * extra defensiveness here.)
14334 	 */
14335 	bp->b_iodone = NULL;
14336 
14337 	freerbuf(bp);
14338 
14339 	kmem_free(xp, sizeof (struct sd_xbuf));
14340 }
14341 
14342 /*
14343  *    Function: sd_shadow_buf_free
14344  *
14345  * Description: Deallocate a buf(9S) that was used for 'shadow' IO operations.
14346  *
14347  *     Context: May be called under interrupt context
14348  */
14349 
14350 static void
14351 sd_shadow_buf_free(struct buf *bp)
14352 {
14353 	struct sd_xbuf	*xp;
14354 
14355 	ASSERT(bp != NULL);
14356 	xp = SD_GET_XBUF(bp);
14357 	ASSERT(xp != NULL);
14358 
14359 #if defined(__sparc)
14360 	/*
14361 	 * Call bp_mapout() before freeing the buf,  in case a lower
14362 	 * layer or HBA  had done a bp_mapin().  we must do this here
14363 	 * as we are the "originator" of the shadow buf.
14364 	 */
14365 	bp_mapout(bp);
14366 #endif
14367 
14368 	/*
14369 	 * Null out b_iodone before freeing the bp, to ensure that the driver
14370 	 * never gets confused by a stale value in this field. (Just a little
14371 	 * extra defensiveness here.)
14372 	 */
14373 	bp->b_iodone = NULL;
14374 
14375 #if defined(__i386) || defined(__amd64)
14376 	kmem_free(bp->b_un.b_addr, bp->b_bcount);
14377 	freerbuf(bp);
14378 #else
14379 	scsi_free_consistent_buf(bp);
14380 #endif
14381 
14382 	kmem_free(xp, sizeof (struct sd_xbuf));
14383 }
14384 
14385 
14386 /*
14387  *    Function: sd_print_transport_rejected_message
14388  *
14389  * Description: This implements the ludicrously complex rules for printing
14390  *		a "transport rejected" message.  This is to address the
14391  *		specific problem of having a flood of this error message
14392  *		produced when a failover occurs.
14393  *
14394  *     Context: Any.
14395  */
14396 
14397 static void
14398 sd_print_transport_rejected_message(struct sd_lun *un, struct sd_xbuf *xp,
14399 	int code)
14400 {
14401 	ASSERT(un != NULL);
14402 	ASSERT(mutex_owned(SD_MUTEX(un)));
14403 	ASSERT(xp != NULL);
14404 
14405 	/*
14406 	 * Print the "transport rejected" message under the following
14407 	 * conditions:
14408 	 *
14409 	 * - Whenever the SD_LOGMASK_DIAG bit of sd_level_mask is set
14410 	 * - The error code from scsi_transport() is NOT a TRAN_FATAL_ERROR.
14411 	 * - If the error code IS a TRAN_FATAL_ERROR, then the message is
14412 	 *   printed the FIRST time a TRAN_FATAL_ERROR is returned from
14413 	 *   scsi_transport(9F) (which indicates that the target might have
14414 	 *   gone off-line).  This uses the un->un_tran_fatal_count
14415 	 *   count, which is incremented whenever a TRAN_FATAL_ERROR is
14416 	 *   received, and reset to zero whenver a TRAN_ACCEPT is returned
14417 	 *   from scsi_transport().
14418 	 *
14419 	 * The FLAG_SILENT in the scsi_pkt must be CLEARED in ALL of
14420 	 * the preceeding cases in order for the message to be printed.
14421 	 */
14422 	if (((xp->xb_pktp->pkt_flags & FLAG_SILENT) == 0) &&
14423 	    (SD_FM_LOG(un) == SD_FM_LOG_NSUP)) {
14424 		if ((sd_level_mask & SD_LOGMASK_DIAG) ||
14425 		    (code != TRAN_FATAL_ERROR) ||
14426 		    (un->un_tran_fatal_count == 1)) {
14427 			switch (code) {
14428 			case TRAN_BADPKT:
14429 				scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
14430 				    "transport rejected bad packet\n");
14431 				break;
14432 			case TRAN_FATAL_ERROR:
14433 				scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
14434 				    "transport rejected fatal error\n");
14435 				break;
14436 			default:
14437 				scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
14438 				    "transport rejected (%d)\n", code);
14439 				break;
14440 			}
14441 		}
14442 	}
14443 }
14444 
14445 
14446 /*
14447  *    Function: sd_add_buf_to_waitq
14448  *
14449  * Description: Add the given buf(9S) struct to the wait queue for the
14450  *		instance.  If sorting is enabled, then the buf is added
14451  *		to the queue via an elevator sort algorithm (a la
14452  *		disksort(9F)).  The SD_GET_BLKNO(bp) is used as the sort key.
14453  *		If sorting is not enabled, then the buf is just added
14454  *		to the end of the wait queue.
14455  *
14456  * Return Code: void
14457  *
14458  *     Context: Does not sleep/block, therefore technically can be called
14459  *		from any context.  However if sorting is enabled then the
14460  *		execution time is indeterminate, and may take long if
14461  *		the wait queue grows large.
14462  */
14463 
14464 static void
14465 sd_add_buf_to_waitq(struct sd_lun *un, struct buf *bp)
14466 {
14467 	struct buf *ap;
14468 
14469 	ASSERT(bp != NULL);
14470 	ASSERT(un != NULL);
14471 	ASSERT(mutex_owned(SD_MUTEX(un)));
14472 
14473 	/* If the queue is empty, add the buf as the only entry & return. */
14474 	if (un->un_waitq_headp == NULL) {
14475 		ASSERT(un->un_waitq_tailp == NULL);
14476 		un->un_waitq_headp = un->un_waitq_tailp = bp;
14477 		bp->av_forw = NULL;
14478 		return;
14479 	}
14480 
14481 	ASSERT(un->un_waitq_tailp != NULL);
14482 
14483 	/*
14484 	 * If sorting is disabled, just add the buf to the tail end of
14485 	 * the wait queue and return.
14486 	 */
14487 	if (un->un_f_disksort_disabled) {
14488 		un->un_waitq_tailp->av_forw = bp;
14489 		un->un_waitq_tailp = bp;
14490 		bp->av_forw = NULL;
14491 		return;
14492 	}
14493 
14494 	/*
14495 	 * Sort thru the list of requests currently on the wait queue
14496 	 * and add the new buf request at the appropriate position.
14497 	 *
14498 	 * The un->un_waitq_headp is an activity chain pointer on which
14499 	 * we keep two queues, sorted in ascending SD_GET_BLKNO() order. The
14500 	 * first queue holds those requests which are positioned after
14501 	 * the current SD_GET_BLKNO() (in the first request); the second holds
14502 	 * requests which came in after their SD_GET_BLKNO() number was passed.
14503 	 * Thus we implement a one way scan, retracting after reaching
14504 	 * the end of the drive to the first request on the second
14505 	 * queue, at which time it becomes the first queue.
14506 	 * A one-way scan is natural because of the way UNIX read-ahead
14507 	 * blocks are allocated.
14508 	 *
14509 	 * If we lie after the first request, then we must locate the
14510 	 * second request list and add ourselves to it.
14511 	 */
14512 	ap = un->un_waitq_headp;
14513 	if (SD_GET_BLKNO(bp) < SD_GET_BLKNO(ap)) {
14514 		while (ap->av_forw != NULL) {
14515 			/*
14516 			 * Look for an "inversion" in the (normally
14517 			 * ascending) block numbers. This indicates
14518 			 * the start of the second request list.
14519 			 */
14520 			if (SD_GET_BLKNO(ap->av_forw) < SD_GET_BLKNO(ap)) {
14521 				/*
14522 				 * Search the second request list for the
14523 				 * first request at a larger block number.
14524 				 * We go before that; however if there is
14525 				 * no such request, we go at the end.
14526 				 */
14527 				do {
14528 					if (SD_GET_BLKNO(bp) <
14529 					    SD_GET_BLKNO(ap->av_forw)) {
14530 						goto insert;
14531 					}
14532 					ap = ap->av_forw;
14533 				} while (ap->av_forw != NULL);
14534 				goto insert;		/* after last */
14535 			}
14536 			ap = ap->av_forw;
14537 		}
14538 
14539 		/*
14540 		 * No inversions... we will go after the last, and
14541 		 * be the first request in the second request list.
14542 		 */
14543 		goto insert;
14544 	}
14545 
14546 	/*
14547 	 * Request is at/after the current request...
14548 	 * sort in the first request list.
14549 	 */
14550 	while (ap->av_forw != NULL) {
14551 		/*
14552 		 * We want to go after the current request (1) if
14553 		 * there is an inversion after it (i.e. it is the end
14554 		 * of the first request list), or (2) if the next
14555 		 * request is a larger block no. than our request.
14556 		 */
14557 		if ((SD_GET_BLKNO(ap->av_forw) < SD_GET_BLKNO(ap)) ||
14558 		    (SD_GET_BLKNO(bp) < SD_GET_BLKNO(ap->av_forw))) {
14559 			goto insert;
14560 		}
14561 		ap = ap->av_forw;
14562 	}
14563 
14564 	/*
14565 	 * Neither a second list nor a larger request, therefore
14566 	 * we go at the end of the first list (which is the same
14567 	 * as the end of the whole schebang).
14568 	 */
14569 insert:
14570 	bp->av_forw = ap->av_forw;
14571 	ap->av_forw = bp;
14572 
14573 	/*
14574 	 * If we inserted onto the tail end of the waitq, make sure the
14575 	 * tail pointer is updated.
14576 	 */
14577 	if (ap == un->un_waitq_tailp) {
14578 		un->un_waitq_tailp = bp;
14579 	}
14580 }
14581 
14582 
14583 /*
14584  *    Function: sd_start_cmds
14585  *
14586  * Description: Remove and transport cmds from the driver queues.
14587  *
14588  *   Arguments: un - pointer to the unit (soft state) struct for the target.
14589  *
14590  *		immed_bp - ptr to a buf to be transported immediately. Only
14591  *		the immed_bp is transported; bufs on the waitq are not
14592  *		processed and the un_retry_bp is not checked.  If immed_bp is
14593  *		NULL, then normal queue processing is performed.
14594  *
14595  *     Context: May be called from kernel thread context, interrupt context,
14596  *		or runout callback context. This function may not block or
14597  *		call routines that block.
14598  */
14599 
14600 static void
14601 sd_start_cmds(struct sd_lun *un, struct buf *immed_bp)
14602 {
14603 	struct	sd_xbuf	*xp;
14604 	struct	buf	*bp;
14605 	void	(*statp)(kstat_io_t *);
14606 #if defined(__i386) || defined(__amd64)	/* DMAFREE for x86 only */
14607 	void	(*saved_statp)(kstat_io_t *);
14608 #endif
14609 	int	rval;
14610 	struct sd_fm_internal *sfip = NULL;
14611 
14612 	ASSERT(un != NULL);
14613 	ASSERT(mutex_owned(SD_MUTEX(un)));
14614 	ASSERT(un->un_ncmds_in_transport >= 0);
14615 	ASSERT(un->un_throttle >= 0);
14616 
14617 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un, "sd_start_cmds: entry\n");
14618 
14619 	do {
14620 #if defined(__i386) || defined(__amd64)	/* DMAFREE for x86 only */
14621 		saved_statp = NULL;
14622 #endif
14623 
14624 		/*
14625 		 * If we are syncing or dumping, fail the command to
14626 		 * avoid recursively calling back into scsi_transport().
14627 		 * The dump I/O itself uses a separate code path so this
14628 		 * only prevents non-dump I/O from being sent while dumping.
14629 		 * File system sync takes place before dumping begins.
14630 		 * During panic, filesystem I/O is allowed provided
14631 		 * un_in_callback is <= 1.  This is to prevent recursion
14632 		 * such as sd_start_cmds -> scsi_transport -> sdintr ->
14633 		 * sd_start_cmds and so on.  See panic.c for more information
14634 		 * about the states the system can be in during panic.
14635 		 */
14636 		if ((un->un_state == SD_STATE_DUMPING) ||
14637 		    (ddi_in_panic() && (un->un_in_callback > 1))) {
14638 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
14639 			    "sd_start_cmds: panicking\n");
14640 			goto exit;
14641 		}
14642 
14643 		if ((bp = immed_bp) != NULL) {
14644 			/*
14645 			 * We have a bp that must be transported immediately.
14646 			 * It's OK to transport the immed_bp here without doing
14647 			 * the throttle limit check because the immed_bp is
14648 			 * always used in a retry/recovery case. This means
14649 			 * that we know we are not at the throttle limit by
14650 			 * virtue of the fact that to get here we must have
14651 			 * already gotten a command back via sdintr(). This also
14652 			 * relies on (1) the command on un_retry_bp preventing
14653 			 * further commands from the waitq from being issued;
14654 			 * and (2) the code in sd_retry_command checking the
14655 			 * throttle limit before issuing a delayed or immediate
14656 			 * retry. This holds even if the throttle limit is
14657 			 * currently ratcheted down from its maximum value.
14658 			 */
14659 			statp = kstat_runq_enter;
14660 			if (bp == un->un_retry_bp) {
14661 				ASSERT((un->un_retry_statp == NULL) ||
14662 				    (un->un_retry_statp == kstat_waitq_enter) ||
14663 				    (un->un_retry_statp ==
14664 				    kstat_runq_back_to_waitq));
14665 				/*
14666 				 * If the waitq kstat was incremented when
14667 				 * sd_set_retry_bp() queued this bp for a retry,
14668 				 * then we must set up statp so that the waitq
14669 				 * count will get decremented correctly below.
14670 				 * Also we must clear un->un_retry_statp to
14671 				 * ensure that we do not act on a stale value
14672 				 * in this field.
14673 				 */
14674 				if ((un->un_retry_statp == kstat_waitq_enter) ||
14675 				    (un->un_retry_statp ==
14676 				    kstat_runq_back_to_waitq)) {
14677 					statp = kstat_waitq_to_runq;
14678 				}
14679 #if defined(__i386) || defined(__amd64)	/* DMAFREE for x86 only */
14680 				saved_statp = un->un_retry_statp;
14681 #endif
14682 				un->un_retry_statp = NULL;
14683 
14684 				SD_TRACE(SD_LOG_IO | SD_LOG_ERROR, un,
14685 				    "sd_start_cmds: un:0x%p: GOT retry_bp:0x%p "
14686 				    "un_throttle:%d un_ncmds_in_transport:%d\n",
14687 				    un, un->un_retry_bp, un->un_throttle,
14688 				    un->un_ncmds_in_transport);
14689 			} else {
14690 				SD_TRACE(SD_LOG_IO_CORE, un, "sd_start_cmds: "
14691 				    "processing priority bp:0x%p\n", bp);
14692 			}
14693 
14694 		} else if ((bp = un->un_waitq_headp) != NULL) {
14695 			/*
14696 			 * A command on the waitq is ready to go, but do not
14697 			 * send it if:
14698 			 *
14699 			 * (1) the throttle limit has been reached, or
14700 			 * (2) a retry is pending, or
14701 			 * (3) a START_STOP_UNIT callback pending, or
14702 			 * (4) a callback for a SD_PATH_DIRECT_PRIORITY
14703 			 *	command is pending.
14704 			 *
14705 			 * For all of these conditions, IO processing will
14706 			 * restart after the condition is cleared.
14707 			 */
14708 			if (un->un_ncmds_in_transport >= un->un_throttle) {
14709 				SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
14710 				    "sd_start_cmds: exiting, "
14711 				    "throttle limit reached!\n");
14712 				goto exit;
14713 			}
14714 			if (un->un_retry_bp != NULL) {
14715 				SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
14716 				    "sd_start_cmds: exiting, retry pending!\n");
14717 				goto exit;
14718 			}
14719 			if (un->un_startstop_timeid != NULL) {
14720 				SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
14721 				    "sd_start_cmds: exiting, "
14722 				    "START_STOP pending!\n");
14723 				goto exit;
14724 			}
14725 			if (un->un_direct_priority_timeid != NULL) {
14726 				SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
14727 				    "sd_start_cmds: exiting, "
14728 				    "SD_PATH_DIRECT_PRIORITY cmd. pending!\n");
14729 				goto exit;
14730 			}
14731 
14732 			/* Dequeue the command */
14733 			un->un_waitq_headp = bp->av_forw;
14734 			if (un->un_waitq_headp == NULL) {
14735 				un->un_waitq_tailp = NULL;
14736 			}
14737 			bp->av_forw = NULL;
14738 			statp = kstat_waitq_to_runq;
14739 			SD_TRACE(SD_LOG_IO_CORE, un,
14740 			    "sd_start_cmds: processing waitq bp:0x%p\n", bp);
14741 
14742 		} else {
14743 			/* No work to do so bail out now */
14744 			SD_TRACE(SD_LOG_IO_CORE, un,
14745 			    "sd_start_cmds: no more work, exiting!\n");
14746 			goto exit;
14747 		}
14748 
14749 		/*
14750 		 * Reset the state to normal. This is the mechanism by which
14751 		 * the state transitions from either SD_STATE_RWAIT or
14752 		 * SD_STATE_OFFLINE to SD_STATE_NORMAL.
14753 		 * If state is SD_STATE_PM_CHANGING then this command is
14754 		 * part of the device power control and the state must
14755 		 * not be put back to normal. Doing so would would
14756 		 * allow new commands to proceed when they shouldn't,
14757 		 * the device may be going off.
14758 		 */
14759 		if ((un->un_state != SD_STATE_SUSPENDED) &&
14760 		    (un->un_state != SD_STATE_PM_CHANGING)) {
14761 			New_state(un, SD_STATE_NORMAL);
14762 		}
14763 
14764 		xp = SD_GET_XBUF(bp);
14765 		ASSERT(xp != NULL);
14766 
14767 #if defined(__i386) || defined(__amd64)	/* DMAFREE for x86 only */
14768 		/*
14769 		 * Allocate the scsi_pkt if we need one, or attach DMA
14770 		 * resources if we have a scsi_pkt that needs them. The
14771 		 * latter should only occur for commands that are being
14772 		 * retried.
14773 		 */
14774 		if ((xp->xb_pktp == NULL) ||
14775 		    ((xp->xb_pkt_flags & SD_XB_DMA_FREED) != 0)) {
14776 #else
14777 		if (xp->xb_pktp == NULL) {
14778 #endif
14779 			/*
14780 			 * There is no scsi_pkt allocated for this buf. Call
14781 			 * the initpkt function to allocate & init one.
14782 			 *
14783 			 * The scsi_init_pkt runout callback functionality is
14784 			 * implemented as follows:
14785 			 *
14786 			 * 1) The initpkt function always calls
14787 			 *    scsi_init_pkt(9F) with sdrunout specified as the
14788 			 *    callback routine.
14789 			 * 2) A successful packet allocation is initialized and
14790 			 *    the I/O is transported.
14791 			 * 3) The I/O associated with an allocation resource
14792 			 *    failure is left on its queue to be retried via
14793 			 *    runout or the next I/O.
14794 			 * 4) The I/O associated with a DMA error is removed
14795 			 *    from the queue and failed with EIO. Processing of
14796 			 *    the transport queues is also halted to be
14797 			 *    restarted via runout or the next I/O.
14798 			 * 5) The I/O associated with a CDB size or packet
14799 			 *    size error is removed from the queue and failed
14800 			 *    with EIO. Processing of the transport queues is
14801 			 *    continued.
14802 			 *
14803 			 * Note: there is no interface for canceling a runout
14804 			 * callback. To prevent the driver from detaching or
14805 			 * suspending while a runout is pending the driver
14806 			 * state is set to SD_STATE_RWAIT
14807 			 *
14808 			 * Note: using the scsi_init_pkt callback facility can
14809 			 * result in an I/O request persisting at the head of
14810 			 * the list which cannot be satisfied even after
14811 			 * multiple retries. In the future the driver may
14812 			 * implement some kind of maximum runout count before
14813 			 * failing an I/O.
14814 			 *
14815 			 * Note: the use of funcp below may seem superfluous,
14816 			 * but it helps warlock figure out the correct
14817 			 * initpkt function calls (see [s]sd.wlcmd).
14818 			 */
14819 			struct scsi_pkt	*pktp;
14820 			int (*funcp)(struct buf *bp, struct scsi_pkt **pktp);
14821 
14822 			ASSERT(bp != un->un_rqs_bp);
14823 
14824 			funcp = sd_initpkt_map[xp->xb_chain_iostart];
14825 			switch ((*funcp)(bp, &pktp)) {
14826 			case  SD_PKT_ALLOC_SUCCESS:
14827 				xp->xb_pktp = pktp;
14828 				SD_TRACE(SD_LOG_IO_CORE, un,
14829 				    "sd_start_cmd: SD_PKT_ALLOC_SUCCESS 0x%p\n",
14830 				    pktp);
14831 				goto got_pkt;
14832 
14833 			case SD_PKT_ALLOC_FAILURE:
14834 				/*
14835 				 * Temporary (hopefully) resource depletion.
14836 				 * Since retries and RQS commands always have a
14837 				 * scsi_pkt allocated, these cases should never
14838 				 * get here. So the only cases this needs to
14839 				 * handle is a bp from the waitq (which we put
14840 				 * back onto the waitq for sdrunout), or a bp
14841 				 * sent as an immed_bp (which we just fail).
14842 				 */
14843 				SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
14844 				    "sd_start_cmds: SD_PKT_ALLOC_FAILURE\n");
14845 
14846 #if defined(__i386) || defined(__amd64)	/* DMAFREE for x86 only */
14847 
14848 				if (bp == immed_bp) {
14849 					/*
14850 					 * If SD_XB_DMA_FREED is clear, then
14851 					 * this is a failure to allocate a
14852 					 * scsi_pkt, and we must fail the
14853 					 * command.
14854 					 */
14855 					if ((xp->xb_pkt_flags &
14856 					    SD_XB_DMA_FREED) == 0) {
14857 						break;
14858 					}
14859 
14860 					/*
14861 					 * If this immediate command is NOT our
14862 					 * un_retry_bp, then we must fail it.
14863 					 */
14864 					if (bp != un->un_retry_bp) {
14865 						break;
14866 					}
14867 
14868 					/*
14869 					 * We get here if this cmd is our
14870 					 * un_retry_bp that was DMAFREED, but
14871 					 * scsi_init_pkt() failed to reallocate
14872 					 * DMA resources when we attempted to
14873 					 * retry it. This can happen when an
14874 					 * mpxio failover is in progress, but
14875 					 * we don't want to just fail the
14876 					 * command in this case.
14877 					 *
14878 					 * Use timeout(9F) to restart it after
14879 					 * a 100ms delay.  We don't want to
14880 					 * let sdrunout() restart it, because
14881 					 * sdrunout() is just supposed to start
14882 					 * commands that are sitting on the
14883 					 * wait queue.  The un_retry_bp stays
14884 					 * set until the command completes, but
14885 					 * sdrunout can be called many times
14886 					 * before that happens.  Since sdrunout
14887 					 * cannot tell if the un_retry_bp is
14888 					 * already in the transport, it could
14889 					 * end up calling scsi_transport() for
14890 					 * the un_retry_bp multiple times.
14891 					 *
14892 					 * Also: don't schedule the callback
14893 					 * if some other callback is already
14894 					 * pending.
14895 					 */
14896 					if (un->un_retry_statp == NULL) {
14897 						/*
14898 						 * restore the kstat pointer to
14899 						 * keep kstat counts coherent
14900 						 * when we do retry the command.
14901 						 */
14902 						un->un_retry_statp =
14903 						    saved_statp;
14904 					}
14905 
14906 					if ((un->un_startstop_timeid == NULL) &&
14907 					    (un->un_retry_timeid == NULL) &&
14908 					    (un->un_direct_priority_timeid ==
14909 					    NULL)) {
14910 
14911 						un->un_retry_timeid =
14912 						    timeout(
14913 						    sd_start_retry_command,
14914 						    un, SD_RESTART_TIMEOUT);
14915 					}
14916 					goto exit;
14917 				}
14918 
14919 #else
14920 				if (bp == immed_bp) {
14921 					break;	/* Just fail the command */
14922 				}
14923 #endif
14924 
14925 				/* Add the buf back to the head of the waitq */
14926 				bp->av_forw = un->un_waitq_headp;
14927 				un->un_waitq_headp = bp;
14928 				if (un->un_waitq_tailp == NULL) {
14929 					un->un_waitq_tailp = bp;
14930 				}
14931 				goto exit;
14932 
14933 			case SD_PKT_ALLOC_FAILURE_NO_DMA:
14934 				/*
14935 				 * HBA DMA resource failure. Fail the command
14936 				 * and continue processing of the queues.
14937 				 */
14938 				SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
14939 				    "sd_start_cmds: "
14940 				    "SD_PKT_ALLOC_FAILURE_NO_DMA\n");
14941 				break;
14942 
14943 			case SD_PKT_ALLOC_FAILURE_PKT_TOO_SMALL:
14944 				/*
14945 				 * Note:x86: Partial DMA mapping not supported
14946 				 * for USCSI commands, and all the needed DMA
14947 				 * resources were not allocated.
14948 				 */
14949 				SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
14950 				    "sd_start_cmds: "
14951 				    "SD_PKT_ALLOC_FAILURE_PKT_TOO_SMALL\n");
14952 				break;
14953 
14954 			case SD_PKT_ALLOC_FAILURE_CDB_TOO_SMALL:
14955 				/*
14956 				 * Note:x86: Request cannot fit into CDB based
14957 				 * on lba and len.
14958 				 */
14959 				SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
14960 				    "sd_start_cmds: "
14961 				    "SD_PKT_ALLOC_FAILURE_CDB_TOO_SMALL\n");
14962 				break;
14963 
14964 			default:
14965 				/* Should NEVER get here! */
14966 				panic("scsi_initpkt error");
14967 				/*NOTREACHED*/
14968 			}
14969 
14970 			/*
14971 			 * Fatal error in allocating a scsi_pkt for this buf.
14972 			 * Update kstats & return the buf with an error code.
14973 			 * We must use sd_return_failed_command_no_restart() to
14974 			 * avoid a recursive call back into sd_start_cmds().
14975 			 * However this also means that we must keep processing
14976 			 * the waitq here in order to avoid stalling.
14977 			 */
14978 			if (statp == kstat_waitq_to_runq) {
14979 				SD_UPDATE_KSTATS(un, kstat_waitq_exit, bp);
14980 			}
14981 			sd_return_failed_command_no_restart(un, bp, EIO);
14982 			if (bp == immed_bp) {
14983 				/* immed_bp is gone by now, so clear this */
14984 				immed_bp = NULL;
14985 			}
14986 			continue;
14987 		}
14988 got_pkt:
14989 		if (bp == immed_bp) {
14990 			/* goto the head of the class.... */
14991 			xp->xb_pktp->pkt_flags |= FLAG_HEAD;
14992 		}
14993 
14994 		un->un_ncmds_in_transport++;
14995 		SD_UPDATE_KSTATS(un, statp, bp);
14996 
14997 		/*
14998 		 * Call scsi_transport() to send the command to the target.
14999 		 * According to SCSA architecture, we must drop the mutex here
15000 		 * before calling scsi_transport() in order to avoid deadlock.
15001 		 * Note that the scsi_pkt's completion routine can be executed
15002 		 * (from interrupt context) even before the call to
15003 		 * scsi_transport() returns.
15004 		 */
15005 		SD_TRACE(SD_LOG_IO_CORE, un,
15006 		    "sd_start_cmds: calling scsi_transport()\n");
15007 		DTRACE_PROBE1(scsi__transport__dispatch, struct buf *, bp);
15008 
15009 		mutex_exit(SD_MUTEX(un));
15010 		rval = scsi_transport(xp->xb_pktp);
15011 		mutex_enter(SD_MUTEX(un));
15012 
15013 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
15014 		    "sd_start_cmds: scsi_transport() returned %d\n", rval);
15015 
15016 		switch (rval) {
15017 		case TRAN_ACCEPT:
15018 			/* Clear this with every pkt accepted by the HBA */
15019 			un->un_tran_fatal_count = 0;
15020 			break;	/* Success; try the next cmd (if any) */
15021 
15022 		case TRAN_BUSY:
15023 			un->un_ncmds_in_transport--;
15024 			ASSERT(un->un_ncmds_in_transport >= 0);
15025 
15026 			/*
15027 			 * Don't retry request sense, the sense data
15028 			 * is lost when another request is sent.
15029 			 * Free up the rqs buf and retry
15030 			 * the original failed cmd.  Update kstat.
15031 			 */
15032 			if (bp == un->un_rqs_bp) {
15033 				SD_UPDATE_KSTATS(un, kstat_runq_exit, bp);
15034 				bp = sd_mark_rqs_idle(un, xp);
15035 				sd_retry_command(un, bp, SD_RETRIES_STANDARD,
15036 				    NULL, NULL, EIO, un->un_busy_timeout / 500,
15037 				    kstat_waitq_enter);
15038 				goto exit;
15039 			}
15040 
15041 #if defined(__i386) || defined(__amd64)	/* DMAFREE for x86 only */
15042 			/*
15043 			 * Free the DMA resources for the  scsi_pkt. This will
15044 			 * allow mpxio to select another path the next time
15045 			 * we call scsi_transport() with this scsi_pkt.
15046 			 * See sdintr() for the rationalization behind this.
15047 			 */
15048 			if ((un->un_f_is_fibre == TRUE) &&
15049 			    ((xp->xb_pkt_flags & SD_XB_USCSICMD) == 0) &&
15050 			    ((xp->xb_pktp->pkt_flags & FLAG_SENSING) == 0)) {
15051 				scsi_dmafree(xp->xb_pktp);
15052 				xp->xb_pkt_flags |= SD_XB_DMA_FREED;
15053 			}
15054 #endif
15055 
15056 			if (SD_IS_DIRECT_PRIORITY(SD_GET_XBUF(bp))) {
15057 				/*
15058 				 * Commands that are SD_PATH_DIRECT_PRIORITY
15059 				 * are for error recovery situations. These do
15060 				 * not use the normal command waitq, so if they
15061 				 * get a TRAN_BUSY we cannot put them back onto
15062 				 * the waitq for later retry. One possible
15063 				 * problem is that there could already be some
15064 				 * other command on un_retry_bp that is waiting
15065 				 * for this one to complete, so we would be
15066 				 * deadlocked if we put this command back onto
15067 				 * the waitq for later retry (since un_retry_bp
15068 				 * must complete before the driver gets back to
15069 				 * commands on the waitq).
15070 				 *
15071 				 * To avoid deadlock we must schedule a callback
15072 				 * that will restart this command after a set
15073 				 * interval.  This should keep retrying for as
15074 				 * long as the underlying transport keeps
15075 				 * returning TRAN_BUSY (just like for other
15076 				 * commands).  Use the same timeout interval as
15077 				 * for the ordinary TRAN_BUSY retry.
15078 				 */
15079 				SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
15080 				    "sd_start_cmds: scsi_transport() returned "
15081 				    "TRAN_BUSY for DIRECT_PRIORITY cmd!\n");
15082 
15083 				SD_UPDATE_KSTATS(un, kstat_runq_exit, bp);
15084 				un->un_direct_priority_timeid =
15085 				    timeout(sd_start_direct_priority_command,
15086 				    bp, un->un_busy_timeout / 500);
15087 
15088 				goto exit;
15089 			}
15090 
15091 			/*
15092 			 * For TRAN_BUSY, we want to reduce the throttle value,
15093 			 * unless we are retrying a command.
15094 			 */
15095 			if (bp != un->un_retry_bp) {
15096 				sd_reduce_throttle(un, SD_THROTTLE_TRAN_BUSY);
15097 			}
15098 
15099 			/*
15100 			 * Set up the bp to be tried again 10 ms later.
15101 			 * Note:x86: Is there a timeout value in the sd_lun
15102 			 * for this condition?
15103 			 */
15104 			sd_set_retry_bp(un, bp, un->un_busy_timeout / 500,
15105 			    kstat_runq_back_to_waitq);
15106 			goto exit;
15107 
15108 		case TRAN_FATAL_ERROR:
15109 			un->un_tran_fatal_count++;
15110 			/* FALLTHRU */
15111 
15112 		case TRAN_BADPKT:
15113 		default:
15114 			un->un_ncmds_in_transport--;
15115 			ASSERT(un->un_ncmds_in_transport >= 0);
15116 
15117 			/*
15118 			 * If this is our REQUEST SENSE command with a
15119 			 * transport error, we must get back the pointers
15120 			 * to the original buf, and mark the REQUEST
15121 			 * SENSE command as "available".
15122 			 */
15123 			if (bp == un->un_rqs_bp) {
15124 				bp = sd_mark_rqs_idle(un, xp);
15125 				xp = SD_GET_XBUF(bp);
15126 			} else {
15127 				/*
15128 				 * Legacy behavior: do not update transport
15129 				 * error count for request sense commands.
15130 				 */
15131 				SD_UPDATE_ERRSTATS(un, sd_transerrs);
15132 			}
15133 
15134 			SD_UPDATE_KSTATS(un, kstat_runq_exit, bp);
15135 			sd_print_transport_rejected_message(un, xp, rval);
15136 
15137 			/*
15138 			 * This command will be terminated by SD driver due
15139 			 * to a fatal transport error. We should post
15140 			 * ereport.io.scsi.cmd.disk.tran with driver-assessment
15141 			 * of "fail" for any command to indicate this
15142 			 * situation.
15143 			 */
15144 			if (xp->xb_ena > 0) {
15145 				ASSERT(un->un_fm_private != NULL);
15146 				sfip = un->un_fm_private;
15147 				sfip->fm_ssc.ssc_flags |= SSC_FLAGS_TRAN_ABORT;
15148 				sd_ssc_extract_info(&sfip->fm_ssc, un,
15149 				    xp->xb_pktp, bp, xp);
15150 				sd_ssc_post(&sfip->fm_ssc, SD_FM_DRV_FATAL);
15151 			}
15152 
15153 			/*
15154 			 * We must use sd_return_failed_command_no_restart() to
15155 			 * avoid a recursive call back into sd_start_cmds().
15156 			 * However this also means that we must keep processing
15157 			 * the waitq here in order to avoid stalling.
15158 			 */
15159 			sd_return_failed_command_no_restart(un, bp, EIO);
15160 
15161 			/*
15162 			 * Notify any threads waiting in sd_ddi_suspend() that
15163 			 * a command completion has occurred.
15164 			 */
15165 			if (un->un_state == SD_STATE_SUSPENDED) {
15166 				cv_broadcast(&un->un_disk_busy_cv);
15167 			}
15168 
15169 			if (bp == immed_bp) {
15170 				/* immed_bp is gone by now, so clear this */
15171 				immed_bp = NULL;
15172 			}
15173 			break;
15174 		}
15175 
15176 	} while (immed_bp == NULL);
15177 
15178 exit:
15179 	ASSERT(mutex_owned(SD_MUTEX(un)));
15180 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un, "sd_start_cmds: exit\n");
15181 }
15182 
15183 
15184 /*
15185  *    Function: sd_return_command
15186  *
15187  * Description: Returns a command to its originator (with or without an
15188  *		error).  Also starts commands waiting to be transported
15189  *		to the target.
15190  *
15191  *     Context: May be called from interrupt, kernel, or timeout context
15192  */
15193 
15194 static void
15195 sd_return_command(struct sd_lun *un, struct buf *bp)
15196 {
15197 	struct sd_xbuf *xp;
15198 	struct scsi_pkt *pktp;
15199 	struct sd_fm_internal *sfip;
15200 
15201 	ASSERT(bp != NULL);
15202 	ASSERT(un != NULL);
15203 	ASSERT(mutex_owned(SD_MUTEX(un)));
15204 	ASSERT(bp != un->un_rqs_bp);
15205 	xp = SD_GET_XBUF(bp);
15206 	ASSERT(xp != NULL);
15207 
15208 	pktp = SD_GET_PKTP(bp);
15209 	sfip = (struct sd_fm_internal *)un->un_fm_private;
15210 	ASSERT(sfip != NULL);
15211 
15212 	SD_TRACE(SD_LOG_IO_CORE, un, "sd_return_command: entry\n");
15213 
15214 	/*
15215 	 * Note: check for the "sdrestart failed" case.
15216 	 */
15217 	if ((un->un_partial_dma_supported == 1) &&
15218 	    ((xp->xb_pkt_flags & SD_XB_USCSICMD) != SD_XB_USCSICMD) &&
15219 	    (geterror(bp) == 0) && (xp->xb_dma_resid != 0) &&
15220 	    (xp->xb_pktp->pkt_resid == 0)) {
15221 
15222 		if (sd_setup_next_xfer(un, bp, pktp, xp) != 0) {
15223 			/*
15224 			 * Successfully set up next portion of cmd
15225 			 * transfer, try sending it
15226 			 */
15227 			sd_retry_command(un, bp, SD_RETRIES_NOCHECK,
15228 			    NULL, NULL, 0, (clock_t)0, NULL);
15229 			sd_start_cmds(un, NULL);
15230 			return;	/* Note:x86: need a return here? */
15231 		}
15232 	}
15233 
15234 	/*
15235 	 * If this is the failfast bp, clear it from un_failfast_bp. This
15236 	 * can happen if upon being re-tried the failfast bp either
15237 	 * succeeded or encountered another error (possibly even a different
15238 	 * error than the one that precipitated the failfast state, but in
15239 	 * that case it would have had to exhaust retries as well). Regardless,
15240 	 * this should not occur whenever the instance is in the active
15241 	 * failfast state.
15242 	 */
15243 	if (bp == un->un_failfast_bp) {
15244 		ASSERT(un->un_failfast_state == SD_FAILFAST_INACTIVE);
15245 		un->un_failfast_bp = NULL;
15246 	}
15247 
15248 	/*
15249 	 * Clear the failfast state upon successful completion of ANY cmd.
15250 	 */
15251 	if (bp->b_error == 0) {
15252 		un->un_failfast_state = SD_FAILFAST_INACTIVE;
15253 		/*
15254 		 * If this is a successful command, but used to be retried,
15255 		 * we will take it as a recovered command and post an
15256 		 * ereport with driver-assessment of "recovered".
15257 		 */
15258 		if (xp->xb_ena > 0) {
15259 			sd_ssc_extract_info(&sfip->fm_ssc, un, pktp, bp, xp);
15260 			sd_ssc_post(&sfip->fm_ssc, SD_FM_DRV_RECOVERY);
15261 		}
15262 	} else {
15263 		/*
15264 		 * If this is a failed non-USCSI command we will post an
15265 		 * ereport with driver-assessment set accordingly("fail" or
15266 		 * "fatal").
15267 		 */
15268 		if (!(xp->xb_pkt_flags & SD_XB_USCSICMD)) {
15269 			sd_ssc_extract_info(&sfip->fm_ssc, un, pktp, bp, xp);
15270 			sd_ssc_post(&sfip->fm_ssc, SD_FM_DRV_FATAL);
15271 		}
15272 	}
15273 
15274 	/*
15275 	 * This is used if the command was retried one or more times. Show that
15276 	 * we are done with it, and allow processing of the waitq to resume.
15277 	 */
15278 	if (bp == un->un_retry_bp) {
15279 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
15280 		    "sd_return_command: un:0x%p: "
15281 		    "RETURNING retry_bp:0x%p\n", un, un->un_retry_bp);
15282 		un->un_retry_bp = NULL;
15283 		un->un_retry_statp = NULL;
15284 	}
15285 
15286 	SD_UPDATE_RDWR_STATS(un, bp);
15287 	SD_UPDATE_PARTITION_STATS(un, bp);
15288 
15289 	switch (un->un_state) {
15290 	case SD_STATE_SUSPENDED:
15291 		/*
15292 		 * Notify any threads waiting in sd_ddi_suspend() that
15293 		 * a command completion has occurred.
15294 		 */
15295 		cv_broadcast(&un->un_disk_busy_cv);
15296 		break;
15297 	default:
15298 		sd_start_cmds(un, NULL);
15299 		break;
15300 	}
15301 
15302 	/* Return this command up the iodone chain to its originator. */
15303 	mutex_exit(SD_MUTEX(un));
15304 
15305 	(*(sd_destroypkt_map[xp->xb_chain_iodone]))(bp);
15306 	xp->xb_pktp = NULL;
15307 
15308 	SD_BEGIN_IODONE(xp->xb_chain_iodone, un, bp);
15309 
15310 	ASSERT(!mutex_owned(SD_MUTEX(un)));
15311 	mutex_enter(SD_MUTEX(un));
15312 
15313 	SD_TRACE(SD_LOG_IO_CORE, un, "sd_return_command: exit\n");
15314 }
15315 
15316 
15317 /*
15318  *    Function: sd_return_failed_command
15319  *
15320  * Description: Command completion when an error occurred.
15321  *
15322  *     Context: May be called from interrupt context
15323  */
15324 
15325 static void
15326 sd_return_failed_command(struct sd_lun *un, struct buf *bp, int errcode)
15327 {
15328 	ASSERT(bp != NULL);
15329 	ASSERT(un != NULL);
15330 	ASSERT(mutex_owned(SD_MUTEX(un)));
15331 
15332 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
15333 	    "sd_return_failed_command: entry\n");
15334 
15335 	/*
15336 	 * b_resid could already be nonzero due to a partial data
15337 	 * transfer, so do not change it here.
15338 	 */
15339 	SD_BIOERROR(bp, errcode);
15340 
15341 	sd_return_command(un, bp);
15342 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
15343 	    "sd_return_failed_command: exit\n");
15344 }
15345 
15346 
15347 /*
15348  *    Function: sd_return_failed_command_no_restart
15349  *
15350  * Description: Same as sd_return_failed_command, but ensures that no
15351  *		call back into sd_start_cmds will be issued.
15352  *
15353  *     Context: May be called from interrupt context
15354  */
15355 
15356 static void
15357 sd_return_failed_command_no_restart(struct sd_lun *un, struct buf *bp,
15358 	int errcode)
15359 {
15360 	struct sd_xbuf *xp;
15361 
15362 	ASSERT(bp != NULL);
15363 	ASSERT(un != NULL);
15364 	ASSERT(mutex_owned(SD_MUTEX(un)));
15365 	xp = SD_GET_XBUF(bp);
15366 	ASSERT(xp != NULL);
15367 	ASSERT(errcode != 0);
15368 
15369 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
15370 	    "sd_return_failed_command_no_restart: entry\n");
15371 
15372 	/*
15373 	 * b_resid could already be nonzero due to a partial data
15374 	 * transfer, so do not change it here.
15375 	 */
15376 	SD_BIOERROR(bp, errcode);
15377 
15378 	/*
15379 	 * If this is the failfast bp, clear it. This can happen if the
15380 	 * failfast bp encounterd a fatal error when we attempted to
15381 	 * re-try it (such as a scsi_transport(9F) failure).  However
15382 	 * we should NOT be in an active failfast state if the failfast
15383 	 * bp is not NULL.
15384 	 */
15385 	if (bp == un->un_failfast_bp) {
15386 		ASSERT(un->un_failfast_state == SD_FAILFAST_INACTIVE);
15387 		un->un_failfast_bp = NULL;
15388 	}
15389 
15390 	if (bp == un->un_retry_bp) {
15391 		/*
15392 		 * This command was retried one or more times. Show that we are
15393 		 * done with it, and allow processing of the waitq to resume.
15394 		 */
15395 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
15396 		    "sd_return_failed_command_no_restart: "
15397 		    " un:0x%p: RETURNING retry_bp:0x%p\n", un, un->un_retry_bp);
15398 		un->un_retry_bp = NULL;
15399 		un->un_retry_statp = NULL;
15400 	}
15401 
15402 	SD_UPDATE_RDWR_STATS(un, bp);
15403 	SD_UPDATE_PARTITION_STATS(un, bp);
15404 
15405 	mutex_exit(SD_MUTEX(un));
15406 
15407 	if (xp->xb_pktp != NULL) {
15408 		(*(sd_destroypkt_map[xp->xb_chain_iodone]))(bp);
15409 		xp->xb_pktp = NULL;
15410 	}
15411 
15412 	SD_BEGIN_IODONE(xp->xb_chain_iodone, un, bp);
15413 
15414 	mutex_enter(SD_MUTEX(un));
15415 
15416 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
15417 	    "sd_return_failed_command_no_restart: exit\n");
15418 }
15419 
15420 
15421 /*
15422  *    Function: sd_retry_command
15423  *
15424  * Description: queue up a command for retry, or (optionally) fail it
15425  *		if retry counts are exhausted.
15426  *
15427  *   Arguments: un - Pointer to the sd_lun struct for the target.
15428  *
15429  *		bp - Pointer to the buf for the command to be retried.
15430  *
15431  *		retry_check_flag - Flag to see which (if any) of the retry
15432  *		   counts should be decremented/checked. If the indicated
15433  *		   retry count is exhausted, then the command will not be
15434  *		   retried; it will be failed instead. This should use a
15435  *		   value equal to one of the following:
15436  *
15437  *			SD_RETRIES_NOCHECK
15438  *			SD_RESD_RETRIES_STANDARD
15439  *			SD_RETRIES_VICTIM
15440  *
15441  *		   Optionally may be bitwise-OR'ed with SD_RETRIES_ISOLATE
15442  *		   if the check should be made to see of FLAG_ISOLATE is set
15443  *		   in the pkt. If FLAG_ISOLATE is set, then the command is
15444  *		   not retried, it is simply failed.
15445  *
15446  *		user_funcp - Ptr to function to call before dispatching the
15447  *		   command. May be NULL if no action needs to be performed.
15448  *		   (Primarily intended for printing messages.)
15449  *
15450  *		user_arg - Optional argument to be passed along to
15451  *		   the user_funcp call.
15452  *
15453  *		failure_code - errno return code to set in the bp if the
15454  *		   command is going to be failed.
15455  *
15456  *		retry_delay - Retry delay interval in (clock_t) units. May
15457  *		   be zero which indicates that the retry should be retried
15458  *		   immediately (ie, without an intervening delay).
15459  *
15460  *		statp - Ptr to kstat function to be updated if the command
15461  *		   is queued for a delayed retry. May be NULL if no kstat
15462  *		   update is desired.
15463  *
15464  *     Context: May be called from interrupt context.
15465  */
15466 
15467 static void
15468 sd_retry_command(struct sd_lun *un, struct buf *bp, int retry_check_flag,
15469 	void (*user_funcp)(struct sd_lun *un, struct buf *bp, void *argp, int
15470 	code), void *user_arg, int failure_code,  clock_t retry_delay,
15471 	void (*statp)(kstat_io_t *))
15472 {
15473 	struct sd_xbuf	*xp;
15474 	struct scsi_pkt	*pktp;
15475 	struct sd_fm_internal *sfip;
15476 
15477 	ASSERT(un != NULL);
15478 	ASSERT(mutex_owned(SD_MUTEX(un)));
15479 	ASSERT(bp != NULL);
15480 	xp = SD_GET_XBUF(bp);
15481 	ASSERT(xp != NULL);
15482 	pktp = SD_GET_PKTP(bp);
15483 	ASSERT(pktp != NULL);
15484 
15485 	sfip = (struct sd_fm_internal *)un->un_fm_private;
15486 	ASSERT(sfip != NULL);
15487 
15488 	SD_TRACE(SD_LOG_IO | SD_LOG_ERROR, un,
15489 	    "sd_retry_command: entry: bp:0x%p xp:0x%p\n", bp, xp);
15490 
15491 	/*
15492 	 * If we are syncing or dumping, fail the command to avoid
15493 	 * recursively calling back into scsi_transport().
15494 	 */
15495 	if (ddi_in_panic()) {
15496 		goto fail_command_no_log;
15497 	}
15498 
15499 	/*
15500 	 * We should never be be retrying a command with FLAG_DIAGNOSE set, so
15501 	 * log an error and fail the command.
15502 	 */
15503 	if ((pktp->pkt_flags & FLAG_DIAGNOSE) != 0) {
15504 		scsi_log(SD_DEVINFO(un), sd_label, CE_NOTE,
15505 		    "ERROR, retrying FLAG_DIAGNOSE command.\n");
15506 		sd_dump_memory(un, SD_LOG_IO, "CDB",
15507 		    (uchar_t *)pktp->pkt_cdbp, CDB_SIZE, SD_LOG_HEX);
15508 		sd_dump_memory(un, SD_LOG_IO, "Sense Data",
15509 		    (uchar_t *)xp->xb_sense_data, SENSE_LENGTH, SD_LOG_HEX);
15510 		goto fail_command;
15511 	}
15512 
15513 	/*
15514 	 * If we are suspended, then put the command onto head of the
15515 	 * wait queue since we don't want to start more commands, and
15516 	 * clear the un_retry_bp. Next time when we are resumed, will
15517 	 * handle the command in the wait queue.
15518 	 */
15519 	switch (un->un_state) {
15520 	case SD_STATE_SUSPENDED:
15521 	case SD_STATE_DUMPING:
15522 		bp->av_forw = un->un_waitq_headp;
15523 		un->un_waitq_headp = bp;
15524 		if (un->un_waitq_tailp == NULL) {
15525 			un->un_waitq_tailp = bp;
15526 		}
15527 		if (bp == un->un_retry_bp) {
15528 			un->un_retry_bp = NULL;
15529 			un->un_retry_statp = NULL;
15530 		}
15531 		SD_UPDATE_KSTATS(un, kstat_waitq_enter, bp);
15532 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un, "sd_retry_command: "
15533 		    "exiting; cmd bp:0x%p requeued for SUSPEND/DUMP\n", bp);
15534 		return;
15535 	default:
15536 		break;
15537 	}
15538 
15539 	/*
15540 	 * If the caller wants us to check FLAG_ISOLATE, then see if that
15541 	 * is set; if it is then we do not want to retry the command.
15542 	 * Normally, FLAG_ISOLATE is only used with USCSI cmds.
15543 	 */
15544 	if ((retry_check_flag & SD_RETRIES_ISOLATE) != 0) {
15545 		if ((pktp->pkt_flags & FLAG_ISOLATE) != 0) {
15546 			goto fail_command;
15547 		}
15548 	}
15549 
15550 
15551 	/*
15552 	 * If SD_RETRIES_FAILFAST is set, it indicates that either a
15553 	 * command timeout or a selection timeout has occurred. This means
15554 	 * that we were unable to establish an kind of communication with
15555 	 * the target, and subsequent retries and/or commands are likely
15556 	 * to encounter similar results and take a long time to complete.
15557 	 *
15558 	 * If this is a failfast error condition, we need to update the
15559 	 * failfast state, even if this bp does not have B_FAILFAST set.
15560 	 */
15561 	if (retry_check_flag & SD_RETRIES_FAILFAST) {
15562 		if (un->un_failfast_state == SD_FAILFAST_ACTIVE) {
15563 			ASSERT(un->un_failfast_bp == NULL);
15564 			/*
15565 			 * If we are already in the active failfast state, and
15566 			 * another failfast error condition has been detected,
15567 			 * then fail this command if it has B_FAILFAST set.
15568 			 * If B_FAILFAST is clear, then maintain the legacy
15569 			 * behavior of retrying heroically, even tho this will
15570 			 * take a lot more time to fail the command.
15571 			 */
15572 			if (bp->b_flags & B_FAILFAST) {
15573 				goto fail_command;
15574 			}
15575 		} else {
15576 			/*
15577 			 * We're not in the active failfast state, but we
15578 			 * have a failfast error condition, so we must begin
15579 			 * transition to the next state. We do this regardless
15580 			 * of whether or not this bp has B_FAILFAST set.
15581 			 */
15582 			if (un->un_failfast_bp == NULL) {
15583 				/*
15584 				 * This is the first bp to meet a failfast
15585 				 * condition so save it on un_failfast_bp &
15586 				 * do normal retry processing. Do not enter
15587 				 * active failfast state yet. This marks
15588 				 * entry into the "failfast pending" state.
15589 				 */
15590 				un->un_failfast_bp = bp;
15591 
15592 			} else if (un->un_failfast_bp == bp) {
15593 				/*
15594 				 * This is the second time *this* bp has
15595 				 * encountered a failfast error condition,
15596 				 * so enter active failfast state & flush
15597 				 * queues as appropriate.
15598 				 */
15599 				un->un_failfast_state = SD_FAILFAST_ACTIVE;
15600 				un->un_failfast_bp = NULL;
15601 				sd_failfast_flushq(un);
15602 
15603 				/*
15604 				 * Fail this bp now if B_FAILFAST set;
15605 				 * otherwise continue with retries. (It would
15606 				 * be pretty ironic if this bp succeeded on a
15607 				 * subsequent retry after we just flushed all
15608 				 * the queues).
15609 				 */
15610 				if (bp->b_flags & B_FAILFAST) {
15611 					goto fail_command;
15612 				}
15613 
15614 #if !defined(lint) && !defined(__lint)
15615 			} else {
15616 				/*
15617 				 * If neither of the preceeding conditionals
15618 				 * was true, it means that there is some
15619 				 * *other* bp that has met an inital failfast
15620 				 * condition and is currently either being
15621 				 * retried or is waiting to be retried. In
15622 				 * that case we should perform normal retry
15623 				 * processing on *this* bp, since there is a
15624 				 * chance that the current failfast condition
15625 				 * is transient and recoverable. If that does
15626 				 * not turn out to be the case, then retries
15627 				 * will be cleared when the wait queue is
15628 				 * flushed anyway.
15629 				 */
15630 #endif
15631 			}
15632 		}
15633 	} else {
15634 		/*
15635 		 * SD_RETRIES_FAILFAST is clear, which indicates that we
15636 		 * likely were able to at least establish some level of
15637 		 * communication with the target and subsequent commands
15638 		 * and/or retries are likely to get through to the target,
15639 		 * In this case we want to be aggressive about clearing
15640 		 * the failfast state. Note that this does not affect
15641 		 * the "failfast pending" condition.
15642 		 */
15643 		un->un_failfast_state = SD_FAILFAST_INACTIVE;
15644 	}
15645 
15646 
15647 	/*
15648 	 * Check the specified retry count to see if we can still do
15649 	 * any retries with this pkt before we should fail it.
15650 	 */
15651 	switch (retry_check_flag & SD_RETRIES_MASK) {
15652 	case SD_RETRIES_VICTIM:
15653 		/*
15654 		 * Check the victim retry count. If exhausted, then fall
15655 		 * thru & check against the standard retry count.
15656 		 */
15657 		if (xp->xb_victim_retry_count < un->un_victim_retry_count) {
15658 			/* Increment count & proceed with the retry */
15659 			xp->xb_victim_retry_count++;
15660 			break;
15661 		}
15662 		/* Victim retries exhausted, fall back to std. retries... */
15663 		/* FALLTHRU */
15664 
15665 	case SD_RETRIES_STANDARD:
15666 		if (xp->xb_retry_count >= un->un_retry_count) {
15667 			/* Retries exhausted, fail the command */
15668 			SD_TRACE(SD_LOG_IO_CORE, un,
15669 			    "sd_retry_command: retries exhausted!\n");
15670 			/*
15671 			 * update b_resid for failed SCMD_READ & SCMD_WRITE
15672 			 * commands with nonzero pkt_resid.
15673 			 */
15674 			if ((pktp->pkt_reason == CMD_CMPLT) &&
15675 			    (SD_GET_PKT_STATUS(pktp) == STATUS_GOOD) &&
15676 			    (pktp->pkt_resid != 0)) {
15677 				uchar_t op = SD_GET_PKT_OPCODE(pktp) & 0x1F;
15678 				if ((op == SCMD_READ) || (op == SCMD_WRITE)) {
15679 					SD_UPDATE_B_RESID(bp, pktp);
15680 				}
15681 			}
15682 			goto fail_command;
15683 		}
15684 		xp->xb_retry_count++;
15685 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
15686 		    "sd_retry_command: retry count:%d\n", xp->xb_retry_count);
15687 		break;
15688 
15689 	case SD_RETRIES_UA:
15690 		if (xp->xb_ua_retry_count >= sd_ua_retry_count) {
15691 			/* Retries exhausted, fail the command */
15692 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
15693 			    "Unit Attention retries exhausted. "
15694 			    "Check the target.\n");
15695 			goto fail_command;
15696 		}
15697 		xp->xb_ua_retry_count++;
15698 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
15699 		    "sd_retry_command: retry count:%d\n",
15700 		    xp->xb_ua_retry_count);
15701 		break;
15702 
15703 	case SD_RETRIES_BUSY:
15704 		if (xp->xb_retry_count >= un->un_busy_retry_count) {
15705 			/* Retries exhausted, fail the command */
15706 			SD_TRACE(SD_LOG_IO_CORE, un,
15707 			    "sd_retry_command: retries exhausted!\n");
15708 			goto fail_command;
15709 		}
15710 		xp->xb_retry_count++;
15711 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
15712 		    "sd_retry_command: retry count:%d\n", xp->xb_retry_count);
15713 		break;
15714 
15715 	case SD_RETRIES_NOCHECK:
15716 	default:
15717 		/* No retry count to check. Just proceed with the retry */
15718 		break;
15719 	}
15720 
15721 	xp->xb_pktp->pkt_flags |= FLAG_HEAD;
15722 
15723 	/*
15724 	 * If this is a non-USCSI command being retried
15725 	 * during execution last time, we should post an ereport with
15726 	 * driver-assessment of the value "retry".
15727 	 * For partial DMA, request sense and STATUS_QFULL, there are no
15728 	 * hardware errors, we bypass ereport posting.
15729 	 */
15730 	if (failure_code != 0) {
15731 		if (!(xp->xb_pkt_flags & SD_XB_USCSICMD)) {
15732 			sd_ssc_extract_info(&sfip->fm_ssc, un, pktp, bp, xp);
15733 			sd_ssc_post(&sfip->fm_ssc, SD_FM_DRV_RETRY);
15734 		}
15735 	}
15736 
15737 	/*
15738 	 * If we were given a zero timeout, we must attempt to retry the
15739 	 * command immediately (ie, without a delay).
15740 	 */
15741 	if (retry_delay == 0) {
15742 		/*
15743 		 * Check some limiting conditions to see if we can actually
15744 		 * do the immediate retry.  If we cannot, then we must
15745 		 * fall back to queueing up a delayed retry.
15746 		 */
15747 		if (un->un_ncmds_in_transport >= un->un_throttle) {
15748 			/*
15749 			 * We are at the throttle limit for the target,
15750 			 * fall back to delayed retry.
15751 			 */
15752 			retry_delay = un->un_busy_timeout;
15753 			statp = kstat_waitq_enter;
15754 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
15755 			    "sd_retry_command: immed. retry hit "
15756 			    "throttle!\n");
15757 		} else {
15758 			/*
15759 			 * We're clear to proceed with the immediate retry.
15760 			 * First call the user-provided function (if any)
15761 			 */
15762 			if (user_funcp != NULL) {
15763 				(*user_funcp)(un, bp, user_arg,
15764 				    SD_IMMEDIATE_RETRY_ISSUED);
15765 #ifdef __lock_lint
15766 				sd_print_incomplete_msg(un, bp, user_arg,
15767 				    SD_IMMEDIATE_RETRY_ISSUED);
15768 				sd_print_cmd_incomplete_msg(un, bp, user_arg,
15769 				    SD_IMMEDIATE_RETRY_ISSUED);
15770 				sd_print_sense_failed_msg(un, bp, user_arg,
15771 				    SD_IMMEDIATE_RETRY_ISSUED);
15772 #endif
15773 			}
15774 
15775 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
15776 			    "sd_retry_command: issuing immediate retry\n");
15777 
15778 			/*
15779 			 * Call sd_start_cmds() to transport the command to
15780 			 * the target.
15781 			 */
15782 			sd_start_cmds(un, bp);
15783 
15784 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
15785 			    "sd_retry_command exit\n");
15786 			return;
15787 		}
15788 	}
15789 
15790 	/*
15791 	 * Set up to retry the command after a delay.
15792 	 * First call the user-provided function (if any)
15793 	 */
15794 	if (user_funcp != NULL) {
15795 		(*user_funcp)(un, bp, user_arg, SD_DELAYED_RETRY_ISSUED);
15796 	}
15797 
15798 	sd_set_retry_bp(un, bp, retry_delay, statp);
15799 
15800 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un, "sd_retry_command: exit\n");
15801 	return;
15802 
15803 fail_command:
15804 
15805 	if (user_funcp != NULL) {
15806 		(*user_funcp)(un, bp, user_arg, SD_NO_RETRY_ISSUED);
15807 	}
15808 
15809 fail_command_no_log:
15810 
15811 	SD_INFO(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
15812 	    "sd_retry_command: returning failed command\n");
15813 
15814 	sd_return_failed_command(un, bp, failure_code);
15815 
15816 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un, "sd_retry_command: exit\n");
15817 }
15818 
15819 
15820 /*
15821  *    Function: sd_set_retry_bp
15822  *
15823  * Description: Set up the given bp for retry.
15824  *
15825  *   Arguments: un - ptr to associated softstate
15826  *		bp - ptr to buf(9S) for the command
15827  *		retry_delay - time interval before issuing retry (may be 0)
15828  *		statp - optional pointer to kstat function
15829  *
15830  *     Context: May be called under interrupt context
15831  */
15832 
15833 static void
15834 sd_set_retry_bp(struct sd_lun *un, struct buf *bp, clock_t retry_delay,
15835 	void (*statp)(kstat_io_t *))
15836 {
15837 	ASSERT(un != NULL);
15838 	ASSERT(mutex_owned(SD_MUTEX(un)));
15839 	ASSERT(bp != NULL);
15840 
15841 	SD_TRACE(SD_LOG_IO | SD_LOG_ERROR, un,
15842 	    "sd_set_retry_bp: entry: un:0x%p bp:0x%p\n", un, bp);
15843 
15844 	/*
15845 	 * Indicate that the command is being retried. This will not allow any
15846 	 * other commands on the wait queue to be transported to the target
15847 	 * until this command has been completed (success or failure). The
15848 	 * "retry command" is not transported to the target until the given
15849 	 * time delay expires, unless the user specified a 0 retry_delay.
15850 	 *
15851 	 * Note: the timeout(9F) callback routine is what actually calls
15852 	 * sd_start_cmds() to transport the command, with the exception of a
15853 	 * zero retry_delay. The only current implementor of a zero retry delay
15854 	 * is the case where a START_STOP_UNIT is sent to spin-up a device.
15855 	 */
15856 	if (un->un_retry_bp == NULL) {
15857 		ASSERT(un->un_retry_statp == NULL);
15858 		un->un_retry_bp = bp;
15859 
15860 		/*
15861 		 * If the user has not specified a delay the command should
15862 		 * be queued and no timeout should be scheduled.
15863 		 */
15864 		if (retry_delay == 0) {
15865 			/*
15866 			 * Save the kstat pointer that will be used in the
15867 			 * call to SD_UPDATE_KSTATS() below, so that
15868 			 * sd_start_cmds() can correctly decrement the waitq
15869 			 * count when it is time to transport this command.
15870 			 */
15871 			un->un_retry_statp = statp;
15872 			goto done;
15873 		}
15874 	}
15875 
15876 	if (un->un_retry_bp == bp) {
15877 		/*
15878 		 * Save the kstat pointer that will be used in the call to
15879 		 * SD_UPDATE_KSTATS() below, so that sd_start_cmds() can
15880 		 * correctly decrement the waitq count when it is time to
15881 		 * transport this command.
15882 		 */
15883 		un->un_retry_statp = statp;
15884 
15885 		/*
15886 		 * Schedule a timeout if:
15887 		 *   1) The user has specified a delay.
15888 		 *   2) There is not a START_STOP_UNIT callback pending.
15889 		 *
15890 		 * If no delay has been specified, then it is up to the caller
15891 		 * to ensure that IO processing continues without stalling.
15892 		 * Effectively, this means that the caller will issue the
15893 		 * required call to sd_start_cmds(). The START_STOP_UNIT
15894 		 * callback does this after the START STOP UNIT command has
15895 		 * completed. In either of these cases we should not schedule
15896 		 * a timeout callback here.  Also don't schedule the timeout if
15897 		 * an SD_PATH_DIRECT_PRIORITY command is waiting to restart.
15898 		 */
15899 		if ((retry_delay != 0) && (un->un_startstop_timeid == NULL) &&
15900 		    (un->un_direct_priority_timeid == NULL)) {
15901 			un->un_retry_timeid =
15902 			    timeout(sd_start_retry_command, un, retry_delay);
15903 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
15904 			    "sd_set_retry_bp: setting timeout: un: 0x%p"
15905 			    " bp:0x%p un_retry_timeid:0x%p\n",
15906 			    un, bp, un->un_retry_timeid);
15907 		}
15908 	} else {
15909 		/*
15910 		 * We only get in here if there is already another command
15911 		 * waiting to be retried.  In this case, we just put the
15912 		 * given command onto the wait queue, so it can be transported
15913 		 * after the current retry command has completed.
15914 		 *
15915 		 * Also we have to make sure that if the command at the head
15916 		 * of the wait queue is the un_failfast_bp, that we do not
15917 		 * put ahead of it any other commands that are to be retried.
15918 		 */
15919 		if ((un->un_failfast_bp != NULL) &&
15920 		    (un->un_failfast_bp == un->un_waitq_headp)) {
15921 			/*
15922 			 * Enqueue this command AFTER the first command on
15923 			 * the wait queue (which is also un_failfast_bp).
15924 			 */
15925 			bp->av_forw = un->un_waitq_headp->av_forw;
15926 			un->un_waitq_headp->av_forw = bp;
15927 			if (un->un_waitq_headp == un->un_waitq_tailp) {
15928 				un->un_waitq_tailp = bp;
15929 			}
15930 		} else {
15931 			/* Enqueue this command at the head of the waitq. */
15932 			bp->av_forw = un->un_waitq_headp;
15933 			un->un_waitq_headp = bp;
15934 			if (un->un_waitq_tailp == NULL) {
15935 				un->un_waitq_tailp = bp;
15936 			}
15937 		}
15938 
15939 		if (statp == NULL) {
15940 			statp = kstat_waitq_enter;
15941 		}
15942 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
15943 		    "sd_set_retry_bp: un:0x%p already delayed retry\n", un);
15944 	}
15945 
15946 done:
15947 	if (statp != NULL) {
15948 		SD_UPDATE_KSTATS(un, statp, bp);
15949 	}
15950 
15951 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
15952 	    "sd_set_retry_bp: exit un:0x%p\n", un);
15953 }
15954 
15955 
15956 /*
15957  *    Function: sd_start_retry_command
15958  *
15959  * Description: Start the command that has been waiting on the target's
15960  *		retry queue.  Called from timeout(9F) context after the
15961  *		retry delay interval has expired.
15962  *
15963  *   Arguments: arg - pointer to associated softstate for the device.
15964  *
15965  *     Context: timeout(9F) thread context.  May not sleep.
15966  */
15967 
15968 static void
15969 sd_start_retry_command(void *arg)
15970 {
15971 	struct sd_lun *un = arg;
15972 
15973 	ASSERT(un != NULL);
15974 	ASSERT(!mutex_owned(SD_MUTEX(un)));
15975 
15976 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
15977 	    "sd_start_retry_command: entry\n");
15978 
15979 	mutex_enter(SD_MUTEX(un));
15980 
15981 	un->un_retry_timeid = NULL;
15982 
15983 	if (un->un_retry_bp != NULL) {
15984 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
15985 		    "sd_start_retry_command: un:0x%p STARTING bp:0x%p\n",
15986 		    un, un->un_retry_bp);
15987 		sd_start_cmds(un, un->un_retry_bp);
15988 	}
15989 
15990 	mutex_exit(SD_MUTEX(un));
15991 
15992 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
15993 	    "sd_start_retry_command: exit\n");
15994 }
15995 
15996 /*
15997  *    Function: sd_rmw_msg_print_handler
15998  *
15999  * Description: If RMW mode is enabled and warning message is triggered
16000  *              print I/O count during a fixed interval.
16001  *
16002  *   Arguments: arg - pointer to associated softstate for the device.
16003  *
16004  *     Context: timeout(9F) thread context. May not sleep.
16005  */
16006 static void
16007 sd_rmw_msg_print_handler(void *arg)
16008 {
16009 	struct sd_lun *un = arg;
16010 
16011 	ASSERT(un != NULL);
16012 	ASSERT(!mutex_owned(SD_MUTEX(un)));
16013 
16014 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
16015 	    "sd_rmw_msg_print_handler: entry\n");
16016 
16017 	mutex_enter(SD_MUTEX(un));
16018 
16019 	if (un->un_rmw_incre_count > 0) {
16020 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
16021 		    "%"PRIu64" I/O requests are not aligned with %d disk "
16022 		    "sector size in %ld seconds. They are handled through "
16023 		    "Read Modify Write but the performance is very low!\n",
16024 		    un->un_rmw_incre_count, un->un_tgt_blocksize,
16025 		    drv_hztousec(SD_RMW_MSG_PRINT_TIMEOUT) / 1000000);
16026 		un->un_rmw_incre_count = 0;
16027 		un->un_rmw_msg_timeid = timeout(sd_rmw_msg_print_handler,
16028 		    un, SD_RMW_MSG_PRINT_TIMEOUT);
16029 	} else {
16030 		un->un_rmw_msg_timeid = NULL;
16031 	}
16032 
16033 	mutex_exit(SD_MUTEX(un));
16034 
16035 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
16036 	    "sd_rmw_msg_print_handler: exit\n");
16037 }
16038 
16039 /*
16040  *    Function: sd_start_direct_priority_command
16041  *
16042  * Description: Used to re-start an SD_PATH_DIRECT_PRIORITY command that had
16043  *		received TRAN_BUSY when we called scsi_transport() to send it
16044  *		to the underlying HBA. This function is called from timeout(9F)
16045  *		context after the delay interval has expired.
16046  *
16047  *   Arguments: arg - pointer to associated buf(9S) to be restarted.
16048  *
16049  *     Context: timeout(9F) thread context.  May not sleep.
16050  */
16051 
16052 static void
16053 sd_start_direct_priority_command(void *arg)
16054 {
16055 	struct buf	*priority_bp = arg;
16056 	struct sd_lun	*un;
16057 
16058 	ASSERT(priority_bp != NULL);
16059 	un = SD_GET_UN(priority_bp);
16060 	ASSERT(un != NULL);
16061 	ASSERT(!mutex_owned(SD_MUTEX(un)));
16062 
16063 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
16064 	    "sd_start_direct_priority_command: entry\n");
16065 
16066 	mutex_enter(SD_MUTEX(un));
16067 	un->un_direct_priority_timeid = NULL;
16068 	sd_start_cmds(un, priority_bp);
16069 	mutex_exit(SD_MUTEX(un));
16070 
16071 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
16072 	    "sd_start_direct_priority_command: exit\n");
16073 }
16074 
16075 
16076 /*
16077  *    Function: sd_send_request_sense_command
16078  *
16079  * Description: Sends a REQUEST SENSE command to the target
16080  *
16081  *     Context: May be called from interrupt context.
16082  */
16083 
16084 static void
16085 sd_send_request_sense_command(struct sd_lun *un, struct buf *bp,
16086 	struct scsi_pkt *pktp)
16087 {
16088 	ASSERT(bp != NULL);
16089 	ASSERT(un != NULL);
16090 	ASSERT(mutex_owned(SD_MUTEX(un)));
16091 
16092 	SD_TRACE(SD_LOG_IO | SD_LOG_ERROR, un, "sd_send_request_sense_command: "
16093 	    "entry: buf:0x%p\n", bp);
16094 
16095 	/*
16096 	 * If we are syncing or dumping, then fail the command to avoid a
16097 	 * recursive callback into scsi_transport(). Also fail the command
16098 	 * if we are suspended (legacy behavior).
16099 	 */
16100 	if (ddi_in_panic() || (un->un_state == SD_STATE_SUSPENDED) ||
16101 	    (un->un_state == SD_STATE_DUMPING)) {
16102 		sd_return_failed_command(un, bp, EIO);
16103 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
16104 		    "sd_send_request_sense_command: syncing/dumping, exit\n");
16105 		return;
16106 	}
16107 
16108 	/*
16109 	 * Retry the failed command and don't issue the request sense if:
16110 	 *    1) the sense buf is busy
16111 	 *    2) we have 1 or more outstanding commands on the target
16112 	 *    (the sense data will be cleared or invalidated any way)
16113 	 *
16114 	 * Note: There could be an issue with not checking a retry limit here,
16115 	 * the problem is determining which retry limit to check.
16116 	 */
16117 	if ((un->un_sense_isbusy != 0) || (un->un_ncmds_in_transport > 0)) {
16118 		/* Don't retry if the command is flagged as non-retryable */
16119 		if ((pktp->pkt_flags & FLAG_DIAGNOSE) == 0) {
16120 			sd_retry_command(un, bp, SD_RETRIES_NOCHECK,
16121 			    NULL, NULL, 0, un->un_busy_timeout,
16122 			    kstat_waitq_enter);
16123 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
16124 			    "sd_send_request_sense_command: "
16125 			    "at full throttle, retrying exit\n");
16126 		} else {
16127 			sd_return_failed_command(un, bp, EIO);
16128 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
16129 			    "sd_send_request_sense_command: "
16130 			    "at full throttle, non-retryable exit\n");
16131 		}
16132 		return;
16133 	}
16134 
16135 	sd_mark_rqs_busy(un, bp);
16136 	sd_start_cmds(un, un->un_rqs_bp);
16137 
16138 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
16139 	    "sd_send_request_sense_command: exit\n");
16140 }
16141 
16142 
16143 /*
16144  *    Function: sd_mark_rqs_busy
16145  *
16146  * Description: Indicate that the request sense bp for this instance is
16147  *		in use.
16148  *
16149  *     Context: May be called under interrupt context
16150  */
16151 
16152 static void
16153 sd_mark_rqs_busy(struct sd_lun *un, struct buf *bp)
16154 {
16155 	struct sd_xbuf	*sense_xp;
16156 
16157 	ASSERT(un != NULL);
16158 	ASSERT(bp != NULL);
16159 	ASSERT(mutex_owned(SD_MUTEX(un)));
16160 	ASSERT(un->un_sense_isbusy == 0);
16161 
16162 	SD_TRACE(SD_LOG_IO_CORE, un, "sd_mark_rqs_busy: entry: "
16163 	    "buf:0x%p xp:0x%p un:0x%p\n", bp, SD_GET_XBUF(bp), un);
16164 
16165 	sense_xp = SD_GET_XBUF(un->un_rqs_bp);
16166 	ASSERT(sense_xp != NULL);
16167 
16168 	SD_INFO(SD_LOG_IO, un,
16169 	    "sd_mark_rqs_busy: entry: sense_xp:0x%p\n", sense_xp);
16170 
16171 	ASSERT(sense_xp->xb_pktp != NULL);
16172 	ASSERT((sense_xp->xb_pktp->pkt_flags & (FLAG_SENSING | FLAG_HEAD))
16173 	    == (FLAG_SENSING | FLAG_HEAD));
16174 
16175 	un->un_sense_isbusy = 1;
16176 	un->un_rqs_bp->b_resid = 0;
16177 	sense_xp->xb_pktp->pkt_resid  = 0;
16178 	sense_xp->xb_pktp->pkt_reason = 0;
16179 
16180 	/* So we can get back the bp at interrupt time! */
16181 	sense_xp->xb_sense_bp = bp;
16182 
16183 	bzero(un->un_rqs_bp->b_un.b_addr, SENSE_LENGTH);
16184 
16185 	/*
16186 	 * Mark this buf as awaiting sense data. (This is already set in
16187 	 * the pkt_flags for the RQS packet.)
16188 	 */
16189 	((SD_GET_XBUF(bp))->xb_pktp)->pkt_flags |= FLAG_SENSING;
16190 
16191 	/* Request sense down same path */
16192 	if (scsi_pkt_allocated_correctly((SD_GET_XBUF(bp))->xb_pktp) &&
16193 	    ((SD_GET_XBUF(bp))->xb_pktp)->pkt_path_instance)
16194 		sense_xp->xb_pktp->pkt_path_instance =
16195 		    ((SD_GET_XBUF(bp))->xb_pktp)->pkt_path_instance;
16196 
16197 	sense_xp->xb_retry_count	= 0;
16198 	sense_xp->xb_victim_retry_count = 0;
16199 	sense_xp->xb_ua_retry_count	= 0;
16200 	sense_xp->xb_nr_retry_count 	= 0;
16201 	sense_xp->xb_dma_resid  = 0;
16202 
16203 	/* Clean up the fields for auto-request sense */
16204 	sense_xp->xb_sense_status = 0;
16205 	sense_xp->xb_sense_state  = 0;
16206 	sense_xp->xb_sense_resid  = 0;
16207 	bzero(sense_xp->xb_sense_data, sizeof (sense_xp->xb_sense_data));
16208 
16209 	SD_TRACE(SD_LOG_IO_CORE, un, "sd_mark_rqs_busy: exit\n");
16210 }
16211 
16212 
16213 /*
16214  *    Function: sd_mark_rqs_idle
16215  *
16216  * Description: SD_MUTEX must be held continuously through this routine
16217  *		to prevent reuse of the rqs struct before the caller can
16218  *		complete it's processing.
16219  *
16220  * Return Code: Pointer to the RQS buf
16221  *
16222  *     Context: May be called under interrupt context
16223  */
16224 
16225 static struct buf *
16226 sd_mark_rqs_idle(struct sd_lun *un, struct sd_xbuf *sense_xp)
16227 {
16228 	struct buf *bp;
16229 	ASSERT(un != NULL);
16230 	ASSERT(sense_xp != NULL);
16231 	ASSERT(mutex_owned(SD_MUTEX(un)));
16232 	ASSERT(un->un_sense_isbusy != 0);
16233 
16234 	un->un_sense_isbusy = 0;
16235 	bp = sense_xp->xb_sense_bp;
16236 	sense_xp->xb_sense_bp = NULL;
16237 
16238 	/* This pkt is no longer interested in getting sense data */
16239 	((SD_GET_XBUF(bp))->xb_pktp)->pkt_flags &= ~FLAG_SENSING;
16240 
16241 	return (bp);
16242 }
16243 
16244 
16245 
16246 /*
16247  *    Function: sd_alloc_rqs
16248  *
16249  * Description: Set up the unit to receive auto request sense data
16250  *
16251  * Return Code: DDI_SUCCESS or DDI_FAILURE
16252  *
16253  *     Context: Called under attach(9E) context
16254  */
16255 
16256 static int
16257 sd_alloc_rqs(struct scsi_device *devp, struct sd_lun *un)
16258 {
16259 	struct sd_xbuf *xp;
16260 
16261 	ASSERT(un != NULL);
16262 	ASSERT(!mutex_owned(SD_MUTEX(un)));
16263 	ASSERT(un->un_rqs_bp == NULL);
16264 	ASSERT(un->un_rqs_pktp == NULL);
16265 
16266 	/*
16267 	 * First allocate the required buf and scsi_pkt structs, then set up
16268 	 * the CDB in the scsi_pkt for a REQUEST SENSE command.
16269 	 */
16270 	un->un_rqs_bp = scsi_alloc_consistent_buf(&devp->sd_address, NULL,
16271 	    MAX_SENSE_LENGTH, B_READ, SLEEP_FUNC, NULL);
16272 	if (un->un_rqs_bp == NULL) {
16273 		return (DDI_FAILURE);
16274 	}
16275 
16276 	un->un_rqs_pktp = scsi_init_pkt(&devp->sd_address, NULL, un->un_rqs_bp,
16277 	    CDB_GROUP0, 1, 0, PKT_CONSISTENT, SLEEP_FUNC, NULL);
16278 
16279 	if (un->un_rqs_pktp == NULL) {
16280 		sd_free_rqs(un);
16281 		return (DDI_FAILURE);
16282 	}
16283 
16284 	/* Set up the CDB in the scsi_pkt for a REQUEST SENSE command. */
16285 	(void) scsi_setup_cdb((union scsi_cdb *)un->un_rqs_pktp->pkt_cdbp,
16286 	    SCMD_REQUEST_SENSE, 0, MAX_SENSE_LENGTH, 0);
16287 
16288 	SD_FILL_SCSI1_LUN(un, un->un_rqs_pktp);
16289 
16290 	/* Set up the other needed members in the ARQ scsi_pkt. */
16291 	un->un_rqs_pktp->pkt_comp   = sdintr;
16292 	un->un_rqs_pktp->pkt_time   = sd_io_time;
16293 	un->un_rqs_pktp->pkt_flags |=
16294 	    (FLAG_SENSING | FLAG_HEAD);	/* (1222170) */
16295 
16296 	/*
16297 	 * Allocate  & init the sd_xbuf struct for the RQS command. Do not
16298 	 * provide any intpkt, destroypkt routines as we take care of
16299 	 * scsi_pkt allocation/freeing here and in sd_free_rqs().
16300 	 */
16301 	xp = kmem_alloc(sizeof (struct sd_xbuf), KM_SLEEP);
16302 	sd_xbuf_init(un, un->un_rqs_bp, xp, SD_CHAIN_NULL, NULL);
16303 	xp->xb_pktp = un->un_rqs_pktp;
16304 	SD_INFO(SD_LOG_ATTACH_DETACH, un,
16305 	    "sd_alloc_rqs: un 0x%p, rqs  xp 0x%p,  pkt 0x%p,  buf 0x%p\n",
16306 	    un, xp, un->un_rqs_pktp, un->un_rqs_bp);
16307 
16308 	/*
16309 	 * Save the pointer to the request sense private bp so it can
16310 	 * be retrieved in sdintr.
16311 	 */
16312 	un->un_rqs_pktp->pkt_private = un->un_rqs_bp;
16313 	ASSERT(un->un_rqs_bp->b_private == xp);
16314 
16315 	/*
16316 	 * See if the HBA supports auto-request sense for the specified
16317 	 * target/lun. If it does, then try to enable it (if not already
16318 	 * enabled).
16319 	 *
16320 	 * Note: For some HBAs (ifp & sf), scsi_ifsetcap will always return
16321 	 * failure, while for other HBAs (pln) scsi_ifsetcap will always
16322 	 * return success.  However, in both of these cases ARQ is always
16323 	 * enabled and scsi_ifgetcap will always return true. The best approach
16324 	 * is to issue the scsi_ifgetcap() first, then try the scsi_ifsetcap().
16325 	 *
16326 	 * The 3rd case is the HBA (adp) always return enabled on
16327 	 * scsi_ifgetgetcap even when it's not enable, the best approach
16328 	 * is issue a scsi_ifsetcap then a scsi_ifgetcap
16329 	 * Note: this case is to circumvent the Adaptec bug. (x86 only)
16330 	 */
16331 
16332 	if (un->un_f_is_fibre == TRUE) {
16333 		un->un_f_arq_enabled = TRUE;
16334 	} else {
16335 #if defined(__i386) || defined(__amd64)
16336 		/*
16337 		 * Circumvent the Adaptec bug, remove this code when
16338 		 * the bug is fixed
16339 		 */
16340 		(void) scsi_ifsetcap(SD_ADDRESS(un), "auto-rqsense", 1, 1);
16341 #endif
16342 		switch (scsi_ifgetcap(SD_ADDRESS(un), "auto-rqsense", 1)) {
16343 		case 0:
16344 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
16345 			    "sd_alloc_rqs: HBA supports ARQ\n");
16346 			/*
16347 			 * ARQ is supported by this HBA but currently is not
16348 			 * enabled. Attempt to enable it and if successful then
16349 			 * mark this instance as ARQ enabled.
16350 			 */
16351 			if (scsi_ifsetcap(SD_ADDRESS(un), "auto-rqsense", 1, 1)
16352 			    == 1) {
16353 				/* Successfully enabled ARQ in the HBA */
16354 				SD_INFO(SD_LOG_ATTACH_DETACH, un,
16355 				    "sd_alloc_rqs: ARQ enabled\n");
16356 				un->un_f_arq_enabled = TRUE;
16357 			} else {
16358 				/* Could not enable ARQ in the HBA */
16359 				SD_INFO(SD_LOG_ATTACH_DETACH, un,
16360 				    "sd_alloc_rqs: failed ARQ enable\n");
16361 				un->un_f_arq_enabled = FALSE;
16362 			}
16363 			break;
16364 		case 1:
16365 			/*
16366 			 * ARQ is supported by this HBA and is already enabled.
16367 			 * Just mark ARQ as enabled for this instance.
16368 			 */
16369 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
16370 			    "sd_alloc_rqs: ARQ already enabled\n");
16371 			un->un_f_arq_enabled = TRUE;
16372 			break;
16373 		default:
16374 			/*
16375 			 * ARQ is not supported by this HBA; disable it for this
16376 			 * instance.
16377 			 */
16378 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
16379 			    "sd_alloc_rqs: HBA does not support ARQ\n");
16380 			un->un_f_arq_enabled = FALSE;
16381 			break;
16382 		}
16383 	}
16384 
16385 	return (DDI_SUCCESS);
16386 }
16387 
16388 
16389 /*
16390  *    Function: sd_free_rqs
16391  *
16392  * Description: Cleanup for the pre-instance RQS command.
16393  *
16394  *     Context: Kernel thread context
16395  */
16396 
16397 static void
16398 sd_free_rqs(struct sd_lun *un)
16399 {
16400 	ASSERT(un != NULL);
16401 
16402 	SD_TRACE(SD_LOG_IO_CORE, un, "sd_free_rqs: entry\n");
16403 
16404 	/*
16405 	 * If consistent memory is bound to a scsi_pkt, the pkt
16406 	 * has to be destroyed *before* freeing the consistent memory.
16407 	 * Don't change the sequence of this operations.
16408 	 * scsi_destroy_pkt() might access memory, which isn't allowed,
16409 	 * after it was freed in scsi_free_consistent_buf().
16410 	 */
16411 	if (un->un_rqs_pktp != NULL) {
16412 		scsi_destroy_pkt(un->un_rqs_pktp);
16413 		un->un_rqs_pktp = NULL;
16414 	}
16415 
16416 	if (un->un_rqs_bp != NULL) {
16417 		struct sd_xbuf *xp = SD_GET_XBUF(un->un_rqs_bp);
16418 		if (xp != NULL) {
16419 			kmem_free(xp, sizeof (struct sd_xbuf));
16420 		}
16421 		scsi_free_consistent_buf(un->un_rqs_bp);
16422 		un->un_rqs_bp = NULL;
16423 	}
16424 	SD_TRACE(SD_LOG_IO_CORE, un, "sd_free_rqs: exit\n");
16425 }
16426 
16427 
16428 
16429 /*
16430  *    Function: sd_reduce_throttle
16431  *
16432  * Description: Reduces the maximum # of outstanding commands on a
16433  *		target to the current number of outstanding commands.
16434  *		Queues a tiemout(9F) callback to restore the limit
16435  *		after a specified interval has elapsed.
16436  *		Typically used when we get a TRAN_BUSY return code
16437  *		back from scsi_transport().
16438  *
16439  *   Arguments: un - ptr to the sd_lun softstate struct
16440  *		throttle_type: SD_THROTTLE_TRAN_BUSY or SD_THROTTLE_QFULL
16441  *
16442  *     Context: May be called from interrupt context
16443  */
16444 
16445 static void
16446 sd_reduce_throttle(struct sd_lun *un, int throttle_type)
16447 {
16448 	ASSERT(un != NULL);
16449 	ASSERT(mutex_owned(SD_MUTEX(un)));
16450 	ASSERT(un->un_ncmds_in_transport >= 0);
16451 
16452 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un, "sd_reduce_throttle: "
16453 	    "entry: un:0x%p un_throttle:%d un_ncmds_in_transport:%d\n",
16454 	    un, un->un_throttle, un->un_ncmds_in_transport);
16455 
16456 	if (un->un_throttle > 1) {
16457 		if (un->un_f_use_adaptive_throttle == TRUE) {
16458 			switch (throttle_type) {
16459 			case SD_THROTTLE_TRAN_BUSY:
16460 				if (un->un_busy_throttle == 0) {
16461 					un->un_busy_throttle = un->un_throttle;
16462 				}
16463 				break;
16464 			case SD_THROTTLE_QFULL:
16465 				un->un_busy_throttle = 0;
16466 				break;
16467 			default:
16468 				ASSERT(FALSE);
16469 			}
16470 
16471 			if (un->un_ncmds_in_transport > 0) {
16472 				un->un_throttle = un->un_ncmds_in_transport;
16473 			}
16474 
16475 		} else {
16476 			if (un->un_ncmds_in_transport == 0) {
16477 				un->un_throttle = 1;
16478 			} else {
16479 				un->un_throttle = un->un_ncmds_in_transport;
16480 			}
16481 		}
16482 	}
16483 
16484 	/* Reschedule the timeout if none is currently active */
16485 	if (un->un_reset_throttle_timeid == NULL) {
16486 		un->un_reset_throttle_timeid = timeout(sd_restore_throttle,
16487 		    un, SD_THROTTLE_RESET_INTERVAL);
16488 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
16489 		    "sd_reduce_throttle: timeout scheduled!\n");
16490 	}
16491 
16492 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un, "sd_reduce_throttle: "
16493 	    "exit: un:0x%p un_throttle:%d\n", un, un->un_throttle);
16494 }
16495 
16496 
16497 
16498 /*
16499  *    Function: sd_restore_throttle
16500  *
16501  * Description: Callback function for timeout(9F).  Resets the current
16502  *		value of un->un_throttle to its default.
16503  *
16504  *   Arguments: arg - pointer to associated softstate for the device.
16505  *
16506  *     Context: May be called from interrupt context
16507  */
16508 
16509 static void
16510 sd_restore_throttle(void *arg)
16511 {
16512 	struct sd_lun	*un = arg;
16513 
16514 	ASSERT(un != NULL);
16515 	ASSERT(!mutex_owned(SD_MUTEX(un)));
16516 
16517 	mutex_enter(SD_MUTEX(un));
16518 
16519 	SD_TRACE(SD_LOG_IO | SD_LOG_ERROR, un, "sd_restore_throttle: "
16520 	    "entry: un:0x%p un_throttle:%d\n", un, un->un_throttle);
16521 
16522 	un->un_reset_throttle_timeid = NULL;
16523 
16524 	if (un->un_f_use_adaptive_throttle == TRUE) {
16525 		/*
16526 		 * If un_busy_throttle is nonzero, then it contains the
16527 		 * value that un_throttle was when we got a TRAN_BUSY back
16528 		 * from scsi_transport(). We want to revert back to this
16529 		 * value.
16530 		 *
16531 		 * In the QFULL case, the throttle limit will incrementally
16532 		 * increase until it reaches max throttle.
16533 		 */
16534 		if (un->un_busy_throttle > 0) {
16535 			un->un_throttle = un->un_busy_throttle;
16536 			un->un_busy_throttle = 0;
16537 		} else {
16538 			/*
16539 			 * increase throttle by 10% open gate slowly, schedule
16540 			 * another restore if saved throttle has not been
16541 			 * reached
16542 			 */
16543 			short throttle;
16544 			if (sd_qfull_throttle_enable) {
16545 				throttle = un->un_throttle +
16546 				    max((un->un_throttle / 10), 1);
16547 				un->un_throttle =
16548 				    (throttle < un->un_saved_throttle) ?
16549 				    throttle : un->un_saved_throttle;
16550 				if (un->un_throttle < un->un_saved_throttle) {
16551 					un->un_reset_throttle_timeid =
16552 					    timeout(sd_restore_throttle,
16553 					    un,
16554 					    SD_QFULL_THROTTLE_RESET_INTERVAL);
16555 				}
16556 			}
16557 		}
16558 
16559 		/*
16560 		 * If un_throttle has fallen below the low-water mark, we
16561 		 * restore the maximum value here (and allow it to ratchet
16562 		 * down again if necessary).
16563 		 */
16564 		if (un->un_throttle < un->un_min_throttle) {
16565 			un->un_throttle = un->un_saved_throttle;
16566 		}
16567 	} else {
16568 		SD_TRACE(SD_LOG_IO | SD_LOG_ERROR, un, "sd_restore_throttle: "
16569 		    "restoring limit from 0x%x to 0x%x\n",
16570 		    un->un_throttle, un->un_saved_throttle);
16571 		un->un_throttle = un->un_saved_throttle;
16572 	}
16573 
16574 	SD_TRACE(SD_LOG_IO | SD_LOG_ERROR, un,
16575 	    "sd_restore_throttle: calling sd_start_cmds!\n");
16576 
16577 	sd_start_cmds(un, NULL);
16578 
16579 	SD_TRACE(SD_LOG_IO | SD_LOG_ERROR, un,
16580 	    "sd_restore_throttle: exit: un:0x%p un_throttle:%d\n",
16581 	    un, un->un_throttle);
16582 
16583 	mutex_exit(SD_MUTEX(un));
16584 
16585 	SD_TRACE(SD_LOG_IO | SD_LOG_ERROR, un, "sd_restore_throttle: exit\n");
16586 }
16587 
16588 /*
16589  *    Function: sdrunout
16590  *
16591  * Description: Callback routine for scsi_init_pkt when a resource allocation
16592  *		fails.
16593  *
16594  *   Arguments: arg - a pointer to the sd_lun unit struct for the particular
16595  *		soft state instance.
16596  *
16597  * Return Code: The scsi_init_pkt routine allows for the callback function to
16598  *		return a 0 indicating the callback should be rescheduled or a 1
16599  *		indicating not to reschedule. This routine always returns 1
16600  *		because the driver always provides a callback function to
16601  *		scsi_init_pkt. This results in a callback always being scheduled
16602  *		(via the scsi_init_pkt callback implementation) if a resource
16603  *		failure occurs.
16604  *
16605  *     Context: This callback function may not block or call routines that block
16606  *
16607  *        Note: Using the scsi_init_pkt callback facility can result in an I/O
16608  *		request persisting at the head of the list which cannot be
16609  *		satisfied even after multiple retries. In the future the driver
16610  *		may implement some time of maximum runout count before failing
16611  *		an I/O.
16612  */
16613 
16614 static int
16615 sdrunout(caddr_t arg)
16616 {
16617 	struct sd_lun	*un = (struct sd_lun *)arg;
16618 
16619 	ASSERT(un != NULL);
16620 	ASSERT(!mutex_owned(SD_MUTEX(un)));
16621 
16622 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un, "sdrunout: entry\n");
16623 
16624 	mutex_enter(SD_MUTEX(un));
16625 	sd_start_cmds(un, NULL);
16626 	mutex_exit(SD_MUTEX(un));
16627 	/*
16628 	 * This callback routine always returns 1 (i.e. do not reschedule)
16629 	 * because we always specify sdrunout as the callback handler for
16630 	 * scsi_init_pkt inside the call to sd_start_cmds.
16631 	 */
16632 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un, "sdrunout: exit\n");
16633 	return (1);
16634 }
16635 
16636 
16637 /*
16638  *    Function: sdintr
16639  *
16640  * Description: Completion callback routine for scsi_pkt(9S) structs
16641  *		sent to the HBA driver via scsi_transport(9F).
16642  *
16643  *     Context: Interrupt context
16644  */
16645 
16646 static void
16647 sdintr(struct scsi_pkt *pktp)
16648 {
16649 	struct buf	*bp;
16650 	struct sd_xbuf	*xp;
16651 	struct sd_lun	*un;
16652 	size_t		actual_len;
16653 	sd_ssc_t	*sscp;
16654 
16655 	ASSERT(pktp != NULL);
16656 	bp = (struct buf *)pktp->pkt_private;
16657 	ASSERT(bp != NULL);
16658 	xp = SD_GET_XBUF(bp);
16659 	ASSERT(xp != NULL);
16660 	ASSERT(xp->xb_pktp != NULL);
16661 	un = SD_GET_UN(bp);
16662 	ASSERT(un != NULL);
16663 	ASSERT(!mutex_owned(SD_MUTEX(un)));
16664 
16665 #ifdef SD_FAULT_INJECTION
16666 
16667 	SD_INFO(SD_LOG_IOERR, un, "sdintr: sdintr calling Fault injection\n");
16668 	/* SD FaultInjection */
16669 	sd_faultinjection(pktp);
16670 
16671 #endif /* SD_FAULT_INJECTION */
16672 
16673 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un, "sdintr: entry: buf:0x%p,"
16674 	    " xp:0x%p, un:0x%p\n", bp, xp, un);
16675 
16676 	mutex_enter(SD_MUTEX(un));
16677 
16678 	ASSERT(un->un_fm_private != NULL);
16679 	sscp = &((struct sd_fm_internal *)(un->un_fm_private))->fm_ssc;
16680 	ASSERT(sscp != NULL);
16681 
16682 	/* Reduce the count of the #commands currently in transport */
16683 	un->un_ncmds_in_transport--;
16684 	ASSERT(un->un_ncmds_in_transport >= 0);
16685 
16686 	/* Increment counter to indicate that the callback routine is active */
16687 	un->un_in_callback++;
16688 
16689 	SD_UPDATE_KSTATS(un, kstat_runq_exit, bp);
16690 
16691 #ifdef	SDDEBUG
16692 	if (bp == un->un_retry_bp) {
16693 		SD_TRACE(SD_LOG_IO | SD_LOG_ERROR, un, "sdintr: "
16694 		    "un:0x%p: GOT retry_bp:0x%p un_ncmds_in_transport:%d\n",
16695 		    un, un->un_retry_bp, un->un_ncmds_in_transport);
16696 	}
16697 #endif
16698 
16699 	/*
16700 	 * If pkt_reason is CMD_DEV_GONE, fail the command, and update the media
16701 	 * state if needed.
16702 	 */
16703 	if (pktp->pkt_reason == CMD_DEV_GONE) {
16704 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
16705 		    "Command failed to complete...Device is gone\n");
16706 		if (un->un_mediastate != DKIO_DEV_GONE) {
16707 			un->un_mediastate = DKIO_DEV_GONE;
16708 			cv_broadcast(&un->un_state_cv);
16709 		}
16710 		/*
16711 		 * If the command happens to be the REQUEST SENSE command,
16712 		 * free up the rqs buf and fail the original command.
16713 		 */
16714 		if (bp == un->un_rqs_bp) {
16715 			bp = sd_mark_rqs_idle(un, xp);
16716 		}
16717 		sd_return_failed_command(un, bp, EIO);
16718 		goto exit;
16719 	}
16720 
16721 	if (pktp->pkt_state & STATE_XARQ_DONE) {
16722 		SD_TRACE(SD_LOG_COMMON, un,
16723 		    "sdintr: extra sense data received. pkt=%p\n", pktp);
16724 	}
16725 
16726 	/*
16727 	 * First see if the pkt has auto-request sense data with it....
16728 	 * Look at the packet state first so we don't take a performance
16729 	 * hit looking at the arq enabled flag unless absolutely necessary.
16730 	 */
16731 	if ((pktp->pkt_state & STATE_ARQ_DONE) &&
16732 	    (un->un_f_arq_enabled == TRUE)) {
16733 		/*
16734 		 * The HBA did an auto request sense for this command so check
16735 		 * for FLAG_DIAGNOSE. If set this indicates a uscsi or internal
16736 		 * driver command that should not be retried.
16737 		 */
16738 		if ((pktp->pkt_flags & FLAG_DIAGNOSE) != 0) {
16739 			/*
16740 			 * Save the relevant sense info into the xp for the
16741 			 * original cmd.
16742 			 */
16743 			struct scsi_arq_status *asp;
16744 			asp = (struct scsi_arq_status *)(pktp->pkt_scbp);
16745 			xp->xb_sense_status =
16746 			    *((uchar_t *)(&(asp->sts_rqpkt_status)));
16747 			xp->xb_sense_state  = asp->sts_rqpkt_state;
16748 			xp->xb_sense_resid  = asp->sts_rqpkt_resid;
16749 			if (pktp->pkt_state & STATE_XARQ_DONE) {
16750 				actual_len = MAX_SENSE_LENGTH -
16751 				    xp->xb_sense_resid;
16752 				bcopy(&asp->sts_sensedata, xp->xb_sense_data,
16753 				    MAX_SENSE_LENGTH);
16754 			} else {
16755 				if (xp->xb_sense_resid > SENSE_LENGTH) {
16756 					actual_len = MAX_SENSE_LENGTH -
16757 					    xp->xb_sense_resid;
16758 				} else {
16759 					actual_len = SENSE_LENGTH -
16760 					    xp->xb_sense_resid;
16761 				}
16762 				if (xp->xb_pkt_flags & SD_XB_USCSICMD) {
16763 					if ((((struct uscsi_cmd *)
16764 					    (xp->xb_pktinfo))->uscsi_rqlen) >
16765 					    actual_len) {
16766 						xp->xb_sense_resid =
16767 						    (((struct uscsi_cmd *)
16768 						    (xp->xb_pktinfo))->
16769 						    uscsi_rqlen) - actual_len;
16770 					} else {
16771 						xp->xb_sense_resid = 0;
16772 					}
16773 				}
16774 				bcopy(&asp->sts_sensedata, xp->xb_sense_data,
16775 				    SENSE_LENGTH);
16776 			}
16777 
16778 			/* fail the command */
16779 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
16780 			    "sdintr: arq done and FLAG_DIAGNOSE set\n");
16781 			sd_return_failed_command(un, bp, EIO);
16782 			goto exit;
16783 		}
16784 
16785 #if (defined(__i386) || defined(__amd64))	/* DMAFREE for x86 only */
16786 		/*
16787 		 * We want to either retry or fail this command, so free
16788 		 * the DMA resources here.  If we retry the command then
16789 		 * the DMA resources will be reallocated in sd_start_cmds().
16790 		 * Note that when PKT_DMA_PARTIAL is used, this reallocation
16791 		 * causes the *entire* transfer to start over again from the
16792 		 * beginning of the request, even for PARTIAL chunks that
16793 		 * have already transferred successfully.
16794 		 */
16795 		if ((un->un_f_is_fibre == TRUE) &&
16796 		    ((xp->xb_pkt_flags & SD_XB_USCSICMD) == 0) &&
16797 		    ((pktp->pkt_flags & FLAG_SENSING) == 0))  {
16798 			scsi_dmafree(pktp);
16799 			xp->xb_pkt_flags |= SD_XB_DMA_FREED;
16800 		}
16801 #endif
16802 
16803 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
16804 		    "sdintr: arq done, sd_handle_auto_request_sense\n");
16805 
16806 		sd_handle_auto_request_sense(un, bp, xp, pktp);
16807 		goto exit;
16808 	}
16809 
16810 	/* Next see if this is the REQUEST SENSE pkt for the instance */
16811 	if (pktp->pkt_flags & FLAG_SENSING)  {
16812 		/* This pktp is from the unit's REQUEST_SENSE command */
16813 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
16814 		    "sdintr: sd_handle_request_sense\n");
16815 		sd_handle_request_sense(un, bp, xp, pktp);
16816 		goto exit;
16817 	}
16818 
16819 	/*
16820 	 * Check to see if the command successfully completed as requested;
16821 	 * this is the most common case (and also the hot performance path).
16822 	 *
16823 	 * Requirements for successful completion are:
16824 	 * pkt_reason is CMD_CMPLT and packet status is status good.
16825 	 * In addition:
16826 	 * - A residual of zero indicates successful completion no matter what
16827 	 *   the command is.
16828 	 * - If the residual is not zero and the command is not a read or
16829 	 *   write, then it's still defined as successful completion. In other
16830 	 *   words, if the command is a read or write the residual must be
16831 	 *   zero for successful completion.
16832 	 * - If the residual is not zero and the command is a read or
16833 	 *   write, and it's a USCSICMD, then it's still defined as
16834 	 *   successful completion.
16835 	 */
16836 	if ((pktp->pkt_reason == CMD_CMPLT) &&
16837 	    (SD_GET_PKT_STATUS(pktp) == STATUS_GOOD)) {
16838 
16839 		/*
16840 		 * Since this command is returned with a good status, we
16841 		 * can reset the count for Sonoma failover.
16842 		 */
16843 		un->un_sonoma_failure_count = 0;
16844 
16845 		/*
16846 		 * Return all USCSI commands on good status
16847 		 */
16848 		if (pktp->pkt_resid == 0) {
16849 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
16850 			    "sdintr: returning command for resid == 0\n");
16851 		} else if (((SD_GET_PKT_OPCODE(pktp) & 0x1F) != SCMD_READ) &&
16852 		    ((SD_GET_PKT_OPCODE(pktp) & 0x1F) != SCMD_WRITE)) {
16853 			SD_UPDATE_B_RESID(bp, pktp);
16854 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
16855 			    "sdintr: returning command for resid != 0\n");
16856 		} else if (xp->xb_pkt_flags & SD_XB_USCSICMD) {
16857 			SD_UPDATE_B_RESID(bp, pktp);
16858 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
16859 			    "sdintr: returning uscsi command\n");
16860 		} else {
16861 			goto not_successful;
16862 		}
16863 		sd_return_command(un, bp);
16864 
16865 		/*
16866 		 * Decrement counter to indicate that the callback routine
16867 		 * is done.
16868 		 */
16869 		un->un_in_callback--;
16870 		ASSERT(un->un_in_callback >= 0);
16871 		mutex_exit(SD_MUTEX(un));
16872 
16873 		return;
16874 	}
16875 
16876 not_successful:
16877 
16878 #if (defined(__i386) || defined(__amd64))	/* DMAFREE for x86 only */
16879 	/*
16880 	 * The following is based upon knowledge of the underlying transport
16881 	 * and its use of DMA resources.  This code should be removed when
16882 	 * PKT_DMA_PARTIAL support is taken out of the disk driver in favor
16883 	 * of the new PKT_CMD_BREAKUP protocol. See also sd_initpkt_for_buf()
16884 	 * and sd_start_cmds().
16885 	 *
16886 	 * Free any DMA resources associated with this command if there
16887 	 * is a chance it could be retried or enqueued for later retry.
16888 	 * If we keep the DMA binding then mpxio cannot reissue the
16889 	 * command on another path whenever a path failure occurs.
16890 	 *
16891 	 * Note that when PKT_DMA_PARTIAL is used, free/reallocation
16892 	 * causes the *entire* transfer to start over again from the
16893 	 * beginning of the request, even for PARTIAL chunks that
16894 	 * have already transferred successfully.
16895 	 *
16896 	 * This is only done for non-uscsi commands (and also skipped for the
16897 	 * driver's internal RQS command). Also just do this for Fibre Channel
16898 	 * devices as these are the only ones that support mpxio.
16899 	 */
16900 	if ((un->un_f_is_fibre == TRUE) &&
16901 	    ((xp->xb_pkt_flags & SD_XB_USCSICMD) == 0) &&
16902 	    ((pktp->pkt_flags & FLAG_SENSING) == 0))  {
16903 		scsi_dmafree(pktp);
16904 		xp->xb_pkt_flags |= SD_XB_DMA_FREED;
16905 	}
16906 #endif
16907 
16908 	/*
16909 	 * The command did not successfully complete as requested so check
16910 	 * for FLAG_DIAGNOSE. If set this indicates a uscsi or internal
16911 	 * driver command that should not be retried so just return. If
16912 	 * FLAG_DIAGNOSE is not set the error will be processed below.
16913 	 */
16914 	if ((pktp->pkt_flags & FLAG_DIAGNOSE) != 0) {
16915 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
16916 		    "sdintr: FLAG_DIAGNOSE: sd_return_failed_command\n");
16917 		/*
16918 		 * Issue a request sense if a check condition caused the error
16919 		 * (we handle the auto request sense case above), otherwise
16920 		 * just fail the command.
16921 		 */
16922 		if ((pktp->pkt_reason == CMD_CMPLT) &&
16923 		    (SD_GET_PKT_STATUS(pktp) == STATUS_CHECK)) {
16924 			sd_send_request_sense_command(un, bp, pktp);
16925 		} else {
16926 			sd_return_failed_command(un, bp, EIO);
16927 		}
16928 		goto exit;
16929 	}
16930 
16931 	/*
16932 	 * The command did not successfully complete as requested so process
16933 	 * the error, retry, and/or attempt recovery.
16934 	 */
16935 	switch (pktp->pkt_reason) {
16936 	case CMD_CMPLT:
16937 		switch (SD_GET_PKT_STATUS(pktp)) {
16938 		case STATUS_GOOD:
16939 			/*
16940 			 * The command completed successfully with a non-zero
16941 			 * residual
16942 			 */
16943 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
16944 			    "sdintr: STATUS_GOOD \n");
16945 			sd_pkt_status_good(un, bp, xp, pktp);
16946 			break;
16947 
16948 		case STATUS_CHECK:
16949 		case STATUS_TERMINATED:
16950 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
16951 			    "sdintr: STATUS_TERMINATED | STATUS_CHECK\n");
16952 			sd_pkt_status_check_condition(un, bp, xp, pktp);
16953 			break;
16954 
16955 		case STATUS_BUSY:
16956 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
16957 			    "sdintr: STATUS_BUSY\n");
16958 			sd_pkt_status_busy(un, bp, xp, pktp);
16959 			break;
16960 
16961 		case STATUS_RESERVATION_CONFLICT:
16962 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
16963 			    "sdintr: STATUS_RESERVATION_CONFLICT\n");
16964 			sd_pkt_status_reservation_conflict(un, bp, xp, pktp);
16965 			break;
16966 
16967 		case STATUS_QFULL:
16968 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
16969 			    "sdintr: STATUS_QFULL\n");
16970 			sd_pkt_status_qfull(un, bp, xp, pktp);
16971 			break;
16972 
16973 		case STATUS_MET:
16974 		case STATUS_INTERMEDIATE:
16975 		case STATUS_SCSI2:
16976 		case STATUS_INTERMEDIATE_MET:
16977 		case STATUS_ACA_ACTIVE:
16978 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
16979 			    "Unexpected SCSI status received: 0x%x\n",
16980 			    SD_GET_PKT_STATUS(pktp));
16981 			/*
16982 			 * Mark the ssc_flags when detected invalid status
16983 			 * code for non-USCSI command.
16984 			 */
16985 			if (!(xp->xb_pkt_flags & SD_XB_USCSICMD)) {
16986 				sd_ssc_set_info(sscp, SSC_FLAGS_INVALID_STATUS,
16987 				    0, "stat-code");
16988 			}
16989 			sd_return_failed_command(un, bp, EIO);
16990 			break;
16991 
16992 		default:
16993 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
16994 			    "Invalid SCSI status received: 0x%x\n",
16995 			    SD_GET_PKT_STATUS(pktp));
16996 			if (!(xp->xb_pkt_flags & SD_XB_USCSICMD)) {
16997 				sd_ssc_set_info(sscp, SSC_FLAGS_INVALID_STATUS,
16998 				    0, "stat-code");
16999 			}
17000 			sd_return_failed_command(un, bp, EIO);
17001 			break;
17002 
17003 		}
17004 		break;
17005 
17006 	case CMD_INCOMPLETE:
17007 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
17008 		    "sdintr:  CMD_INCOMPLETE\n");
17009 		sd_pkt_reason_cmd_incomplete(un, bp, xp, pktp);
17010 		break;
17011 	case CMD_TRAN_ERR:
17012 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
17013 		    "sdintr: CMD_TRAN_ERR\n");
17014 		sd_pkt_reason_cmd_tran_err(un, bp, xp, pktp);
17015 		break;
17016 	case CMD_RESET:
17017 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
17018 		    "sdintr: CMD_RESET \n");
17019 		sd_pkt_reason_cmd_reset(un, bp, xp, pktp);
17020 		break;
17021 	case CMD_ABORTED:
17022 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
17023 		    "sdintr: CMD_ABORTED \n");
17024 		sd_pkt_reason_cmd_aborted(un, bp, xp, pktp);
17025 		break;
17026 	case CMD_TIMEOUT:
17027 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
17028 		    "sdintr: CMD_TIMEOUT\n");
17029 		sd_pkt_reason_cmd_timeout(un, bp, xp, pktp);
17030 		break;
17031 	case CMD_UNX_BUS_FREE:
17032 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
17033 		    "sdintr: CMD_UNX_BUS_FREE \n");
17034 		sd_pkt_reason_cmd_unx_bus_free(un, bp, xp, pktp);
17035 		break;
17036 	case CMD_TAG_REJECT:
17037 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
17038 		    "sdintr: CMD_TAG_REJECT\n");
17039 		sd_pkt_reason_cmd_tag_reject(un, bp, xp, pktp);
17040 		break;
17041 	default:
17042 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
17043 		    "sdintr: default\n");
17044 		/*
17045 		 * Mark the ssc_flags for detecting invliad pkt_reason.
17046 		 */
17047 		if (!(xp->xb_pkt_flags & SD_XB_USCSICMD)) {
17048 			sd_ssc_set_info(sscp, SSC_FLAGS_INVALID_PKT_REASON,
17049 			    0, "pkt-reason");
17050 		}
17051 		sd_pkt_reason_default(un, bp, xp, pktp);
17052 		break;
17053 	}
17054 
17055 exit:
17056 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un, "sdintr: exit\n");
17057 
17058 	/* Decrement counter to indicate that the callback routine is done. */
17059 	un->un_in_callback--;
17060 	ASSERT(un->un_in_callback >= 0);
17061 
17062 	/*
17063 	 * At this point, the pkt has been dispatched, ie, it is either
17064 	 * being re-tried or has been returned to its caller and should
17065 	 * not be referenced.
17066 	 */
17067 
17068 	mutex_exit(SD_MUTEX(un));
17069 }
17070 
17071 
17072 /*
17073  *    Function: sd_print_incomplete_msg
17074  *
17075  * Description: Prints the error message for a CMD_INCOMPLETE error.
17076  *
17077  *   Arguments: un - ptr to associated softstate for the device.
17078  *		bp - ptr to the buf(9S) for the command.
17079  *		arg - message string ptr
17080  *		code - SD_DELAYED_RETRY_ISSUED, SD_IMMEDIATE_RETRY_ISSUED,
17081  *			or SD_NO_RETRY_ISSUED.
17082  *
17083  *     Context: May be called under interrupt context
17084  */
17085 
17086 static void
17087 sd_print_incomplete_msg(struct sd_lun *un, struct buf *bp, void *arg, int code)
17088 {
17089 	struct scsi_pkt	*pktp;
17090 	char	*msgp;
17091 	char	*cmdp = arg;
17092 
17093 	ASSERT(un != NULL);
17094 	ASSERT(mutex_owned(SD_MUTEX(un)));
17095 	ASSERT(bp != NULL);
17096 	ASSERT(arg != NULL);
17097 	pktp = SD_GET_PKTP(bp);
17098 	ASSERT(pktp != NULL);
17099 
17100 	switch (code) {
17101 	case SD_DELAYED_RETRY_ISSUED:
17102 	case SD_IMMEDIATE_RETRY_ISSUED:
17103 		msgp = "retrying";
17104 		break;
17105 	case SD_NO_RETRY_ISSUED:
17106 	default:
17107 		msgp = "giving up";
17108 		break;
17109 	}
17110 
17111 	if ((pktp->pkt_flags & FLAG_SILENT) == 0) {
17112 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
17113 		    "incomplete %s- %s\n", cmdp, msgp);
17114 	}
17115 }
17116 
17117 
17118 
17119 /*
17120  *    Function: sd_pkt_status_good
17121  *
17122  * Description: Processing for a STATUS_GOOD code in pkt_status.
17123  *
17124  *     Context: May be called under interrupt context
17125  */
17126 
17127 static void
17128 sd_pkt_status_good(struct sd_lun *un, struct buf *bp,
17129 	struct sd_xbuf *xp, struct scsi_pkt *pktp)
17130 {
17131 	char	*cmdp;
17132 
17133 	ASSERT(un != NULL);
17134 	ASSERT(mutex_owned(SD_MUTEX(un)));
17135 	ASSERT(bp != NULL);
17136 	ASSERT(xp != NULL);
17137 	ASSERT(pktp != NULL);
17138 	ASSERT(pktp->pkt_reason == CMD_CMPLT);
17139 	ASSERT(SD_GET_PKT_STATUS(pktp) == STATUS_GOOD);
17140 	ASSERT(pktp->pkt_resid != 0);
17141 
17142 	SD_TRACE(SD_LOG_IO_CORE, un, "sd_pkt_status_good: entry\n");
17143 
17144 	SD_UPDATE_ERRSTATS(un, sd_harderrs);
17145 	switch (SD_GET_PKT_OPCODE(pktp) & 0x1F) {
17146 	case SCMD_READ:
17147 		cmdp = "read";
17148 		break;
17149 	case SCMD_WRITE:
17150 		cmdp = "write";
17151 		break;
17152 	default:
17153 		SD_UPDATE_B_RESID(bp, pktp);
17154 		sd_return_command(un, bp);
17155 		SD_TRACE(SD_LOG_IO_CORE, un, "sd_pkt_status_good: exit\n");
17156 		return;
17157 	}
17158 
17159 	/*
17160 	 * See if we can retry the read/write, preferrably immediately.
17161 	 * If retries are exhaused, then sd_retry_command() will update
17162 	 * the b_resid count.
17163 	 */
17164 	sd_retry_command(un, bp, SD_RETRIES_STANDARD, sd_print_incomplete_msg,
17165 	    cmdp, EIO, (clock_t)0, NULL);
17166 
17167 	SD_TRACE(SD_LOG_IO_CORE, un, "sd_pkt_status_good: exit\n");
17168 }
17169 
17170 
17171 
17172 
17173 
17174 /*
17175  *    Function: sd_handle_request_sense
17176  *
17177  * Description: Processing for non-auto Request Sense command.
17178  *
17179  *   Arguments: un - ptr to associated softstate
17180  *		sense_bp - ptr to buf(9S) for the RQS command
17181  *		sense_xp - ptr to the sd_xbuf for the RQS command
17182  *		sense_pktp - ptr to the scsi_pkt(9S) for the RQS command
17183  *
17184  *     Context: May be called under interrupt context
17185  */
17186 
17187 static void
17188 sd_handle_request_sense(struct sd_lun *un, struct buf *sense_bp,
17189 	struct sd_xbuf *sense_xp, struct scsi_pkt *sense_pktp)
17190 {
17191 	struct buf	*cmd_bp;	/* buf for the original command */
17192 	struct sd_xbuf	*cmd_xp;	/* sd_xbuf for the original command */
17193 	struct scsi_pkt *cmd_pktp;	/* pkt for the original command */
17194 	size_t		actual_len;	/* actual sense data length */
17195 
17196 	ASSERT(un != NULL);
17197 	ASSERT(mutex_owned(SD_MUTEX(un)));
17198 	ASSERT(sense_bp != NULL);
17199 	ASSERT(sense_xp != NULL);
17200 	ASSERT(sense_pktp != NULL);
17201 
17202 	/*
17203 	 * Note the sense_bp, sense_xp, and sense_pktp here are for the
17204 	 * RQS command and not the original command.
17205 	 */
17206 	ASSERT(sense_pktp == un->un_rqs_pktp);
17207 	ASSERT(sense_bp   == un->un_rqs_bp);
17208 	ASSERT((sense_pktp->pkt_flags & (FLAG_SENSING | FLAG_HEAD)) ==
17209 	    (FLAG_SENSING | FLAG_HEAD));
17210 	ASSERT((((SD_GET_XBUF(sense_xp->xb_sense_bp))->xb_pktp->pkt_flags) &
17211 	    FLAG_SENSING) == FLAG_SENSING);
17212 
17213 	/* These are the bp, xp, and pktp for the original command */
17214 	cmd_bp = sense_xp->xb_sense_bp;
17215 	cmd_xp = SD_GET_XBUF(cmd_bp);
17216 	cmd_pktp = SD_GET_PKTP(cmd_bp);
17217 
17218 	if (sense_pktp->pkt_reason != CMD_CMPLT) {
17219 		/*
17220 		 * The REQUEST SENSE command failed.  Release the REQUEST
17221 		 * SENSE command for re-use, get back the bp for the original
17222 		 * command, and attempt to re-try the original command if
17223 		 * FLAG_DIAGNOSE is not set in the original packet.
17224 		 */
17225 		SD_UPDATE_ERRSTATS(un, sd_harderrs);
17226 		if ((cmd_pktp->pkt_flags & FLAG_DIAGNOSE) == 0) {
17227 			cmd_bp = sd_mark_rqs_idle(un, sense_xp);
17228 			sd_retry_command(un, cmd_bp, SD_RETRIES_STANDARD,
17229 			    NULL, NULL, EIO, (clock_t)0, NULL);
17230 			return;
17231 		}
17232 	}
17233 
17234 	/*
17235 	 * Save the relevant sense info into the xp for the original cmd.
17236 	 *
17237 	 * Note: if the request sense failed the state info will be zero
17238 	 * as set in sd_mark_rqs_busy()
17239 	 */
17240 	cmd_xp->xb_sense_status = *(sense_pktp->pkt_scbp);
17241 	cmd_xp->xb_sense_state  = sense_pktp->pkt_state;
17242 	actual_len = MAX_SENSE_LENGTH - sense_pktp->pkt_resid;
17243 	if ((cmd_xp->xb_pkt_flags & SD_XB_USCSICMD) &&
17244 	    (((struct uscsi_cmd *)cmd_xp->xb_pktinfo)->uscsi_rqlen >
17245 	    SENSE_LENGTH)) {
17246 		bcopy(sense_bp->b_un.b_addr, cmd_xp->xb_sense_data,
17247 		    MAX_SENSE_LENGTH);
17248 		cmd_xp->xb_sense_resid = sense_pktp->pkt_resid;
17249 	} else {
17250 		bcopy(sense_bp->b_un.b_addr, cmd_xp->xb_sense_data,
17251 		    SENSE_LENGTH);
17252 		if (actual_len < SENSE_LENGTH) {
17253 			cmd_xp->xb_sense_resid = SENSE_LENGTH - actual_len;
17254 		} else {
17255 			cmd_xp->xb_sense_resid = 0;
17256 		}
17257 	}
17258 
17259 	/*
17260 	 *  Free up the RQS command....
17261 	 *  NOTE:
17262 	 *	Must do this BEFORE calling sd_validate_sense_data!
17263 	 *	sd_validate_sense_data may return the original command in
17264 	 *	which case the pkt will be freed and the flags can no
17265 	 *	longer be touched.
17266 	 *	SD_MUTEX is held through this process until the command
17267 	 *	is dispatched based upon the sense data, so there are
17268 	 *	no race conditions.
17269 	 */
17270 	(void) sd_mark_rqs_idle(un, sense_xp);
17271 
17272 	/*
17273 	 * For a retryable command see if we have valid sense data, if so then
17274 	 * turn it over to sd_decode_sense() to figure out the right course of
17275 	 * action. Just fail a non-retryable command.
17276 	 */
17277 	if ((cmd_pktp->pkt_flags & FLAG_DIAGNOSE) == 0) {
17278 		if (sd_validate_sense_data(un, cmd_bp, cmd_xp, actual_len) ==
17279 		    SD_SENSE_DATA_IS_VALID) {
17280 			sd_decode_sense(un, cmd_bp, cmd_xp, cmd_pktp);
17281 		}
17282 	} else {
17283 		SD_DUMP_MEMORY(un, SD_LOG_IO_CORE, "Failed CDB",
17284 		    (uchar_t *)cmd_pktp->pkt_cdbp, CDB_SIZE, SD_LOG_HEX);
17285 		SD_DUMP_MEMORY(un, SD_LOG_IO_CORE, "Sense Data",
17286 		    (uchar_t *)cmd_xp->xb_sense_data, SENSE_LENGTH, SD_LOG_HEX);
17287 		sd_return_failed_command(un, cmd_bp, EIO);
17288 	}
17289 }
17290 
17291 
17292 
17293 
17294 /*
17295  *    Function: sd_handle_auto_request_sense
17296  *
17297  * Description: Processing for auto-request sense information.
17298  *
17299  *   Arguments: un - ptr to associated softstate
17300  *		bp - ptr to buf(9S) for the command
17301  *		xp - ptr to the sd_xbuf for the command
17302  *		pktp - ptr to the scsi_pkt(9S) for the command
17303  *
17304  *     Context: May be called under interrupt context
17305  */
17306 
17307 static void
17308 sd_handle_auto_request_sense(struct sd_lun *un, struct buf *bp,
17309 	struct sd_xbuf *xp, struct scsi_pkt *pktp)
17310 {
17311 	struct scsi_arq_status *asp;
17312 	size_t actual_len;
17313 
17314 	ASSERT(un != NULL);
17315 	ASSERT(mutex_owned(SD_MUTEX(un)));
17316 	ASSERT(bp != NULL);
17317 	ASSERT(xp != NULL);
17318 	ASSERT(pktp != NULL);
17319 	ASSERT(pktp != un->un_rqs_pktp);
17320 	ASSERT(bp   != un->un_rqs_bp);
17321 
17322 	/*
17323 	 * For auto-request sense, we get a scsi_arq_status back from
17324 	 * the HBA, with the sense data in the sts_sensedata member.
17325 	 * The pkt_scbp of the packet points to this scsi_arq_status.
17326 	 */
17327 	asp = (struct scsi_arq_status *)(pktp->pkt_scbp);
17328 
17329 	if (asp->sts_rqpkt_reason != CMD_CMPLT) {
17330 		/*
17331 		 * The auto REQUEST SENSE failed; see if we can re-try
17332 		 * the original command.
17333 		 */
17334 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
17335 		    "auto request sense failed (reason=%s)\n",
17336 		    scsi_rname(asp->sts_rqpkt_reason));
17337 
17338 		sd_reset_target(un, pktp);
17339 
17340 		sd_retry_command(un, bp, SD_RETRIES_STANDARD,
17341 		    NULL, NULL, EIO, (clock_t)0, NULL);
17342 		return;
17343 	}
17344 
17345 	/* Save the relevant sense info into the xp for the original cmd. */
17346 	xp->xb_sense_status = *((uchar_t *)(&(asp->sts_rqpkt_status)));
17347 	xp->xb_sense_state  = asp->sts_rqpkt_state;
17348 	xp->xb_sense_resid  = asp->sts_rqpkt_resid;
17349 	if (xp->xb_sense_state & STATE_XARQ_DONE) {
17350 		actual_len = MAX_SENSE_LENGTH - xp->xb_sense_resid;
17351 		bcopy(&asp->sts_sensedata, xp->xb_sense_data,
17352 		    MAX_SENSE_LENGTH);
17353 	} else {
17354 		if (xp->xb_sense_resid > SENSE_LENGTH) {
17355 			actual_len = MAX_SENSE_LENGTH - xp->xb_sense_resid;
17356 		} else {
17357 			actual_len = SENSE_LENGTH - xp->xb_sense_resid;
17358 		}
17359 		if (xp->xb_pkt_flags & SD_XB_USCSICMD) {
17360 			if ((((struct uscsi_cmd *)
17361 			    (xp->xb_pktinfo))->uscsi_rqlen) > actual_len) {
17362 				xp->xb_sense_resid = (((struct uscsi_cmd *)
17363 				    (xp->xb_pktinfo))->uscsi_rqlen) -
17364 				    actual_len;
17365 			} else {
17366 				xp->xb_sense_resid = 0;
17367 			}
17368 		}
17369 		bcopy(&asp->sts_sensedata, xp->xb_sense_data, SENSE_LENGTH);
17370 	}
17371 
17372 	/*
17373 	 * See if we have valid sense data, if so then turn it over to
17374 	 * sd_decode_sense() to figure out the right course of action.
17375 	 */
17376 	if (sd_validate_sense_data(un, bp, xp, actual_len) ==
17377 	    SD_SENSE_DATA_IS_VALID) {
17378 		sd_decode_sense(un, bp, xp, pktp);
17379 	}
17380 }
17381 
17382 
17383 /*
17384  *    Function: sd_print_sense_failed_msg
17385  *
17386  * Description: Print log message when RQS has failed.
17387  *
17388  *   Arguments: un - ptr to associated softstate
17389  *		bp - ptr to buf(9S) for the command
17390  *		arg - generic message string ptr
17391  *		code - SD_IMMEDIATE_RETRY_ISSUED, SD_DELAYED_RETRY_ISSUED,
17392  *			or SD_NO_RETRY_ISSUED
17393  *
17394  *     Context: May be called from interrupt context
17395  */
17396 
17397 static void
17398 sd_print_sense_failed_msg(struct sd_lun *un, struct buf *bp, void *arg,
17399 	int code)
17400 {
17401 	char	*msgp = arg;
17402 
17403 	ASSERT(un != NULL);
17404 	ASSERT(mutex_owned(SD_MUTEX(un)));
17405 	ASSERT(bp != NULL);
17406 
17407 	if ((code == SD_NO_RETRY_ISSUED) && (msgp != NULL)) {
17408 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN, msgp);
17409 	}
17410 }
17411 
17412 
17413 /*
17414  *    Function: sd_validate_sense_data
17415  *
17416  * Description: Check the given sense data for validity.
17417  *		If the sense data is not valid, the command will
17418  *		be either failed or retried!
17419  *
17420  * Return Code: SD_SENSE_DATA_IS_INVALID
17421  *		SD_SENSE_DATA_IS_VALID
17422  *
17423  *     Context: May be called from interrupt context
17424  */
17425 
17426 static int
17427 sd_validate_sense_data(struct sd_lun *un, struct buf *bp, struct sd_xbuf *xp,
17428 	size_t actual_len)
17429 {
17430 	struct scsi_extended_sense *esp;
17431 	struct	scsi_pkt *pktp;
17432 	char	*msgp = NULL;
17433 	sd_ssc_t *sscp;
17434 
17435 	ASSERT(un != NULL);
17436 	ASSERT(mutex_owned(SD_MUTEX(un)));
17437 	ASSERT(bp != NULL);
17438 	ASSERT(bp != un->un_rqs_bp);
17439 	ASSERT(xp != NULL);
17440 	ASSERT(un->un_fm_private != NULL);
17441 
17442 	pktp = SD_GET_PKTP(bp);
17443 	ASSERT(pktp != NULL);
17444 
17445 	sscp = &((struct sd_fm_internal *)(un->un_fm_private))->fm_ssc;
17446 	ASSERT(sscp != NULL);
17447 
17448 	/*
17449 	 * Check the status of the RQS command (auto or manual).
17450 	 */
17451 	switch (xp->xb_sense_status & STATUS_MASK) {
17452 	case STATUS_GOOD:
17453 		break;
17454 
17455 	case STATUS_RESERVATION_CONFLICT:
17456 		sd_pkt_status_reservation_conflict(un, bp, xp, pktp);
17457 		return (SD_SENSE_DATA_IS_INVALID);
17458 
17459 	case STATUS_BUSY:
17460 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
17461 		    "Busy Status on REQUEST SENSE\n");
17462 		sd_retry_command(un, bp, SD_RETRIES_BUSY, NULL,
17463 		    NULL, EIO, un->un_busy_timeout / 500, kstat_waitq_enter);
17464 		return (SD_SENSE_DATA_IS_INVALID);
17465 
17466 	case STATUS_QFULL:
17467 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
17468 		    "QFULL Status on REQUEST SENSE\n");
17469 		sd_retry_command(un, bp, SD_RETRIES_STANDARD, NULL,
17470 		    NULL, EIO, un->un_busy_timeout / 500, kstat_waitq_enter);
17471 		return (SD_SENSE_DATA_IS_INVALID);
17472 
17473 	case STATUS_CHECK:
17474 	case STATUS_TERMINATED:
17475 		msgp = "Check Condition on REQUEST SENSE\n";
17476 		goto sense_failed;
17477 
17478 	default:
17479 		msgp = "Not STATUS_GOOD on REQUEST_SENSE\n";
17480 		goto sense_failed;
17481 	}
17482 
17483 	/*
17484 	 * See if we got the minimum required amount of sense data.
17485 	 * Note: We are assuming the returned sense data is SENSE_LENGTH bytes
17486 	 * or less.
17487 	 */
17488 	if (((xp->xb_sense_state & STATE_XFERRED_DATA) == 0) ||
17489 	    (actual_len == 0)) {
17490 		msgp = "Request Sense couldn't get sense data\n";
17491 		goto sense_failed;
17492 	}
17493 
17494 	if (actual_len < SUN_MIN_SENSE_LENGTH) {
17495 		msgp = "Not enough sense information\n";
17496 		/* Mark the ssc_flags for detecting invalid sense data */
17497 		if (!(xp->xb_pkt_flags & SD_XB_USCSICMD)) {
17498 			sd_ssc_set_info(sscp, SSC_FLAGS_INVALID_SENSE, 0,
17499 			    "sense-data");
17500 		}
17501 		goto sense_failed;
17502 	}
17503 
17504 	/*
17505 	 * We require the extended sense data
17506 	 */
17507 	esp = (struct scsi_extended_sense *)xp->xb_sense_data;
17508 	if (esp->es_class != CLASS_EXTENDED_SENSE) {
17509 		if ((pktp->pkt_flags & FLAG_SILENT) == 0) {
17510 			static char tmp[8];
17511 			static char buf[148];
17512 			char *p = (char *)(xp->xb_sense_data);
17513 			int i;
17514 
17515 			mutex_enter(&sd_sense_mutex);
17516 			(void) strcpy(buf, "undecodable sense information:");
17517 			for (i = 0; i < actual_len; i++) {
17518 				(void) sprintf(tmp, " 0x%x", *(p++)&0xff);
17519 				(void) strcpy(&buf[strlen(buf)], tmp);
17520 			}
17521 			i = strlen(buf);
17522 			(void) strcpy(&buf[i], "-(assumed fatal)\n");
17523 
17524 			if (SD_FM_LOG(un) == SD_FM_LOG_NSUP) {
17525 				scsi_log(SD_DEVINFO(un), sd_label,
17526 				    CE_WARN, buf);
17527 			}
17528 			mutex_exit(&sd_sense_mutex);
17529 		}
17530 
17531 		/* Mark the ssc_flags for detecting invalid sense data */
17532 		if (!(xp->xb_pkt_flags & SD_XB_USCSICMD)) {
17533 			sd_ssc_set_info(sscp, SSC_FLAGS_INVALID_SENSE, 0,
17534 			    "sense-data");
17535 		}
17536 
17537 		/* Note: Legacy behavior, fail the command with no retry */
17538 		sd_return_failed_command(un, bp, EIO);
17539 		return (SD_SENSE_DATA_IS_INVALID);
17540 	}
17541 
17542 	/*
17543 	 * Check that es_code is valid (es_class concatenated with es_code
17544 	 * make up the "response code" field.  es_class will always be 7, so
17545 	 * make sure es_code is 0, 1, 2, 3 or 0xf.  es_code will indicate the
17546 	 * format.
17547 	 */
17548 	if ((esp->es_code != CODE_FMT_FIXED_CURRENT) &&
17549 	    (esp->es_code != CODE_FMT_FIXED_DEFERRED) &&
17550 	    (esp->es_code != CODE_FMT_DESCR_CURRENT) &&
17551 	    (esp->es_code != CODE_FMT_DESCR_DEFERRED) &&
17552 	    (esp->es_code != CODE_FMT_VENDOR_SPECIFIC)) {
17553 		/* Mark the ssc_flags for detecting invalid sense data */
17554 		if (!(xp->xb_pkt_flags & SD_XB_USCSICMD)) {
17555 			sd_ssc_set_info(sscp, SSC_FLAGS_INVALID_SENSE, 0,
17556 			    "sense-data");
17557 		}
17558 		goto sense_failed;
17559 	}
17560 
17561 	return (SD_SENSE_DATA_IS_VALID);
17562 
17563 sense_failed:
17564 	/*
17565 	 * If the request sense failed (for whatever reason), attempt
17566 	 * to retry the original command.
17567 	 */
17568 #if defined(__i386) || defined(__amd64)
17569 	/*
17570 	 * SD_RETRY_DELAY is conditionally compile (#if fibre) in
17571 	 * sddef.h for Sparc platform, and x86 uses 1 binary
17572 	 * for both SCSI/FC.
17573 	 * The SD_RETRY_DELAY value need to be adjusted here
17574 	 * when SD_RETRY_DELAY change in sddef.h
17575 	 */
17576 	sd_retry_command(un, bp, SD_RETRIES_STANDARD,
17577 	    sd_print_sense_failed_msg, msgp, EIO,
17578 	    un->un_f_is_fibre?drv_usectohz(100000):(clock_t)0, NULL);
17579 #else
17580 	sd_retry_command(un, bp, SD_RETRIES_STANDARD,
17581 	    sd_print_sense_failed_msg, msgp, EIO, SD_RETRY_DELAY, NULL);
17582 #endif
17583 
17584 	return (SD_SENSE_DATA_IS_INVALID);
17585 }
17586 
17587 /*
17588  *    Function: sd_decode_sense
17589  *
17590  * Description: Take recovery action(s) when SCSI Sense Data is received.
17591  *
17592  *     Context: Interrupt context.
17593  */
17594 
17595 static void
17596 sd_decode_sense(struct sd_lun *un, struct buf *bp, struct sd_xbuf *xp,
17597 	struct scsi_pkt *pktp)
17598 {
17599 	uint8_t sense_key;
17600 
17601 	ASSERT(un != NULL);
17602 	ASSERT(mutex_owned(SD_MUTEX(un)));
17603 	ASSERT(bp != NULL);
17604 	ASSERT(bp != un->un_rqs_bp);
17605 	ASSERT(xp != NULL);
17606 	ASSERT(pktp != NULL);
17607 
17608 	sense_key = scsi_sense_key(xp->xb_sense_data);
17609 
17610 	switch (sense_key) {
17611 	case KEY_NO_SENSE:
17612 		sd_sense_key_no_sense(un, bp, xp, pktp);
17613 		break;
17614 	case KEY_RECOVERABLE_ERROR:
17615 		sd_sense_key_recoverable_error(un, xp->xb_sense_data,
17616 		    bp, xp, pktp);
17617 		break;
17618 	case KEY_NOT_READY:
17619 		sd_sense_key_not_ready(un, xp->xb_sense_data,
17620 		    bp, xp, pktp);
17621 		break;
17622 	case KEY_MEDIUM_ERROR:
17623 	case KEY_HARDWARE_ERROR:
17624 		sd_sense_key_medium_or_hardware_error(un,
17625 		    xp->xb_sense_data, bp, xp, pktp);
17626 		break;
17627 	case KEY_ILLEGAL_REQUEST:
17628 		sd_sense_key_illegal_request(un, bp, xp, pktp);
17629 		break;
17630 	case KEY_UNIT_ATTENTION:
17631 		sd_sense_key_unit_attention(un, xp->xb_sense_data,
17632 		    bp, xp, pktp);
17633 		break;
17634 	case KEY_WRITE_PROTECT:
17635 	case KEY_VOLUME_OVERFLOW:
17636 	case KEY_MISCOMPARE:
17637 		sd_sense_key_fail_command(un, bp, xp, pktp);
17638 		break;
17639 	case KEY_BLANK_CHECK:
17640 		sd_sense_key_blank_check(un, bp, xp, pktp);
17641 		break;
17642 	case KEY_ABORTED_COMMAND:
17643 		sd_sense_key_aborted_command(un, bp, xp, pktp);
17644 		break;
17645 	case KEY_VENDOR_UNIQUE:
17646 	case KEY_COPY_ABORTED:
17647 	case KEY_EQUAL:
17648 	case KEY_RESERVED:
17649 	default:
17650 		sd_sense_key_default(un, xp->xb_sense_data,
17651 		    bp, xp, pktp);
17652 		break;
17653 	}
17654 }
17655 
17656 
17657 /*
17658  *    Function: sd_dump_memory
17659  *
17660  * Description: Debug logging routine to print the contents of a user provided
17661  *		buffer. The output of the buffer is broken up into 256 byte
17662  *		segments due to a size constraint of the scsi_log.
17663  *		implementation.
17664  *
17665  *   Arguments: un - ptr to softstate
17666  *		comp - component mask
17667  *		title - "title" string to preceed data when printed
17668  *		data - ptr to data block to be printed
17669  *		len - size of data block to be printed
17670  *		fmt - SD_LOG_HEX (use 0x%02x format) or SD_LOG_CHAR (use %c)
17671  *
17672  *     Context: May be called from interrupt context
17673  */
17674 
17675 #define	SD_DUMP_MEMORY_BUF_SIZE	256
17676 
17677 static char *sd_dump_format_string[] = {
17678 		" 0x%02x",
17679 		" %c"
17680 };
17681 
17682 static void
17683 sd_dump_memory(struct sd_lun *un, uint_t comp, char *title, uchar_t *data,
17684     int len, int fmt)
17685 {
17686 	int	i, j;
17687 	int	avail_count;
17688 	int	start_offset;
17689 	int	end_offset;
17690 	size_t	entry_len;
17691 	char	*bufp;
17692 	char	*local_buf;
17693 	char	*format_string;
17694 
17695 	ASSERT((fmt == SD_LOG_HEX) || (fmt == SD_LOG_CHAR));
17696 
17697 	/*
17698 	 * In the debug version of the driver, this function is called from a
17699 	 * number of places which are NOPs in the release driver.
17700 	 * The debug driver therefore has additional methods of filtering
17701 	 * debug output.
17702 	 */
17703 #ifdef SDDEBUG
17704 	/*
17705 	 * In the debug version of the driver we can reduce the amount of debug
17706 	 * messages by setting sd_error_level to something other than
17707 	 * SCSI_ERR_ALL and clearing bits in sd_level_mask and
17708 	 * sd_component_mask.
17709 	 */
17710 	if (((sd_level_mask & (SD_LOGMASK_DUMP_MEM | SD_LOGMASK_DIAG)) == 0) ||
17711 	    (sd_error_level != SCSI_ERR_ALL)) {
17712 		return;
17713 	}
17714 	if (((sd_component_mask & comp) == 0) ||
17715 	    (sd_error_level != SCSI_ERR_ALL)) {
17716 		return;
17717 	}
17718 #else
17719 	if (sd_error_level != SCSI_ERR_ALL) {
17720 		return;
17721 	}
17722 #endif
17723 
17724 	local_buf = kmem_zalloc(SD_DUMP_MEMORY_BUF_SIZE, KM_SLEEP);
17725 	bufp = local_buf;
17726 	/*
17727 	 * Available length is the length of local_buf[], minus the
17728 	 * length of the title string, minus one for the ":", minus
17729 	 * one for the newline, minus one for the NULL terminator.
17730 	 * This gives the #bytes available for holding the printed
17731 	 * values from the given data buffer.
17732 	 */
17733 	if (fmt == SD_LOG_HEX) {
17734 		format_string = sd_dump_format_string[0];
17735 	} else /* SD_LOG_CHAR */ {
17736 		format_string = sd_dump_format_string[1];
17737 	}
17738 	/*
17739 	 * Available count is the number of elements from the given
17740 	 * data buffer that we can fit into the available length.
17741 	 * This is based upon the size of the format string used.
17742 	 * Make one entry and find it's size.
17743 	 */
17744 	(void) sprintf(bufp, format_string, data[0]);
17745 	entry_len = strlen(bufp);
17746 	avail_count = (SD_DUMP_MEMORY_BUF_SIZE - strlen(title) - 3) / entry_len;
17747 
17748 	j = 0;
17749 	while (j < len) {
17750 		bufp = local_buf;
17751 		bzero(bufp, SD_DUMP_MEMORY_BUF_SIZE);
17752 		start_offset = j;
17753 
17754 		end_offset = start_offset + avail_count;
17755 
17756 		(void) sprintf(bufp, "%s:", title);
17757 		bufp += strlen(bufp);
17758 		for (i = start_offset; ((i < end_offset) && (j < len));
17759 		    i++, j++) {
17760 			(void) sprintf(bufp, format_string, data[i]);
17761 			bufp += entry_len;
17762 		}
17763 		(void) sprintf(bufp, "\n");
17764 
17765 		scsi_log(SD_DEVINFO(un), sd_label, CE_NOTE, "%s", local_buf);
17766 	}
17767 	kmem_free(local_buf, SD_DUMP_MEMORY_BUF_SIZE);
17768 }
17769 
17770 /*
17771  *    Function: sd_print_sense_msg
17772  *
17773  * Description: Log a message based upon the given sense data.
17774  *
17775  *   Arguments: un - ptr to associated softstate
17776  *		bp - ptr to buf(9S) for the command
17777  *		arg - ptr to associate sd_sense_info struct
17778  *		code - SD_IMMEDIATE_RETRY_ISSUED, SD_DELAYED_RETRY_ISSUED,
17779  *			or SD_NO_RETRY_ISSUED
17780  *
17781  *     Context: May be called from interrupt context
17782  */
17783 
17784 static void
17785 sd_print_sense_msg(struct sd_lun *un, struct buf *bp, void *arg, int code)
17786 {
17787 	struct sd_xbuf	*xp;
17788 	struct scsi_pkt	*pktp;
17789 	uint8_t *sensep;
17790 	daddr_t request_blkno;
17791 	diskaddr_t err_blkno;
17792 	int severity;
17793 	int pfa_flag;
17794 	extern struct scsi_key_strings scsi_cmds[];
17795 
17796 	ASSERT(un != NULL);
17797 	ASSERT(mutex_owned(SD_MUTEX(un)));
17798 	ASSERT(bp != NULL);
17799 	xp = SD_GET_XBUF(bp);
17800 	ASSERT(xp != NULL);
17801 	pktp = SD_GET_PKTP(bp);
17802 	ASSERT(pktp != NULL);
17803 	ASSERT(arg != NULL);
17804 
17805 	severity = ((struct sd_sense_info *)(arg))->ssi_severity;
17806 	pfa_flag = ((struct sd_sense_info *)(arg))->ssi_pfa_flag;
17807 
17808 	if ((code == SD_DELAYED_RETRY_ISSUED) ||
17809 	    (code == SD_IMMEDIATE_RETRY_ISSUED)) {
17810 		severity = SCSI_ERR_RETRYABLE;
17811 	}
17812 
17813 	/* Use absolute block number for the request block number */
17814 	request_blkno = xp->xb_blkno;
17815 
17816 	/*
17817 	 * Now try to get the error block number from the sense data
17818 	 */
17819 	sensep = xp->xb_sense_data;
17820 
17821 	if (scsi_sense_info_uint64(sensep, SENSE_LENGTH,
17822 	    (uint64_t *)&err_blkno)) {
17823 		/*
17824 		 * We retrieved the error block number from the information
17825 		 * portion of the sense data.
17826 		 *
17827 		 * For USCSI commands we are better off using the error
17828 		 * block no. as the requested block no. (This is the best
17829 		 * we can estimate.)
17830 		 */
17831 		if ((SD_IS_BUFIO(xp) == FALSE) &&
17832 		    ((pktp->pkt_flags & FLAG_SILENT) == 0)) {
17833 			request_blkno = err_blkno;
17834 		}
17835 	} else {
17836 		/*
17837 		 * Without the es_valid bit set (for fixed format) or an
17838 		 * information descriptor (for descriptor format) we cannot
17839 		 * be certain of the error blkno, so just use the
17840 		 * request_blkno.
17841 		 */
17842 		err_blkno = (diskaddr_t)request_blkno;
17843 	}
17844 
17845 	/*
17846 	 * The following will log the buffer contents for the release driver
17847 	 * if the SD_LOGMASK_DIAG bit of sd_level_mask is set, or the error
17848 	 * level is set to verbose.
17849 	 */
17850 	sd_dump_memory(un, SD_LOG_IO, "Failed CDB",
17851 	    (uchar_t *)pktp->pkt_cdbp, CDB_SIZE, SD_LOG_HEX);
17852 	sd_dump_memory(un, SD_LOG_IO, "Sense Data",
17853 	    (uchar_t *)sensep, SENSE_LENGTH, SD_LOG_HEX);
17854 
17855 	if (pfa_flag == FALSE) {
17856 		/* This is normally only set for USCSI */
17857 		if ((pktp->pkt_flags & FLAG_SILENT) != 0) {
17858 			return;
17859 		}
17860 
17861 		if ((SD_IS_BUFIO(xp) == TRUE) &&
17862 		    (((sd_level_mask & SD_LOGMASK_DIAG) == 0) &&
17863 		    (severity < sd_error_level))) {
17864 			return;
17865 		}
17866 	}
17867 	/*
17868 	 * Check for Sonoma Failover and keep a count of how many failed I/O's
17869 	 */
17870 	if ((SD_IS_LSI(un)) &&
17871 	    (scsi_sense_key(sensep) == KEY_ILLEGAL_REQUEST) &&
17872 	    (scsi_sense_asc(sensep) == 0x94) &&
17873 	    (scsi_sense_ascq(sensep) == 0x01)) {
17874 		un->un_sonoma_failure_count++;
17875 		if (un->un_sonoma_failure_count > 1) {
17876 			return;
17877 		}
17878 	}
17879 
17880 	if (SD_FM_LOG(un) == SD_FM_LOG_NSUP ||
17881 	    ((scsi_sense_key(sensep) == KEY_RECOVERABLE_ERROR) &&
17882 	    (pktp->pkt_resid == 0))) {
17883 		scsi_vu_errmsg(SD_SCSI_DEVP(un), pktp, sd_label, severity,
17884 		    request_blkno, err_blkno, scsi_cmds,
17885 		    (struct scsi_extended_sense *)sensep,
17886 		    un->un_additional_codes, NULL);
17887 	}
17888 }
17889 
17890 /*
17891  *    Function: sd_sense_key_no_sense
17892  *
17893  * Description: Recovery action when sense data was not received.
17894  *
17895  *     Context: May be called from interrupt context
17896  */
17897 
17898 static void
17899 sd_sense_key_no_sense(struct sd_lun *un, struct buf *bp,
17900 	struct sd_xbuf *xp, struct scsi_pkt *pktp)
17901 {
17902 	struct sd_sense_info	si;
17903 
17904 	ASSERT(un != NULL);
17905 	ASSERT(mutex_owned(SD_MUTEX(un)));
17906 	ASSERT(bp != NULL);
17907 	ASSERT(xp != NULL);
17908 	ASSERT(pktp != NULL);
17909 
17910 	si.ssi_severity = SCSI_ERR_FATAL;
17911 	si.ssi_pfa_flag = FALSE;
17912 
17913 	SD_UPDATE_ERRSTATS(un, sd_softerrs);
17914 
17915 	sd_retry_command(un, bp, SD_RETRIES_STANDARD, sd_print_sense_msg,
17916 	    &si, EIO, (clock_t)0, NULL);
17917 }
17918 
17919 
17920 /*
17921  *    Function: sd_sense_key_recoverable_error
17922  *
17923  * Description: Recovery actions for a SCSI "Recovered Error" sense key.
17924  *
17925  *     Context: May be called from interrupt context
17926  */
17927 
17928 static void
17929 sd_sense_key_recoverable_error(struct sd_lun *un,
17930 	uint8_t *sense_datap,
17931 	struct buf *bp, struct sd_xbuf *xp, struct scsi_pkt *pktp)
17932 {
17933 	struct sd_sense_info	si;
17934 	uint8_t asc = scsi_sense_asc(sense_datap);
17935 
17936 	ASSERT(un != NULL);
17937 	ASSERT(mutex_owned(SD_MUTEX(un)));
17938 	ASSERT(bp != NULL);
17939 	ASSERT(xp != NULL);
17940 	ASSERT(pktp != NULL);
17941 
17942 	/*
17943 	 * 0x5D: FAILURE PREDICTION THRESHOLD EXCEEDED
17944 	 */
17945 	if ((asc == 0x5D) && (sd_report_pfa != 0)) {
17946 		SD_UPDATE_ERRSTATS(un, sd_rq_pfa_err);
17947 		si.ssi_severity = SCSI_ERR_INFO;
17948 		si.ssi_pfa_flag = TRUE;
17949 	} else {
17950 		SD_UPDATE_ERRSTATS(un, sd_softerrs);
17951 		SD_UPDATE_ERRSTATS(un, sd_rq_recov_err);
17952 		si.ssi_severity = SCSI_ERR_RECOVERED;
17953 		si.ssi_pfa_flag = FALSE;
17954 	}
17955 
17956 	if (pktp->pkt_resid == 0) {
17957 		sd_print_sense_msg(un, bp, &si, SD_NO_RETRY_ISSUED);
17958 		sd_return_command(un, bp);
17959 		return;
17960 	}
17961 
17962 	sd_retry_command(un, bp, SD_RETRIES_STANDARD, sd_print_sense_msg,
17963 	    &si, EIO, (clock_t)0, NULL);
17964 }
17965 
17966 
17967 
17968 
17969 /*
17970  *    Function: sd_sense_key_not_ready
17971  *
17972  * Description: Recovery actions for a SCSI "Not Ready" sense key.
17973  *
17974  *     Context: May be called from interrupt context
17975  */
17976 
17977 static void
17978 sd_sense_key_not_ready(struct sd_lun *un,
17979 	uint8_t *sense_datap,
17980 	struct buf *bp, struct sd_xbuf *xp, struct scsi_pkt *pktp)
17981 {
17982 	struct sd_sense_info	si;
17983 	uint8_t asc = scsi_sense_asc(sense_datap);
17984 	uint8_t ascq = scsi_sense_ascq(sense_datap);
17985 
17986 	ASSERT(un != NULL);
17987 	ASSERT(mutex_owned(SD_MUTEX(un)));
17988 	ASSERT(bp != NULL);
17989 	ASSERT(xp != NULL);
17990 	ASSERT(pktp != NULL);
17991 
17992 	si.ssi_severity = SCSI_ERR_FATAL;
17993 	si.ssi_pfa_flag = FALSE;
17994 
17995 	/*
17996 	 * Update error stats after first NOT READY error. Disks may have
17997 	 * been powered down and may need to be restarted.  For CDROMs,
17998 	 * report NOT READY errors only if media is present.
17999 	 */
18000 	if ((ISCD(un) && (asc == 0x3A)) ||
18001 	    (xp->xb_nr_retry_count > 0)) {
18002 		SD_UPDATE_ERRSTATS(un, sd_harderrs);
18003 		SD_UPDATE_ERRSTATS(un, sd_rq_ntrdy_err);
18004 	}
18005 
18006 	/*
18007 	 * Just fail if the "not ready" retry limit has been reached.
18008 	 */
18009 	if (xp->xb_nr_retry_count >= un->un_notready_retry_count) {
18010 		/* Special check for error message printing for removables. */
18011 		if (un->un_f_has_removable_media && (asc == 0x04) &&
18012 		    (ascq >= 0x04)) {
18013 			si.ssi_severity = SCSI_ERR_ALL;
18014 		}
18015 		goto fail_command;
18016 	}
18017 
18018 	/*
18019 	 * Check the ASC and ASCQ in the sense data as needed, to determine
18020 	 * what to do.
18021 	 */
18022 	switch (asc) {
18023 	case 0x04:	/* LOGICAL UNIT NOT READY */
18024 		/*
18025 		 * disk drives that don't spin up result in a very long delay
18026 		 * in format without warning messages. We will log a message
18027 		 * if the error level is set to verbose.
18028 		 */
18029 		if (sd_error_level < SCSI_ERR_RETRYABLE) {
18030 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
18031 			    "logical unit not ready, resetting disk\n");
18032 		}
18033 
18034 		/*
18035 		 * There are different requirements for CDROMs and disks for
18036 		 * the number of retries.  If a CD-ROM is giving this, it is
18037 		 * probably reading TOC and is in the process of getting
18038 		 * ready, so we should keep on trying for a long time to make
18039 		 * sure that all types of media are taken in account (for
18040 		 * some media the drive takes a long time to read TOC).  For
18041 		 * disks we do not want to retry this too many times as this
18042 		 * can cause a long hang in format when the drive refuses to
18043 		 * spin up (a very common failure).
18044 		 */
18045 		switch (ascq) {
18046 		case 0x00:  /* LUN NOT READY, CAUSE NOT REPORTABLE */
18047 			/*
18048 			 * Disk drives frequently refuse to spin up which
18049 			 * results in a very long hang in format without
18050 			 * warning messages.
18051 			 *
18052 			 * Note: This code preserves the legacy behavior of
18053 			 * comparing xb_nr_retry_count against zero for fibre
18054 			 * channel targets instead of comparing against the
18055 			 * un_reset_retry_count value.  The reason for this
18056 			 * discrepancy has been so utterly lost beneath the
18057 			 * Sands of Time that even Indiana Jones could not
18058 			 * find it.
18059 			 */
18060 			if (un->un_f_is_fibre == TRUE) {
18061 				if (((sd_level_mask & SD_LOGMASK_DIAG) ||
18062 				    (xp->xb_nr_retry_count > 0)) &&
18063 				    (un->un_startstop_timeid == NULL)) {
18064 					scsi_log(SD_DEVINFO(un), sd_label,
18065 					    CE_WARN, "logical unit not ready, "
18066 					    "resetting disk\n");
18067 					sd_reset_target(un, pktp);
18068 				}
18069 			} else {
18070 				if (((sd_level_mask & SD_LOGMASK_DIAG) ||
18071 				    (xp->xb_nr_retry_count >
18072 				    un->un_reset_retry_count)) &&
18073 				    (un->un_startstop_timeid == NULL)) {
18074 					scsi_log(SD_DEVINFO(un), sd_label,
18075 					    CE_WARN, "logical unit not ready, "
18076 					    "resetting disk\n");
18077 					sd_reset_target(un, pktp);
18078 				}
18079 			}
18080 			break;
18081 
18082 		case 0x01:  /* LUN IS IN PROCESS OF BECOMING READY */
18083 			/*
18084 			 * If the target is in the process of becoming
18085 			 * ready, just proceed with the retry. This can
18086 			 * happen with CD-ROMs that take a long time to
18087 			 * read TOC after a power cycle or reset.
18088 			 */
18089 			goto do_retry;
18090 
18091 		case 0x02:  /* LUN NOT READY, INITITIALIZING CMD REQUIRED */
18092 			break;
18093 
18094 		case 0x03:  /* LUN NOT READY, MANUAL INTERVENTION REQUIRED */
18095 			/*
18096 			 * Retries cannot help here so just fail right away.
18097 			 */
18098 			goto fail_command;
18099 
18100 		case 0x88:
18101 			/*
18102 			 * Vendor-unique code for T3/T4: it indicates a
18103 			 * path problem in a mutipathed config, but as far as
18104 			 * the target driver is concerned it equates to a fatal
18105 			 * error, so we should just fail the command right away
18106 			 * (without printing anything to the console). If this
18107 			 * is not a T3/T4, fall thru to the default recovery
18108 			 * action.
18109 			 * T3/T4 is FC only, don't need to check is_fibre
18110 			 */
18111 			if (SD_IS_T3(un) || SD_IS_T4(un)) {
18112 				sd_return_failed_command(un, bp, EIO);
18113 				return;
18114 			}
18115 			/* FALLTHRU */
18116 
18117 		case 0x04:  /* LUN NOT READY, FORMAT IN PROGRESS */
18118 		case 0x05:  /* LUN NOT READY, REBUILD IN PROGRESS */
18119 		case 0x06:  /* LUN NOT READY, RECALCULATION IN PROGRESS */
18120 		case 0x07:  /* LUN NOT READY, OPERATION IN PROGRESS */
18121 		case 0x08:  /* LUN NOT READY, LONG WRITE IN PROGRESS */
18122 		default:    /* Possible future codes in SCSI spec? */
18123 			/*
18124 			 * For removable-media devices, do not retry if
18125 			 * ASCQ > 2 as these result mostly from USCSI commands
18126 			 * on MMC devices issued to check status of an
18127 			 * operation initiated in immediate mode.  Also for
18128 			 * ASCQ >= 4 do not print console messages as these
18129 			 * mainly represent a user-initiated operation
18130 			 * instead of a system failure.
18131 			 */
18132 			if (un->un_f_has_removable_media) {
18133 				si.ssi_severity = SCSI_ERR_ALL;
18134 				goto fail_command;
18135 			}
18136 			break;
18137 		}
18138 
18139 		/*
18140 		 * As part of our recovery attempt for the NOT READY
18141 		 * condition, we issue a START STOP UNIT command. However
18142 		 * we want to wait for a short delay before attempting this
18143 		 * as there may still be more commands coming back from the
18144 		 * target with the check condition. To do this we use
18145 		 * timeout(9F) to call sd_start_stop_unit_callback() after
18146 		 * the delay interval expires. (sd_start_stop_unit_callback()
18147 		 * dispatches sd_start_stop_unit_task(), which will issue
18148 		 * the actual START STOP UNIT command. The delay interval
18149 		 * is one-half of the delay that we will use to retry the
18150 		 * command that generated the NOT READY condition.
18151 		 *
18152 		 * Note that we could just dispatch sd_start_stop_unit_task()
18153 		 * from here and allow it to sleep for the delay interval,
18154 		 * but then we would be tying up the taskq thread
18155 		 * uncesessarily for the duration of the delay.
18156 		 *
18157 		 * Do not issue the START STOP UNIT if the current command
18158 		 * is already a START STOP UNIT.
18159 		 */
18160 		if (pktp->pkt_cdbp[0] == SCMD_START_STOP) {
18161 			break;
18162 		}
18163 
18164 		/*
18165 		 * Do not schedule the timeout if one is already pending.
18166 		 */
18167 		if (un->un_startstop_timeid != NULL) {
18168 			SD_INFO(SD_LOG_ERROR, un,
18169 			    "sd_sense_key_not_ready: restart already issued to"
18170 			    " %s%d\n", ddi_driver_name(SD_DEVINFO(un)),
18171 			    ddi_get_instance(SD_DEVINFO(un)));
18172 			break;
18173 		}
18174 
18175 		/*
18176 		 * Schedule the START STOP UNIT command, then queue the command
18177 		 * for a retry.
18178 		 *
18179 		 * Note: A timeout is not scheduled for this retry because we
18180 		 * want the retry to be serial with the START_STOP_UNIT. The
18181 		 * retry will be started when the START_STOP_UNIT is completed
18182 		 * in sd_start_stop_unit_task.
18183 		 */
18184 		un->un_startstop_timeid = timeout(sd_start_stop_unit_callback,
18185 		    un, un->un_busy_timeout / 2);
18186 		xp->xb_nr_retry_count++;
18187 		sd_set_retry_bp(un, bp, 0, kstat_waitq_enter);
18188 		return;
18189 
18190 	case 0x05:	/* LOGICAL UNIT DOES NOT RESPOND TO SELECTION */
18191 		if (sd_error_level < SCSI_ERR_RETRYABLE) {
18192 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
18193 			    "unit does not respond to selection\n");
18194 		}
18195 		break;
18196 
18197 	case 0x3A:	/* MEDIUM NOT PRESENT */
18198 		if (sd_error_level >= SCSI_ERR_FATAL) {
18199 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
18200 			    "Caddy not inserted in drive\n");
18201 		}
18202 
18203 		sr_ejected(un);
18204 		un->un_mediastate = DKIO_EJECTED;
18205 		/* The state has changed, inform the media watch routines */
18206 		cv_broadcast(&un->un_state_cv);
18207 		/* Just fail if no media is present in the drive. */
18208 		goto fail_command;
18209 
18210 	default:
18211 		if (sd_error_level < SCSI_ERR_RETRYABLE) {
18212 			scsi_log(SD_DEVINFO(un), sd_label, CE_NOTE,
18213 			    "Unit not Ready. Additional sense code 0x%x\n",
18214 			    asc);
18215 		}
18216 		break;
18217 	}
18218 
18219 do_retry:
18220 
18221 	/*
18222 	 * Retry the command, as some targets may report NOT READY for
18223 	 * several seconds after being reset.
18224 	 */
18225 	xp->xb_nr_retry_count++;
18226 	si.ssi_severity = SCSI_ERR_RETRYABLE;
18227 	sd_retry_command(un, bp, SD_RETRIES_NOCHECK, sd_print_sense_msg,
18228 	    &si, EIO, un->un_busy_timeout, NULL);
18229 
18230 	return;
18231 
18232 fail_command:
18233 	sd_print_sense_msg(un, bp, &si, SD_NO_RETRY_ISSUED);
18234 	sd_return_failed_command(un, bp, EIO);
18235 }
18236 
18237 
18238 
18239 /*
18240  *    Function: sd_sense_key_medium_or_hardware_error
18241  *
18242  * Description: Recovery actions for a SCSI "Medium Error" or "Hardware Error"
18243  *		sense key.
18244  *
18245  *     Context: May be called from interrupt context
18246  */
18247 
18248 static void
18249 sd_sense_key_medium_or_hardware_error(struct sd_lun *un,
18250 	uint8_t *sense_datap,
18251 	struct buf *bp, struct sd_xbuf *xp, struct scsi_pkt *pktp)
18252 {
18253 	struct sd_sense_info	si;
18254 	uint8_t sense_key = scsi_sense_key(sense_datap);
18255 	uint8_t asc = scsi_sense_asc(sense_datap);
18256 
18257 	ASSERT(un != NULL);
18258 	ASSERT(mutex_owned(SD_MUTEX(un)));
18259 	ASSERT(bp != NULL);
18260 	ASSERT(xp != NULL);
18261 	ASSERT(pktp != NULL);
18262 
18263 	si.ssi_severity = SCSI_ERR_FATAL;
18264 	si.ssi_pfa_flag = FALSE;
18265 
18266 	if (sense_key == KEY_MEDIUM_ERROR) {
18267 		SD_UPDATE_ERRSTATS(un, sd_rq_media_err);
18268 	}
18269 
18270 	SD_UPDATE_ERRSTATS(un, sd_harderrs);
18271 
18272 	if ((un->un_reset_retry_count != 0) &&
18273 	    (xp->xb_retry_count == un->un_reset_retry_count)) {
18274 		mutex_exit(SD_MUTEX(un));
18275 		/* Do NOT do a RESET_ALL here: too intrusive. (4112858) */
18276 		if (un->un_f_allow_bus_device_reset == TRUE) {
18277 
18278 			boolean_t try_resetting_target = B_TRUE;
18279 
18280 			/*
18281 			 * We need to be able to handle specific ASC when we are
18282 			 * handling a KEY_HARDWARE_ERROR. In particular
18283 			 * taking the default action of resetting the target may
18284 			 * not be the appropriate way to attempt recovery.
18285 			 * Resetting a target because of a single LUN failure
18286 			 * victimizes all LUNs on that target.
18287 			 *
18288 			 * This is true for the LSI arrays, if an LSI
18289 			 * array controller returns an ASC of 0x84 (LUN Dead) we
18290 			 * should trust it.
18291 			 */
18292 
18293 			if (sense_key == KEY_HARDWARE_ERROR) {
18294 				switch (asc) {
18295 				case 0x84:
18296 					if (SD_IS_LSI(un)) {
18297 						try_resetting_target = B_FALSE;
18298 					}
18299 					break;
18300 				default:
18301 					break;
18302 				}
18303 			}
18304 
18305 			if (try_resetting_target == B_TRUE) {
18306 				int reset_retval = 0;
18307 				if (un->un_f_lun_reset_enabled == TRUE) {
18308 					SD_TRACE(SD_LOG_IO_CORE, un,
18309 					    "sd_sense_key_medium_or_hardware_"
18310 					    "error: issuing RESET_LUN\n");
18311 					reset_retval =
18312 					    scsi_reset(SD_ADDRESS(un),
18313 					    RESET_LUN);
18314 				}
18315 				if (reset_retval == 0) {
18316 					SD_TRACE(SD_LOG_IO_CORE, un,
18317 					    "sd_sense_key_medium_or_hardware_"
18318 					    "error: issuing RESET_TARGET\n");
18319 					(void) scsi_reset(SD_ADDRESS(un),
18320 					    RESET_TARGET);
18321 				}
18322 			}
18323 		}
18324 		mutex_enter(SD_MUTEX(un));
18325 	}
18326 
18327 	/*
18328 	 * This really ought to be a fatal error, but we will retry anyway
18329 	 * as some drives report this as a spurious error.
18330 	 */
18331 	sd_retry_command(un, bp, SD_RETRIES_STANDARD, sd_print_sense_msg,
18332 	    &si, EIO, (clock_t)0, NULL);
18333 }
18334 
18335 
18336 
18337 /*
18338  *    Function: sd_sense_key_illegal_request
18339  *
18340  * Description: Recovery actions for a SCSI "Illegal Request" sense key.
18341  *
18342  *     Context: May be called from interrupt context
18343  */
18344 
18345 static void
18346 sd_sense_key_illegal_request(struct sd_lun *un, struct buf *bp,
18347 	struct sd_xbuf *xp, struct scsi_pkt *pktp)
18348 {
18349 	struct sd_sense_info	si;
18350 
18351 	ASSERT(un != NULL);
18352 	ASSERT(mutex_owned(SD_MUTEX(un)));
18353 	ASSERT(bp != NULL);
18354 	ASSERT(xp != NULL);
18355 	ASSERT(pktp != NULL);
18356 
18357 	SD_UPDATE_ERRSTATS(un, sd_rq_illrq_err);
18358 
18359 	si.ssi_severity = SCSI_ERR_INFO;
18360 	si.ssi_pfa_flag = FALSE;
18361 
18362 	/* Pointless to retry if the target thinks it's an illegal request */
18363 	sd_print_sense_msg(un, bp, &si, SD_NO_RETRY_ISSUED);
18364 	sd_return_failed_command(un, bp, EIO);
18365 }
18366 
18367 
18368 
18369 
18370 /*
18371  *    Function: sd_sense_key_unit_attention
18372  *
18373  * Description: Recovery actions for a SCSI "Unit Attention" sense key.
18374  *
18375  *     Context: May be called from interrupt context
18376  */
18377 
18378 static void
18379 sd_sense_key_unit_attention(struct sd_lun *un,
18380 	uint8_t *sense_datap,
18381 	struct buf *bp, struct sd_xbuf *xp, struct scsi_pkt *pktp)
18382 {
18383 	/*
18384 	 * For UNIT ATTENTION we allow retries for one minute. Devices
18385 	 * like Sonoma can return UNIT ATTENTION close to a minute
18386 	 * under certain conditions.
18387 	 */
18388 	int	retry_check_flag = SD_RETRIES_UA;
18389 	boolean_t	kstat_updated = B_FALSE;
18390 	struct	sd_sense_info		si;
18391 	uint8_t asc = scsi_sense_asc(sense_datap);
18392 	uint8_t	ascq = scsi_sense_ascq(sense_datap);
18393 
18394 	ASSERT(un != NULL);
18395 	ASSERT(mutex_owned(SD_MUTEX(un)));
18396 	ASSERT(bp != NULL);
18397 	ASSERT(xp != NULL);
18398 	ASSERT(pktp != NULL);
18399 
18400 	si.ssi_severity = SCSI_ERR_INFO;
18401 	si.ssi_pfa_flag = FALSE;
18402 
18403 
18404 	switch (asc) {
18405 	case 0x5D:  /* FAILURE PREDICTION THRESHOLD EXCEEDED */
18406 		if (sd_report_pfa != 0) {
18407 			SD_UPDATE_ERRSTATS(un, sd_rq_pfa_err);
18408 			si.ssi_pfa_flag = TRUE;
18409 			retry_check_flag = SD_RETRIES_STANDARD;
18410 			goto do_retry;
18411 		}
18412 
18413 		break;
18414 
18415 	case 0x29:  /* POWER ON, RESET, OR BUS DEVICE RESET OCCURRED */
18416 		if ((un->un_resvd_status & SD_RESERVE) == SD_RESERVE) {
18417 			un->un_resvd_status |=
18418 			    (SD_LOST_RESERVE | SD_WANT_RESERVE);
18419 		}
18420 #ifdef _LP64
18421 		if (un->un_blockcount + 1 > SD_GROUP1_MAX_ADDRESS) {
18422 			if (taskq_dispatch(sd_tq, sd_reenable_dsense_task,
18423 			    un, KM_NOSLEEP) == 0) {
18424 				/*
18425 				 * If we can't dispatch the task we'll just
18426 				 * live without descriptor sense.  We can
18427 				 * try again on the next "unit attention"
18428 				 */
18429 				SD_ERROR(SD_LOG_ERROR, un,
18430 				    "sd_sense_key_unit_attention: "
18431 				    "Could not dispatch "
18432 				    "sd_reenable_dsense_task\n");
18433 			}
18434 		}
18435 #endif /* _LP64 */
18436 		/* FALLTHRU */
18437 
18438 	case 0x28: /* NOT READY TO READY CHANGE, MEDIUM MAY HAVE CHANGED */
18439 		if (!un->un_f_has_removable_media) {
18440 			break;
18441 		}
18442 
18443 		/*
18444 		 * When we get a unit attention from a removable-media device,
18445 		 * it may be in a state that will take a long time to recover
18446 		 * (e.g., from a reset).  Since we are executing in interrupt
18447 		 * context here, we cannot wait around for the device to come
18448 		 * back. So hand this command off to sd_media_change_task()
18449 		 * for deferred processing under taskq thread context. (Note
18450 		 * that the command still may be failed if a problem is
18451 		 * encountered at a later time.)
18452 		 */
18453 		if (taskq_dispatch(sd_tq, sd_media_change_task, pktp,
18454 		    KM_NOSLEEP) == 0) {
18455 			/*
18456 			 * Cannot dispatch the request so fail the command.
18457 			 */
18458 			SD_UPDATE_ERRSTATS(un, sd_harderrs);
18459 			SD_UPDATE_ERRSTATS(un, sd_rq_nodev_err);
18460 			si.ssi_severity = SCSI_ERR_FATAL;
18461 			sd_print_sense_msg(un, bp, &si, SD_NO_RETRY_ISSUED);
18462 			sd_return_failed_command(un, bp, EIO);
18463 		}
18464 
18465 		/*
18466 		 * If failed to dispatch sd_media_change_task(), we already
18467 		 * updated kstat. If succeed to dispatch sd_media_change_task(),
18468 		 * we should update kstat later if it encounters an error. So,
18469 		 * we update kstat_updated flag here.
18470 		 */
18471 		kstat_updated = B_TRUE;
18472 
18473 		/*
18474 		 * Either the command has been successfully dispatched to a
18475 		 * task Q for retrying, or the dispatch failed. In either case
18476 		 * do NOT retry again by calling sd_retry_command. This sets up
18477 		 * two retries of the same command and when one completes and
18478 		 * frees the resources the other will access freed memory,
18479 		 * a bad thing.
18480 		 */
18481 		return;
18482 
18483 	default:
18484 		break;
18485 	}
18486 
18487 	/*
18488 	 * ASC  ASCQ
18489 	 *  2A   09	Capacity data has changed
18490 	 *  2A   01	Mode parameters changed
18491 	 *  3F   0E	Reported luns data has changed
18492 	 * Arrays that support logical unit expansion should report
18493 	 * capacity changes(2Ah/09). Mode parameters changed and
18494 	 * reported luns data has changed are the approximation.
18495 	 */
18496 	if (((asc == 0x2a) && (ascq == 0x09)) ||
18497 	    ((asc == 0x2a) && (ascq == 0x01)) ||
18498 	    ((asc == 0x3f) && (ascq == 0x0e))) {
18499 		if (taskq_dispatch(sd_tq, sd_target_change_task, un,
18500 		    KM_NOSLEEP) == 0) {
18501 			SD_ERROR(SD_LOG_ERROR, un,
18502 			    "sd_sense_key_unit_attention: "
18503 			    "Could not dispatch sd_target_change_task\n");
18504 		}
18505 	}
18506 
18507 	/*
18508 	 * Update kstat if we haven't done that.
18509 	 */
18510 	if (!kstat_updated) {
18511 		SD_UPDATE_ERRSTATS(un, sd_harderrs);
18512 		SD_UPDATE_ERRSTATS(un, sd_rq_nodev_err);
18513 	}
18514 
18515 do_retry:
18516 	sd_retry_command(un, bp, retry_check_flag, sd_print_sense_msg, &si,
18517 	    EIO, SD_UA_RETRY_DELAY, NULL);
18518 }
18519 
18520 
18521 
18522 /*
18523  *    Function: sd_sense_key_fail_command
18524  *
18525  * Description: Use to fail a command when we don't like the sense key that
18526  *		was returned.
18527  *
18528  *     Context: May be called from interrupt context
18529  */
18530 
18531 static void
18532 sd_sense_key_fail_command(struct sd_lun *un, struct buf *bp,
18533 	struct sd_xbuf *xp, struct scsi_pkt *pktp)
18534 {
18535 	struct sd_sense_info	si;
18536 
18537 	ASSERT(un != NULL);
18538 	ASSERT(mutex_owned(SD_MUTEX(un)));
18539 	ASSERT(bp != NULL);
18540 	ASSERT(xp != NULL);
18541 	ASSERT(pktp != NULL);
18542 
18543 	si.ssi_severity = SCSI_ERR_FATAL;
18544 	si.ssi_pfa_flag = FALSE;
18545 
18546 	sd_print_sense_msg(un, bp, &si, SD_NO_RETRY_ISSUED);
18547 	sd_return_failed_command(un, bp, EIO);
18548 }
18549 
18550 
18551 
18552 /*
18553  *    Function: sd_sense_key_blank_check
18554  *
18555  * Description: Recovery actions for a SCSI "Blank Check" sense key.
18556  *		Has no monetary connotation.
18557  *
18558  *     Context: May be called from interrupt context
18559  */
18560 
18561 static void
18562 sd_sense_key_blank_check(struct sd_lun *un, struct buf *bp,
18563 	struct sd_xbuf *xp, struct scsi_pkt *pktp)
18564 {
18565 	struct sd_sense_info	si;
18566 
18567 	ASSERT(un != NULL);
18568 	ASSERT(mutex_owned(SD_MUTEX(un)));
18569 	ASSERT(bp != NULL);
18570 	ASSERT(xp != NULL);
18571 	ASSERT(pktp != NULL);
18572 
18573 	/*
18574 	 * Blank check is not fatal for removable devices, therefore
18575 	 * it does not require a console message.
18576 	 */
18577 	si.ssi_severity = (un->un_f_has_removable_media) ? SCSI_ERR_ALL :
18578 	    SCSI_ERR_FATAL;
18579 	si.ssi_pfa_flag = FALSE;
18580 
18581 	sd_print_sense_msg(un, bp, &si, SD_NO_RETRY_ISSUED);
18582 	sd_return_failed_command(un, bp, EIO);
18583 }
18584 
18585 
18586 
18587 
18588 /*
18589  *    Function: sd_sense_key_aborted_command
18590  *
18591  * Description: Recovery actions for a SCSI "Aborted Command" sense key.
18592  *
18593  *     Context: May be called from interrupt context
18594  */
18595 
18596 static void
18597 sd_sense_key_aborted_command(struct sd_lun *un, struct buf *bp,
18598 	struct sd_xbuf *xp, struct scsi_pkt *pktp)
18599 {
18600 	struct sd_sense_info	si;
18601 
18602 	ASSERT(un != NULL);
18603 	ASSERT(mutex_owned(SD_MUTEX(un)));
18604 	ASSERT(bp != NULL);
18605 	ASSERT(xp != NULL);
18606 	ASSERT(pktp != NULL);
18607 
18608 	si.ssi_severity = SCSI_ERR_FATAL;
18609 	si.ssi_pfa_flag = FALSE;
18610 
18611 	SD_UPDATE_ERRSTATS(un, sd_harderrs);
18612 
18613 	/*
18614 	 * This really ought to be a fatal error, but we will retry anyway
18615 	 * as some drives report this as a spurious error.
18616 	 */
18617 	sd_retry_command(un, bp, SD_RETRIES_STANDARD, sd_print_sense_msg,
18618 	    &si, EIO, drv_usectohz(100000), NULL);
18619 }
18620 
18621 
18622 
18623 /*
18624  *    Function: sd_sense_key_default
18625  *
18626  * Description: Default recovery action for several SCSI sense keys (basically
18627  *		attempts a retry).
18628  *
18629  *     Context: May be called from interrupt context
18630  */
18631 
18632 static void
18633 sd_sense_key_default(struct sd_lun *un,
18634 	uint8_t *sense_datap,
18635 	struct buf *bp, struct sd_xbuf *xp, struct scsi_pkt *pktp)
18636 {
18637 	struct sd_sense_info	si;
18638 	uint8_t sense_key = scsi_sense_key(sense_datap);
18639 
18640 	ASSERT(un != NULL);
18641 	ASSERT(mutex_owned(SD_MUTEX(un)));
18642 	ASSERT(bp != NULL);
18643 	ASSERT(xp != NULL);
18644 	ASSERT(pktp != NULL);
18645 
18646 	SD_UPDATE_ERRSTATS(un, sd_harderrs);
18647 
18648 	/*
18649 	 * Undecoded sense key.	Attempt retries and hope that will fix
18650 	 * the problem.  Otherwise, we're dead.
18651 	 */
18652 	if ((pktp->pkt_flags & FLAG_SILENT) == 0) {
18653 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
18654 		    "Unhandled Sense Key '%s'\n", sense_keys[sense_key]);
18655 	}
18656 
18657 	si.ssi_severity = SCSI_ERR_FATAL;
18658 	si.ssi_pfa_flag = FALSE;
18659 
18660 	sd_retry_command(un, bp, SD_RETRIES_STANDARD, sd_print_sense_msg,
18661 	    &si, EIO, (clock_t)0, NULL);
18662 }
18663 
18664 
18665 
18666 /*
18667  *    Function: sd_print_retry_msg
18668  *
18669  * Description: Print a message indicating the retry action being taken.
18670  *
18671  *   Arguments: un - ptr to associated softstate
18672  *		bp - ptr to buf(9S) for the command
18673  *		arg - not used.
18674  *		flag - SD_IMMEDIATE_RETRY_ISSUED, SD_DELAYED_RETRY_ISSUED,
18675  *			or SD_NO_RETRY_ISSUED
18676  *
18677  *     Context: May be called from interrupt context
18678  */
18679 /* ARGSUSED */
18680 static void
18681 sd_print_retry_msg(struct sd_lun *un, struct buf *bp, void *arg, int flag)
18682 {
18683 	struct sd_xbuf	*xp;
18684 	struct scsi_pkt *pktp;
18685 	char *reasonp;
18686 	char *msgp;
18687 
18688 	ASSERT(un != NULL);
18689 	ASSERT(mutex_owned(SD_MUTEX(un)));
18690 	ASSERT(bp != NULL);
18691 	pktp = SD_GET_PKTP(bp);
18692 	ASSERT(pktp != NULL);
18693 	xp = SD_GET_XBUF(bp);
18694 	ASSERT(xp != NULL);
18695 
18696 	ASSERT(!mutex_owned(&un->un_pm_mutex));
18697 	mutex_enter(&un->un_pm_mutex);
18698 	if ((un->un_state == SD_STATE_SUSPENDED) ||
18699 	    (SD_DEVICE_IS_IN_LOW_POWER(un)) ||
18700 	    (pktp->pkt_flags & FLAG_SILENT)) {
18701 		mutex_exit(&un->un_pm_mutex);
18702 		goto update_pkt_reason;
18703 	}
18704 	mutex_exit(&un->un_pm_mutex);
18705 
18706 	/*
18707 	 * Suppress messages if they are all the same pkt_reason; with
18708 	 * TQ, many (up to 256) are returned with the same pkt_reason.
18709 	 * If we are in panic, then suppress the retry messages.
18710 	 */
18711 	switch (flag) {
18712 	case SD_NO_RETRY_ISSUED:
18713 		msgp = "giving up";
18714 		break;
18715 	case SD_IMMEDIATE_RETRY_ISSUED:
18716 	case SD_DELAYED_RETRY_ISSUED:
18717 		if (ddi_in_panic() || (un->un_state == SD_STATE_OFFLINE) ||
18718 		    ((pktp->pkt_reason == un->un_last_pkt_reason) &&
18719 		    (sd_error_level != SCSI_ERR_ALL))) {
18720 			return;
18721 		}
18722 		msgp = "retrying command";
18723 		break;
18724 	default:
18725 		goto update_pkt_reason;
18726 	}
18727 
18728 	reasonp = (((pktp->pkt_statistics & STAT_PERR) != 0) ? "parity error" :
18729 	    scsi_rname(pktp->pkt_reason));
18730 
18731 	if (SD_FM_LOG(un) == SD_FM_LOG_NSUP) {
18732 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
18733 		    "SCSI transport failed: reason '%s': %s\n", reasonp, msgp);
18734 	}
18735 
18736 update_pkt_reason:
18737 	/*
18738 	 * Update un->un_last_pkt_reason with the value in pktp->pkt_reason.
18739 	 * This is to prevent multiple console messages for the same failure
18740 	 * condition.  Note that un->un_last_pkt_reason is NOT restored if &
18741 	 * when the command is retried successfully because there still may be
18742 	 * more commands coming back with the same value of pktp->pkt_reason.
18743 	 */
18744 	if ((pktp->pkt_reason != CMD_CMPLT) || (xp->xb_retry_count == 0)) {
18745 		un->un_last_pkt_reason = pktp->pkt_reason;
18746 	}
18747 }
18748 
18749 
18750 /*
18751  *    Function: sd_print_cmd_incomplete_msg
18752  *
18753  * Description: Message logging fn. for a SCSA "CMD_INCOMPLETE" pkt_reason.
18754  *
18755  *   Arguments: un - ptr to associated softstate
18756  *		bp - ptr to buf(9S) for the command
18757  *		arg - passed to sd_print_retry_msg()
18758  *		code - SD_IMMEDIATE_RETRY_ISSUED, SD_DELAYED_RETRY_ISSUED,
18759  *			or SD_NO_RETRY_ISSUED
18760  *
18761  *     Context: May be called from interrupt context
18762  */
18763 
18764 static void
18765 sd_print_cmd_incomplete_msg(struct sd_lun *un, struct buf *bp, void *arg,
18766 	int code)
18767 {
18768 	dev_info_t	*dip;
18769 
18770 	ASSERT(un != NULL);
18771 	ASSERT(mutex_owned(SD_MUTEX(un)));
18772 	ASSERT(bp != NULL);
18773 
18774 	switch (code) {
18775 	case SD_NO_RETRY_ISSUED:
18776 		/* Command was failed. Someone turned off this target? */
18777 		if (un->un_state != SD_STATE_OFFLINE) {
18778 			/*
18779 			 * Suppress message if we are detaching and
18780 			 * device has been disconnected
18781 			 * Note that DEVI_IS_DEVICE_REMOVED is a consolidation
18782 			 * private interface and not part of the DDI
18783 			 */
18784 			dip = un->un_sd->sd_dev;
18785 			if (!(DEVI_IS_DETACHING(dip) &&
18786 			    DEVI_IS_DEVICE_REMOVED(dip))) {
18787 				scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
18788 				"disk not responding to selection\n");
18789 			}
18790 			New_state(un, SD_STATE_OFFLINE);
18791 		}
18792 		break;
18793 
18794 	case SD_DELAYED_RETRY_ISSUED:
18795 	case SD_IMMEDIATE_RETRY_ISSUED:
18796 	default:
18797 		/* Command was successfully queued for retry */
18798 		sd_print_retry_msg(un, bp, arg, code);
18799 		break;
18800 	}
18801 }
18802 
18803 
18804 /*
18805  *    Function: sd_pkt_reason_cmd_incomplete
18806  *
18807  * Description: Recovery actions for a SCSA "CMD_INCOMPLETE" pkt_reason.
18808  *
18809  *     Context: May be called from interrupt context
18810  */
18811 
18812 static void
18813 sd_pkt_reason_cmd_incomplete(struct sd_lun *un, struct buf *bp,
18814 	struct sd_xbuf *xp, struct scsi_pkt *pktp)
18815 {
18816 	int flag = SD_RETRIES_STANDARD | SD_RETRIES_ISOLATE;
18817 
18818 	ASSERT(un != NULL);
18819 	ASSERT(mutex_owned(SD_MUTEX(un)));
18820 	ASSERT(bp != NULL);
18821 	ASSERT(xp != NULL);
18822 	ASSERT(pktp != NULL);
18823 
18824 	/* Do not do a reset if selection did not complete */
18825 	/* Note: Should this not just check the bit? */
18826 	if (pktp->pkt_state != STATE_GOT_BUS) {
18827 		SD_UPDATE_ERRSTATS(un, sd_transerrs);
18828 		sd_reset_target(un, pktp);
18829 	}
18830 
18831 	/*
18832 	 * If the target was not successfully selected, then set
18833 	 * SD_RETRIES_FAILFAST to indicate that we lost communication
18834 	 * with the target, and further retries and/or commands are
18835 	 * likely to take a long time.
18836 	 */
18837 	if ((pktp->pkt_state & STATE_GOT_TARGET) == 0) {
18838 		flag |= SD_RETRIES_FAILFAST;
18839 	}
18840 
18841 	SD_UPDATE_RESERVATION_STATUS(un, pktp);
18842 
18843 	sd_retry_command(un, bp, flag,
18844 	    sd_print_cmd_incomplete_msg, NULL, EIO, SD_RESTART_TIMEOUT, NULL);
18845 }
18846 
18847 
18848 
18849 /*
18850  *    Function: sd_pkt_reason_cmd_tran_err
18851  *
18852  * Description: Recovery actions for a SCSA "CMD_TRAN_ERR" pkt_reason.
18853  *
18854  *     Context: May be called from interrupt context
18855  */
18856 
18857 static void
18858 sd_pkt_reason_cmd_tran_err(struct sd_lun *un, struct buf *bp,
18859 	struct sd_xbuf *xp, struct scsi_pkt *pktp)
18860 {
18861 	ASSERT(un != NULL);
18862 	ASSERT(mutex_owned(SD_MUTEX(un)));
18863 	ASSERT(bp != NULL);
18864 	ASSERT(xp != NULL);
18865 	ASSERT(pktp != NULL);
18866 
18867 	/*
18868 	 * Do not reset if we got a parity error, or if
18869 	 * selection did not complete.
18870 	 */
18871 	SD_UPDATE_ERRSTATS(un, sd_harderrs);
18872 	/* Note: Should this not just check the bit for pkt_state? */
18873 	if (((pktp->pkt_statistics & STAT_PERR) == 0) &&
18874 	    (pktp->pkt_state != STATE_GOT_BUS)) {
18875 		SD_UPDATE_ERRSTATS(un, sd_transerrs);
18876 		sd_reset_target(un, pktp);
18877 	}
18878 
18879 	SD_UPDATE_RESERVATION_STATUS(un, pktp);
18880 
18881 	sd_retry_command(un, bp, (SD_RETRIES_STANDARD | SD_RETRIES_ISOLATE),
18882 	    sd_print_retry_msg, NULL, EIO, SD_RESTART_TIMEOUT, NULL);
18883 }
18884 
18885 
18886 
18887 /*
18888  *    Function: sd_pkt_reason_cmd_reset
18889  *
18890  * Description: Recovery actions for a SCSA "CMD_RESET" pkt_reason.
18891  *
18892  *     Context: May be called from interrupt context
18893  */
18894 
18895 static void
18896 sd_pkt_reason_cmd_reset(struct sd_lun *un, struct buf *bp,
18897 	struct sd_xbuf *xp, struct scsi_pkt *pktp)
18898 {
18899 	ASSERT(un != NULL);
18900 	ASSERT(mutex_owned(SD_MUTEX(un)));
18901 	ASSERT(bp != NULL);
18902 	ASSERT(xp != NULL);
18903 	ASSERT(pktp != NULL);
18904 
18905 	/* The target may still be running the command, so try to reset. */
18906 	SD_UPDATE_ERRSTATS(un, sd_transerrs);
18907 	sd_reset_target(un, pktp);
18908 
18909 	SD_UPDATE_RESERVATION_STATUS(un, pktp);
18910 
18911 	/*
18912 	 * If pkt_reason is CMD_RESET chances are that this pkt got
18913 	 * reset because another target on this bus caused it. The target
18914 	 * that caused it should get CMD_TIMEOUT with pkt_statistics
18915 	 * of STAT_TIMEOUT/STAT_DEV_RESET.
18916 	 */
18917 
18918 	sd_retry_command(un, bp, (SD_RETRIES_VICTIM | SD_RETRIES_ISOLATE),
18919 	    sd_print_retry_msg, NULL, EIO, SD_RESTART_TIMEOUT, NULL);
18920 }
18921 
18922 
18923 
18924 
18925 /*
18926  *    Function: sd_pkt_reason_cmd_aborted
18927  *
18928  * Description: Recovery actions for a SCSA "CMD_ABORTED" pkt_reason.
18929  *
18930  *     Context: May be called from interrupt context
18931  */
18932 
18933 static void
18934 sd_pkt_reason_cmd_aborted(struct sd_lun *un, struct buf *bp,
18935 	struct sd_xbuf *xp, struct scsi_pkt *pktp)
18936 {
18937 	ASSERT(un != NULL);
18938 	ASSERT(mutex_owned(SD_MUTEX(un)));
18939 	ASSERT(bp != NULL);
18940 	ASSERT(xp != NULL);
18941 	ASSERT(pktp != NULL);
18942 
18943 	/* The target may still be running the command, so try to reset. */
18944 	SD_UPDATE_ERRSTATS(un, sd_transerrs);
18945 	sd_reset_target(un, pktp);
18946 
18947 	SD_UPDATE_RESERVATION_STATUS(un, pktp);
18948 
18949 	/*
18950 	 * If pkt_reason is CMD_ABORTED chances are that this pkt got
18951 	 * aborted because another target on this bus caused it. The target
18952 	 * that caused it should get CMD_TIMEOUT with pkt_statistics
18953 	 * of STAT_TIMEOUT/STAT_DEV_RESET.
18954 	 */
18955 
18956 	sd_retry_command(un, bp, (SD_RETRIES_VICTIM | SD_RETRIES_ISOLATE),
18957 	    sd_print_retry_msg, NULL, EIO, SD_RESTART_TIMEOUT, NULL);
18958 }
18959 
18960 
18961 
18962 /*
18963  *    Function: sd_pkt_reason_cmd_timeout
18964  *
18965  * Description: Recovery actions for a SCSA "CMD_TIMEOUT" pkt_reason.
18966  *
18967  *     Context: May be called from interrupt context
18968  */
18969 
18970 static void
18971 sd_pkt_reason_cmd_timeout(struct sd_lun *un, struct buf *bp,
18972 	struct sd_xbuf *xp, struct scsi_pkt *pktp)
18973 {
18974 	ASSERT(un != NULL);
18975 	ASSERT(mutex_owned(SD_MUTEX(un)));
18976 	ASSERT(bp != NULL);
18977 	ASSERT(xp != NULL);
18978 	ASSERT(pktp != NULL);
18979 
18980 
18981 	SD_UPDATE_ERRSTATS(un, sd_transerrs);
18982 	sd_reset_target(un, pktp);
18983 
18984 	SD_UPDATE_RESERVATION_STATUS(un, pktp);
18985 
18986 	/*
18987 	 * A command timeout indicates that we could not establish
18988 	 * communication with the target, so set SD_RETRIES_FAILFAST
18989 	 * as further retries/commands are likely to take a long time.
18990 	 */
18991 	sd_retry_command(un, bp,
18992 	    (SD_RETRIES_STANDARD | SD_RETRIES_ISOLATE | SD_RETRIES_FAILFAST),
18993 	    sd_print_retry_msg, NULL, EIO, SD_RESTART_TIMEOUT, NULL);
18994 }
18995 
18996 
18997 
18998 /*
18999  *    Function: sd_pkt_reason_cmd_unx_bus_free
19000  *
19001  * Description: Recovery actions for a SCSA "CMD_UNX_BUS_FREE" pkt_reason.
19002  *
19003  *     Context: May be called from interrupt context
19004  */
19005 
19006 static void
19007 sd_pkt_reason_cmd_unx_bus_free(struct sd_lun *un, struct buf *bp,
19008 	struct sd_xbuf *xp, struct scsi_pkt *pktp)
19009 {
19010 	void (*funcp)(struct sd_lun *un, struct buf *bp, void *arg, int code);
19011 
19012 	ASSERT(un != NULL);
19013 	ASSERT(mutex_owned(SD_MUTEX(un)));
19014 	ASSERT(bp != NULL);
19015 	ASSERT(xp != NULL);
19016 	ASSERT(pktp != NULL);
19017 
19018 	SD_UPDATE_ERRSTATS(un, sd_harderrs);
19019 	SD_UPDATE_RESERVATION_STATUS(un, pktp);
19020 
19021 	funcp = ((pktp->pkt_statistics & STAT_PERR) == 0) ?
19022 	    sd_print_retry_msg : NULL;
19023 
19024 	sd_retry_command(un, bp, (SD_RETRIES_STANDARD | SD_RETRIES_ISOLATE),
19025 	    funcp, NULL, EIO, SD_RESTART_TIMEOUT, NULL);
19026 }
19027 
19028 
19029 /*
19030  *    Function: sd_pkt_reason_cmd_tag_reject
19031  *
19032  * Description: Recovery actions for a SCSA "CMD_TAG_REJECT" pkt_reason.
19033  *
19034  *     Context: May be called from interrupt context
19035  */
19036 
19037 static void
19038 sd_pkt_reason_cmd_tag_reject(struct sd_lun *un, struct buf *bp,
19039 	struct sd_xbuf *xp, struct scsi_pkt *pktp)
19040 {
19041 	ASSERT(un != NULL);
19042 	ASSERT(mutex_owned(SD_MUTEX(un)));
19043 	ASSERT(bp != NULL);
19044 	ASSERT(xp != NULL);
19045 	ASSERT(pktp != NULL);
19046 
19047 	SD_UPDATE_ERRSTATS(un, sd_harderrs);
19048 	pktp->pkt_flags = 0;
19049 	un->un_tagflags = 0;
19050 	if (un->un_f_opt_queueing == TRUE) {
19051 		un->un_throttle = min(un->un_throttle, 3);
19052 	} else {
19053 		un->un_throttle = 1;
19054 	}
19055 	mutex_exit(SD_MUTEX(un));
19056 	(void) scsi_ifsetcap(SD_ADDRESS(un), "tagged-qing", 0, 1);
19057 	mutex_enter(SD_MUTEX(un));
19058 
19059 	SD_UPDATE_RESERVATION_STATUS(un, pktp);
19060 
19061 	/* Legacy behavior not to check retry counts here. */
19062 	sd_retry_command(un, bp, (SD_RETRIES_NOCHECK | SD_RETRIES_ISOLATE),
19063 	    sd_print_retry_msg, NULL, EIO, SD_RESTART_TIMEOUT, NULL);
19064 }
19065 
19066 
19067 /*
19068  *    Function: sd_pkt_reason_default
19069  *
19070  * Description: Default recovery actions for SCSA pkt_reason values that
19071  *		do not have more explicit recovery actions.
19072  *
19073  *     Context: May be called from interrupt context
19074  */
19075 
19076 static void
19077 sd_pkt_reason_default(struct sd_lun *un, struct buf *bp,
19078 	struct sd_xbuf *xp, struct scsi_pkt *pktp)
19079 {
19080 	ASSERT(un != NULL);
19081 	ASSERT(mutex_owned(SD_MUTEX(un)));
19082 	ASSERT(bp != NULL);
19083 	ASSERT(xp != NULL);
19084 	ASSERT(pktp != NULL);
19085 
19086 	SD_UPDATE_ERRSTATS(un, sd_transerrs);
19087 	sd_reset_target(un, pktp);
19088 
19089 	SD_UPDATE_RESERVATION_STATUS(un, pktp);
19090 
19091 	sd_retry_command(un, bp, (SD_RETRIES_STANDARD | SD_RETRIES_ISOLATE),
19092 	    sd_print_retry_msg, NULL, EIO, SD_RESTART_TIMEOUT, NULL);
19093 }
19094 
19095 
19096 
19097 /*
19098  *    Function: sd_pkt_status_check_condition
19099  *
19100  * Description: Recovery actions for a "STATUS_CHECK" SCSI command status.
19101  *
19102  *     Context: May be called from interrupt context
19103  */
19104 
19105 static void
19106 sd_pkt_status_check_condition(struct sd_lun *un, struct buf *bp,
19107 	struct sd_xbuf *xp, struct scsi_pkt *pktp)
19108 {
19109 	ASSERT(un != NULL);
19110 	ASSERT(mutex_owned(SD_MUTEX(un)));
19111 	ASSERT(bp != NULL);
19112 	ASSERT(xp != NULL);
19113 	ASSERT(pktp != NULL);
19114 
19115 	SD_TRACE(SD_LOG_IO, un, "sd_pkt_status_check_condition: "
19116 	    "entry: buf:0x%p xp:0x%p\n", bp, xp);
19117 
19118 	/*
19119 	 * If ARQ is NOT enabled, then issue a REQUEST SENSE command (the
19120 	 * command will be retried after the request sense). Otherwise, retry
19121 	 * the command. Note: we are issuing the request sense even though the
19122 	 * retry limit may have been reached for the failed command.
19123 	 */
19124 	if (un->un_f_arq_enabled == FALSE) {
19125 		SD_INFO(SD_LOG_IO_CORE, un, "sd_pkt_status_check_condition: "
19126 		    "no ARQ, sending request sense command\n");
19127 		sd_send_request_sense_command(un, bp, pktp);
19128 	} else {
19129 		SD_INFO(SD_LOG_IO_CORE, un, "sd_pkt_status_check_condition: "
19130 		    "ARQ,retrying request sense command\n");
19131 #if defined(__i386) || defined(__amd64)
19132 		/*
19133 		 * The SD_RETRY_DELAY value need to be adjusted here
19134 		 * when SD_RETRY_DELAY change in sddef.h
19135 		 */
19136 		sd_retry_command(un, bp, SD_RETRIES_STANDARD, NULL, NULL, EIO,
19137 		    un->un_f_is_fibre?drv_usectohz(100000):(clock_t)0,
19138 		    NULL);
19139 #else
19140 		sd_retry_command(un, bp, SD_RETRIES_STANDARD, NULL, NULL,
19141 		    EIO, SD_RETRY_DELAY, NULL);
19142 #endif
19143 	}
19144 
19145 	SD_TRACE(SD_LOG_IO_CORE, un, "sd_pkt_status_check_condition: exit\n");
19146 }
19147 
19148 
19149 /*
19150  *    Function: sd_pkt_status_busy
19151  *
19152  * Description: Recovery actions for a "STATUS_BUSY" SCSI command status.
19153  *
19154  *     Context: May be called from interrupt context
19155  */
19156 
19157 static void
19158 sd_pkt_status_busy(struct sd_lun *un, struct buf *bp, struct sd_xbuf *xp,
19159 	struct scsi_pkt *pktp)
19160 {
19161 	ASSERT(un != NULL);
19162 	ASSERT(mutex_owned(SD_MUTEX(un)));
19163 	ASSERT(bp != NULL);
19164 	ASSERT(xp != NULL);
19165 	ASSERT(pktp != NULL);
19166 
19167 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
19168 	    "sd_pkt_status_busy: entry\n");
19169 
19170 	/* If retries are exhausted, just fail the command. */
19171 	if (xp->xb_retry_count >= un->un_busy_retry_count) {
19172 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
19173 		    "device busy too long\n");
19174 		sd_return_failed_command(un, bp, EIO);
19175 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
19176 		    "sd_pkt_status_busy: exit\n");
19177 		return;
19178 	}
19179 	xp->xb_retry_count++;
19180 
19181 	/*
19182 	 * Try to reset the target. However, we do not want to perform
19183 	 * more than one reset if the device continues to fail. The reset
19184 	 * will be performed when the retry count reaches the reset
19185 	 * threshold.  This threshold should be set such that at least
19186 	 * one retry is issued before the reset is performed.
19187 	 */
19188 	if (xp->xb_retry_count ==
19189 	    ((un->un_reset_retry_count < 2) ? 2 : un->un_reset_retry_count)) {
19190 		int rval = 0;
19191 		mutex_exit(SD_MUTEX(un));
19192 		if (un->un_f_allow_bus_device_reset == TRUE) {
19193 			/*
19194 			 * First try to reset the LUN; if we cannot then
19195 			 * try to reset the target.
19196 			 */
19197 			if (un->un_f_lun_reset_enabled == TRUE) {
19198 				SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
19199 				    "sd_pkt_status_busy: RESET_LUN\n");
19200 				rval = scsi_reset(SD_ADDRESS(un), RESET_LUN);
19201 			}
19202 			if (rval == 0) {
19203 				SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
19204 				    "sd_pkt_status_busy: RESET_TARGET\n");
19205 				rval = scsi_reset(SD_ADDRESS(un), RESET_TARGET);
19206 			}
19207 		}
19208 		if (rval == 0) {
19209 			/*
19210 			 * If the RESET_LUN and/or RESET_TARGET failed,
19211 			 * try RESET_ALL
19212 			 */
19213 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
19214 			    "sd_pkt_status_busy: RESET_ALL\n");
19215 			rval = scsi_reset(SD_ADDRESS(un), RESET_ALL);
19216 		}
19217 		mutex_enter(SD_MUTEX(un));
19218 		if (rval == 0) {
19219 			/*
19220 			 * The RESET_LUN, RESET_TARGET, and/or RESET_ALL failed.
19221 			 * At this point we give up & fail the command.
19222 			 */
19223 			sd_return_failed_command(un, bp, EIO);
19224 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
19225 			    "sd_pkt_status_busy: exit (failed cmd)\n");
19226 			return;
19227 		}
19228 	}
19229 
19230 	/*
19231 	 * Retry the command. Be sure to specify SD_RETRIES_NOCHECK as
19232 	 * we have already checked the retry counts above.
19233 	 */
19234 	sd_retry_command(un, bp, SD_RETRIES_NOCHECK, NULL, NULL,
19235 	    EIO, un->un_busy_timeout, NULL);
19236 
19237 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
19238 	    "sd_pkt_status_busy: exit\n");
19239 }
19240 
19241 
19242 /*
19243  *    Function: sd_pkt_status_reservation_conflict
19244  *
19245  * Description: Recovery actions for a "STATUS_RESERVATION_CONFLICT" SCSI
19246  *		command status.
19247  *
19248  *     Context: May be called from interrupt context
19249  */
19250 
19251 static void
19252 sd_pkt_status_reservation_conflict(struct sd_lun *un, struct buf *bp,
19253 	struct sd_xbuf *xp, struct scsi_pkt *pktp)
19254 {
19255 	ASSERT(un != NULL);
19256 	ASSERT(mutex_owned(SD_MUTEX(un)));
19257 	ASSERT(bp != NULL);
19258 	ASSERT(xp != NULL);
19259 	ASSERT(pktp != NULL);
19260 
19261 	/*
19262 	 * If the command was PERSISTENT_RESERVATION_[IN|OUT] then reservation
19263 	 * conflict could be due to various reasons like incorrect keys, not
19264 	 * registered or not reserved etc. So, we return EACCES to the caller.
19265 	 */
19266 	if (un->un_reservation_type == SD_SCSI3_RESERVATION) {
19267 		int cmd = SD_GET_PKT_OPCODE(pktp);
19268 		if ((cmd == SCMD_PERSISTENT_RESERVE_IN) ||
19269 		    (cmd == SCMD_PERSISTENT_RESERVE_OUT)) {
19270 			sd_return_failed_command(un, bp, EACCES);
19271 			return;
19272 		}
19273 	}
19274 
19275 	un->un_resvd_status |= SD_RESERVATION_CONFLICT;
19276 
19277 	if ((un->un_resvd_status & SD_FAILFAST) != 0) {
19278 		if (sd_failfast_enable != 0) {
19279 			/* By definition, we must panic here.... */
19280 			sd_panic_for_res_conflict(un);
19281 			/*NOTREACHED*/
19282 		}
19283 		SD_ERROR(SD_LOG_IO, un,
19284 		    "sd_handle_resv_conflict: Disk Reserved\n");
19285 		sd_return_failed_command(un, bp, EACCES);
19286 		return;
19287 	}
19288 
19289 	/*
19290 	 * 1147670: retry only if sd_retry_on_reservation_conflict
19291 	 * property is set (default is 1). Retries will not succeed
19292 	 * on a disk reserved by another initiator. HA systems
19293 	 * may reset this via sd.conf to avoid these retries.
19294 	 *
19295 	 * Note: The legacy return code for this failure is EIO, however EACCES
19296 	 * seems more appropriate for a reservation conflict.
19297 	 */
19298 	if (sd_retry_on_reservation_conflict == 0) {
19299 		SD_ERROR(SD_LOG_IO, un,
19300 		    "sd_handle_resv_conflict: Device Reserved\n");
19301 		sd_return_failed_command(un, bp, EIO);
19302 		return;
19303 	}
19304 
19305 	/*
19306 	 * Retry the command if we can.
19307 	 *
19308 	 * Note: The legacy return code for this failure is EIO, however EACCES
19309 	 * seems more appropriate for a reservation conflict.
19310 	 */
19311 	sd_retry_command(un, bp, SD_RETRIES_STANDARD, NULL, NULL, EIO,
19312 	    (clock_t)2, NULL);
19313 }
19314 
19315 
19316 
19317 /*
19318  *    Function: sd_pkt_status_qfull
19319  *
19320  * Description: Handle a QUEUE FULL condition from the target.  This can
19321  *		occur if the HBA does not handle the queue full condition.
19322  *		(Basically this means third-party HBAs as Sun HBAs will
19323  *		handle the queue full condition.)  Note that if there are
19324  *		some commands already in the transport, then the queue full
19325  *		has occurred because the queue for this nexus is actually
19326  *		full. If there are no commands in the transport, then the
19327  *		queue full is resulting from some other initiator or lun
19328  *		consuming all the resources at the target.
19329  *
19330  *     Context: May be called from interrupt context
19331  */
19332 
19333 static void
19334 sd_pkt_status_qfull(struct sd_lun *un, struct buf *bp,
19335 	struct sd_xbuf *xp, struct scsi_pkt *pktp)
19336 {
19337 	ASSERT(un != NULL);
19338 	ASSERT(mutex_owned(SD_MUTEX(un)));
19339 	ASSERT(bp != NULL);
19340 	ASSERT(xp != NULL);
19341 	ASSERT(pktp != NULL);
19342 
19343 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
19344 	    "sd_pkt_status_qfull: entry\n");
19345 
19346 	/*
19347 	 * Just lower the QFULL throttle and retry the command.  Note that
19348 	 * we do not limit the number of retries here.
19349 	 */
19350 	sd_reduce_throttle(un, SD_THROTTLE_QFULL);
19351 	sd_retry_command(un, bp, SD_RETRIES_NOCHECK, NULL, NULL, 0,
19352 	    SD_RESTART_TIMEOUT, NULL);
19353 
19354 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
19355 	    "sd_pkt_status_qfull: exit\n");
19356 }
19357 
19358 
19359 /*
19360  *    Function: sd_reset_target
19361  *
19362  * Description: Issue a scsi_reset(9F), with either RESET_LUN,
19363  *		RESET_TARGET, or RESET_ALL.
19364  *
19365  *     Context: May be called under interrupt context.
19366  */
19367 
19368 static void
19369 sd_reset_target(struct sd_lun *un, struct scsi_pkt *pktp)
19370 {
19371 	int rval = 0;
19372 
19373 	ASSERT(un != NULL);
19374 	ASSERT(mutex_owned(SD_MUTEX(un)));
19375 	ASSERT(pktp != NULL);
19376 
19377 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un, "sd_reset_target: entry\n");
19378 
19379 	/*
19380 	 * No need to reset if the transport layer has already done so.
19381 	 */
19382 	if ((pktp->pkt_statistics &
19383 	    (STAT_BUS_RESET | STAT_DEV_RESET | STAT_ABORTED)) != 0) {
19384 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
19385 		    "sd_reset_target: no reset\n");
19386 		return;
19387 	}
19388 
19389 	mutex_exit(SD_MUTEX(un));
19390 
19391 	if (un->un_f_allow_bus_device_reset == TRUE) {
19392 		if (un->un_f_lun_reset_enabled == TRUE) {
19393 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
19394 			    "sd_reset_target: RESET_LUN\n");
19395 			rval = scsi_reset(SD_ADDRESS(un), RESET_LUN);
19396 		}
19397 		if (rval == 0) {
19398 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
19399 			    "sd_reset_target: RESET_TARGET\n");
19400 			rval = scsi_reset(SD_ADDRESS(un), RESET_TARGET);
19401 		}
19402 	}
19403 
19404 	if (rval == 0) {
19405 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
19406 		    "sd_reset_target: RESET_ALL\n");
19407 		(void) scsi_reset(SD_ADDRESS(un), RESET_ALL);
19408 	}
19409 
19410 	mutex_enter(SD_MUTEX(un));
19411 
19412 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un, "sd_reset_target: exit\n");
19413 }
19414 
19415 /*
19416  *    Function: sd_target_change_task
19417  *
19418  * Description: Handle dynamic target change
19419  *
19420  *     Context: Executes in a taskq() thread context
19421  */
19422 static void
19423 sd_target_change_task(void *arg)
19424 {
19425 	struct sd_lun		*un = arg;
19426 	uint64_t		capacity;
19427 	diskaddr_t		label_cap;
19428 	uint_t			lbasize;
19429 	sd_ssc_t		*ssc;
19430 
19431 	ASSERT(un != NULL);
19432 	ASSERT(!mutex_owned(SD_MUTEX(un)));
19433 
19434 	if ((un->un_f_blockcount_is_valid == FALSE) ||
19435 	    (un->un_f_tgt_blocksize_is_valid == FALSE)) {
19436 		return;
19437 	}
19438 
19439 	ssc = sd_ssc_init(un);
19440 
19441 	if (sd_send_scsi_READ_CAPACITY(ssc, &capacity,
19442 	    &lbasize, SD_PATH_DIRECT) != 0) {
19443 		SD_ERROR(SD_LOG_ERROR, un,
19444 		    "sd_target_change_task: fail to read capacity\n");
19445 		sd_ssc_assessment(ssc, SD_FMT_IGNORE);
19446 		goto task_exit;
19447 	}
19448 
19449 	mutex_enter(SD_MUTEX(un));
19450 	if (capacity <= un->un_blockcount) {
19451 		mutex_exit(SD_MUTEX(un));
19452 		goto task_exit;
19453 	}
19454 
19455 	sd_update_block_info(un, lbasize, capacity);
19456 	mutex_exit(SD_MUTEX(un));
19457 
19458 	/*
19459 	 * If lun is EFI labeled and lun capacity is greater than the
19460 	 * capacity contained in the label, log a sys event.
19461 	 */
19462 	if (cmlb_efi_label_capacity(un->un_cmlbhandle, &label_cap,
19463 	    (void*)SD_PATH_DIRECT) == 0) {
19464 		mutex_enter(SD_MUTEX(un));
19465 		if (un->un_f_blockcount_is_valid &&
19466 		    un->un_blockcount > label_cap) {
19467 			mutex_exit(SD_MUTEX(un));
19468 			sd_log_lun_expansion_event(un, KM_SLEEP);
19469 		} else {
19470 			mutex_exit(SD_MUTEX(un));
19471 		}
19472 	}
19473 
19474 task_exit:
19475 	sd_ssc_fini(ssc);
19476 }
19477 
19478 /*
19479  *    Function: sd_log_lun_expansion_event
19480  *
19481  * Description: Log lun expansion sys event
19482  *
19483  *     Context: Never called from interrupt context
19484  */
19485 static void
19486 sd_log_lun_expansion_event(struct sd_lun *un, int km_flag)
19487 {
19488 	int err;
19489 	char			*path;
19490 	nvlist_t		*dle_attr_list;
19491 
19492 	/* Allocate and build sysevent attribute list */
19493 	err = nvlist_alloc(&dle_attr_list, NV_UNIQUE_NAME_TYPE, km_flag);
19494 	if (err != 0) {
19495 		SD_ERROR(SD_LOG_ERROR, un,
19496 		    "sd_log_lun_expansion_event: fail to allocate space\n");
19497 		return;
19498 	}
19499 
19500 	path = kmem_alloc(MAXPATHLEN, km_flag);
19501 	if (path == NULL) {
19502 		nvlist_free(dle_attr_list);
19503 		SD_ERROR(SD_LOG_ERROR, un,
19504 		    "sd_log_lun_expansion_event: fail to allocate space\n");
19505 		return;
19506 	}
19507 	/*
19508 	 * Add path attribute to identify the lun.
19509 	 * We are using minor node 'a' as the sysevent attribute.
19510 	 */
19511 	(void) snprintf(path, MAXPATHLEN, "/devices");
19512 	(void) ddi_pathname(SD_DEVINFO(un), path + strlen(path));
19513 	(void) snprintf(path + strlen(path), MAXPATHLEN - strlen(path),
19514 	    ":a");
19515 
19516 	err = nvlist_add_string(dle_attr_list, DEV_PHYS_PATH, path);
19517 	if (err != 0) {
19518 		nvlist_free(dle_attr_list);
19519 		kmem_free(path, MAXPATHLEN);
19520 		SD_ERROR(SD_LOG_ERROR, un,
19521 		    "sd_log_lun_expansion_event: fail to add attribute\n");
19522 		return;
19523 	}
19524 
19525 	/* Log dynamic lun expansion sysevent */
19526 	err = ddi_log_sysevent(SD_DEVINFO(un), SUNW_VENDOR, EC_DEV_STATUS,
19527 	    ESC_DEV_DLE, dle_attr_list, NULL, km_flag);
19528 	if (err != DDI_SUCCESS) {
19529 		SD_ERROR(SD_LOG_ERROR, un,
19530 		    "sd_log_lun_expansion_event: fail to log sysevent\n");
19531 	}
19532 
19533 	nvlist_free(dle_attr_list);
19534 	kmem_free(path, MAXPATHLEN);
19535 }
19536 
19537 /*
19538  *    Function: sd_media_change_task
19539  *
19540  * Description: Recovery action for CDROM to become available.
19541  *
19542  *     Context: Executes in a taskq() thread context
19543  */
19544 
19545 static void
19546 sd_media_change_task(void *arg)
19547 {
19548 	struct	scsi_pkt	*pktp = arg;
19549 	struct	sd_lun		*un;
19550 	struct	buf		*bp;
19551 	struct	sd_xbuf		*xp;
19552 	int	err		= 0;
19553 	int	retry_count	= 0;
19554 	int	retry_limit	= SD_UNIT_ATTENTION_RETRY/10;
19555 	struct	sd_sense_info	si;
19556 
19557 	ASSERT(pktp != NULL);
19558 	bp = (struct buf *)pktp->pkt_private;
19559 	ASSERT(bp != NULL);
19560 	xp = SD_GET_XBUF(bp);
19561 	ASSERT(xp != NULL);
19562 	un = SD_GET_UN(bp);
19563 	ASSERT(un != NULL);
19564 	ASSERT(!mutex_owned(SD_MUTEX(un)));
19565 	ASSERT(un->un_f_monitor_media_state);
19566 
19567 	si.ssi_severity = SCSI_ERR_INFO;
19568 	si.ssi_pfa_flag = FALSE;
19569 
19570 	/*
19571 	 * When a reset is issued on a CDROM, it takes a long time to
19572 	 * recover. First few attempts to read capacity and other things
19573 	 * related to handling unit attention fail (with a ASC 0x4 and
19574 	 * ASCQ 0x1). In that case we want to do enough retries and we want
19575 	 * to limit the retries in other cases of genuine failures like
19576 	 * no media in drive.
19577 	 */
19578 	while (retry_count++ < retry_limit) {
19579 		if ((err = sd_handle_mchange(un)) == 0) {
19580 			break;
19581 		}
19582 		if (err == EAGAIN) {
19583 			retry_limit = SD_UNIT_ATTENTION_RETRY;
19584 		}
19585 		/* Sleep for 0.5 sec. & try again */
19586 		delay(drv_usectohz(500000));
19587 	}
19588 
19589 	/*
19590 	 * Dispatch (retry or fail) the original command here,
19591 	 * along with appropriate console messages....
19592 	 *
19593 	 * Must grab the mutex before calling sd_retry_command,
19594 	 * sd_print_sense_msg and sd_return_failed_command.
19595 	 */
19596 	mutex_enter(SD_MUTEX(un));
19597 	if (err != SD_CMD_SUCCESS) {
19598 		SD_UPDATE_ERRSTATS(un, sd_harderrs);
19599 		SD_UPDATE_ERRSTATS(un, sd_rq_nodev_err);
19600 		si.ssi_severity = SCSI_ERR_FATAL;
19601 		sd_print_sense_msg(un, bp, &si, SD_NO_RETRY_ISSUED);
19602 		sd_return_failed_command(un, bp, EIO);
19603 	} else {
19604 		sd_retry_command(un, bp, SD_RETRIES_NOCHECK, sd_print_sense_msg,
19605 		    &si, EIO, (clock_t)0, NULL);
19606 	}
19607 	mutex_exit(SD_MUTEX(un));
19608 }
19609 
19610 
19611 
19612 /*
19613  *    Function: sd_handle_mchange
19614  *
19615  * Description: Perform geometry validation & other recovery when CDROM
19616  *		has been removed from drive.
19617  *
19618  * Return Code: 0 for success
19619  *		errno-type return code of either sd_send_scsi_DOORLOCK() or
19620  *		sd_send_scsi_READ_CAPACITY()
19621  *
19622  *     Context: Executes in a taskq() thread context
19623  */
19624 
19625 static int
19626 sd_handle_mchange(struct sd_lun *un)
19627 {
19628 	uint64_t	capacity;
19629 	uint32_t	lbasize;
19630 	int		rval;
19631 	sd_ssc_t	*ssc;
19632 
19633 	ASSERT(!mutex_owned(SD_MUTEX(un)));
19634 	ASSERT(un->un_f_monitor_media_state);
19635 
19636 	ssc = sd_ssc_init(un);
19637 	rval = sd_send_scsi_READ_CAPACITY(ssc, &capacity, &lbasize,
19638 	    SD_PATH_DIRECT_PRIORITY);
19639 
19640 	if (rval != 0)
19641 		goto failed;
19642 
19643 	mutex_enter(SD_MUTEX(un));
19644 	sd_update_block_info(un, lbasize, capacity);
19645 
19646 	if (un->un_errstats != NULL) {
19647 		struct	sd_errstats *stp =
19648 		    (struct sd_errstats *)un->un_errstats->ks_data;
19649 		stp->sd_capacity.value.ui64 = (uint64_t)
19650 		    ((uint64_t)un->un_blockcount *
19651 		    (uint64_t)un->un_tgt_blocksize);
19652 	}
19653 
19654 	/*
19655 	 * Check if the media in the device is writable or not
19656 	 */
19657 	if (ISCD(un)) {
19658 		sd_check_for_writable_cd(ssc, SD_PATH_DIRECT_PRIORITY);
19659 	}
19660 
19661 	/*
19662 	 * Note: Maybe let the strategy/partitioning chain worry about getting
19663 	 * valid geometry.
19664 	 */
19665 	mutex_exit(SD_MUTEX(un));
19666 	cmlb_invalidate(un->un_cmlbhandle, (void *)SD_PATH_DIRECT_PRIORITY);
19667 
19668 
19669 	if (cmlb_validate(un->un_cmlbhandle, 0,
19670 	    (void *)SD_PATH_DIRECT_PRIORITY) != 0) {
19671 		sd_ssc_fini(ssc);
19672 		return (EIO);
19673 	} else {
19674 		if (un->un_f_pkstats_enabled) {
19675 			sd_set_pstats(un);
19676 			SD_TRACE(SD_LOG_IO_PARTITION, un,
19677 			    "sd_handle_mchange: un:0x%p pstats created and "
19678 			    "set\n", un);
19679 		}
19680 	}
19681 
19682 	/*
19683 	 * Try to lock the door
19684 	 */
19685 	rval = sd_send_scsi_DOORLOCK(ssc, SD_REMOVAL_PREVENT,
19686 	    SD_PATH_DIRECT_PRIORITY);
19687 failed:
19688 	if (rval != 0)
19689 		sd_ssc_assessment(ssc, SD_FMT_IGNORE);
19690 	sd_ssc_fini(ssc);
19691 	return (rval);
19692 }
19693 
19694 
19695 /*
19696  *    Function: sd_send_scsi_DOORLOCK
19697  *
19698  * Description: Issue the scsi DOOR LOCK command
19699  *
19700  *   Arguments: ssc   - ssc contains pointer to driver soft state (unit)
19701  *                      structure for this target.
19702  *		flag  - SD_REMOVAL_ALLOW
19703  *			SD_REMOVAL_PREVENT
19704  *		path_flag - SD_PATH_DIRECT to use the USCSI "direct" chain and
19705  *			the normal command waitq, or SD_PATH_DIRECT_PRIORITY
19706  *			to use the USCSI "direct" chain and bypass the normal
19707  *			command waitq. SD_PATH_DIRECT_PRIORITY is used when this
19708  *			command is issued as part of an error recovery action.
19709  *
19710  * Return Code: 0   - Success
19711  *		errno return code from sd_ssc_send()
19712  *
19713  *     Context: Can sleep.
19714  */
19715 
19716 static int
19717 sd_send_scsi_DOORLOCK(sd_ssc_t *ssc, int flag, int path_flag)
19718 {
19719 	struct scsi_extended_sense	sense_buf;
19720 	union scsi_cdb		cdb;
19721 	struct uscsi_cmd	ucmd_buf;
19722 	int			status;
19723 	struct sd_lun		*un;
19724 
19725 	ASSERT(ssc != NULL);
19726 	un = ssc->ssc_un;
19727 	ASSERT(un != NULL);
19728 	ASSERT(!mutex_owned(SD_MUTEX(un)));
19729 
19730 	SD_TRACE(SD_LOG_IO, un, "sd_send_scsi_DOORLOCK: entry: un:0x%p\n", un);
19731 
19732 	/* already determined doorlock is not supported, fake success */
19733 	if (un->un_f_doorlock_supported == FALSE) {
19734 		return (0);
19735 	}
19736 
19737 	/*
19738 	 * If we are ejecting and see an SD_REMOVAL_PREVENT
19739 	 * ignore the command so we can complete the eject
19740 	 * operation.
19741 	 */
19742 	if (flag == SD_REMOVAL_PREVENT) {
19743 		mutex_enter(SD_MUTEX(un));
19744 		if (un->un_f_ejecting == TRUE) {
19745 			mutex_exit(SD_MUTEX(un));
19746 			return (EAGAIN);
19747 		}
19748 		mutex_exit(SD_MUTEX(un));
19749 	}
19750 
19751 	bzero(&cdb, sizeof (cdb));
19752 	bzero(&ucmd_buf, sizeof (ucmd_buf));
19753 
19754 	cdb.scc_cmd = SCMD_DOORLOCK;
19755 	cdb.cdb_opaque[4] = (uchar_t)flag;
19756 
19757 	ucmd_buf.uscsi_cdb	= (char *)&cdb;
19758 	ucmd_buf.uscsi_cdblen	= CDB_GROUP0;
19759 	ucmd_buf.uscsi_bufaddr	= NULL;
19760 	ucmd_buf.uscsi_buflen	= 0;
19761 	ucmd_buf.uscsi_rqbuf	= (caddr_t)&sense_buf;
19762 	ucmd_buf.uscsi_rqlen	= sizeof (sense_buf);
19763 	ucmd_buf.uscsi_flags	= USCSI_RQENABLE | USCSI_SILENT;
19764 	ucmd_buf.uscsi_timeout	= 15;
19765 
19766 	SD_TRACE(SD_LOG_IO, un,
19767 	    "sd_send_scsi_DOORLOCK: returning sd_ssc_send\n");
19768 
19769 	status = sd_ssc_send(ssc, &ucmd_buf, FKIOCTL,
19770 	    UIO_SYSSPACE, path_flag);
19771 
19772 	if (status == 0)
19773 		sd_ssc_assessment(ssc, SD_FMT_STANDARD);
19774 
19775 	if ((status == EIO) && (ucmd_buf.uscsi_status == STATUS_CHECK) &&
19776 	    (ucmd_buf.uscsi_rqstatus == STATUS_GOOD) &&
19777 	    (scsi_sense_key((uint8_t *)&sense_buf) == KEY_ILLEGAL_REQUEST)) {
19778 		sd_ssc_assessment(ssc, SD_FMT_IGNORE);
19779 
19780 		/* fake success and skip subsequent doorlock commands */
19781 		un->un_f_doorlock_supported = FALSE;
19782 		return (0);
19783 	}
19784 
19785 	return (status);
19786 }
19787 
19788 /*
19789  *    Function: sd_send_scsi_READ_CAPACITY
19790  *
19791  * Description: This routine uses the scsi READ CAPACITY command to determine
19792  *		the device capacity in number of blocks and the device native
19793  *		block size. If this function returns a failure, then the
19794  *		values in *capp and *lbap are undefined.  If the capacity
19795  *		returned is 0xffffffff then the lun is too large for a
19796  *		normal READ CAPACITY command and the results of a
19797  *		READ CAPACITY 16 will be used instead.
19798  *
19799  *   Arguments: ssc   - ssc contains ptr to soft state struct for the target
19800  *		capp - ptr to unsigned 64-bit variable to receive the
19801  *			capacity value from the command.
19802  *		lbap - ptr to unsigned 32-bit varaible to receive the
19803  *			block size value from the command
19804  *		path_flag - SD_PATH_DIRECT to use the USCSI "direct" chain and
19805  *			the normal command waitq, or SD_PATH_DIRECT_PRIORITY
19806  *			to use the USCSI "direct" chain and bypass the normal
19807  *			command waitq. SD_PATH_DIRECT_PRIORITY is used when this
19808  *			command is issued as part of an error recovery action.
19809  *
19810  * Return Code: 0   - Success
19811  *		EIO - IO error
19812  *		EACCES - Reservation conflict detected
19813  *		EAGAIN - Device is becoming ready
19814  *		errno return code from sd_ssc_send()
19815  *
19816  *     Context: Can sleep.  Blocks until command completes.
19817  */
19818 
19819 #define	SD_CAPACITY_SIZE	sizeof (struct scsi_capacity)
19820 
19821 static int
19822 sd_send_scsi_READ_CAPACITY(sd_ssc_t *ssc, uint64_t *capp, uint32_t *lbap,
19823 	int path_flag)
19824 {
19825 	struct	scsi_extended_sense	sense_buf;
19826 	struct	uscsi_cmd	ucmd_buf;
19827 	union	scsi_cdb	cdb;
19828 	uint32_t		*capacity_buf;
19829 	uint64_t		capacity;
19830 	uint32_t		lbasize;
19831 	uint32_t		pbsize;
19832 	int			status;
19833 	struct sd_lun		*un;
19834 
19835 	ASSERT(ssc != NULL);
19836 
19837 	un = ssc->ssc_un;
19838 	ASSERT(un != NULL);
19839 	ASSERT(!mutex_owned(SD_MUTEX(un)));
19840 	ASSERT(capp != NULL);
19841 	ASSERT(lbap != NULL);
19842 
19843 	SD_TRACE(SD_LOG_IO, un,
19844 	    "sd_send_scsi_READ_CAPACITY: entry: un:0x%p\n", un);
19845 
19846 	/*
19847 	 * First send a READ_CAPACITY command to the target.
19848 	 * (This command is mandatory under SCSI-2.)
19849 	 *
19850 	 * Set up the CDB for the READ_CAPACITY command.  The Partial
19851 	 * Medium Indicator bit is cleared.  The address field must be
19852 	 * zero if the PMI bit is zero.
19853 	 */
19854 	bzero(&cdb, sizeof (cdb));
19855 	bzero(&ucmd_buf, sizeof (ucmd_buf));
19856 
19857 	capacity_buf = kmem_zalloc(SD_CAPACITY_SIZE, KM_SLEEP);
19858 
19859 	cdb.scc_cmd = SCMD_READ_CAPACITY;
19860 
19861 	ucmd_buf.uscsi_cdb	= (char *)&cdb;
19862 	ucmd_buf.uscsi_cdblen	= CDB_GROUP1;
19863 	ucmd_buf.uscsi_bufaddr	= (caddr_t)capacity_buf;
19864 	ucmd_buf.uscsi_buflen	= SD_CAPACITY_SIZE;
19865 	ucmd_buf.uscsi_rqbuf	= (caddr_t)&sense_buf;
19866 	ucmd_buf.uscsi_rqlen	= sizeof (sense_buf);
19867 	ucmd_buf.uscsi_flags	= USCSI_RQENABLE | USCSI_READ | USCSI_SILENT;
19868 	ucmd_buf.uscsi_timeout	= 60;
19869 
19870 	status = sd_ssc_send(ssc, &ucmd_buf, FKIOCTL,
19871 	    UIO_SYSSPACE, path_flag);
19872 
19873 	switch (status) {
19874 	case 0:
19875 		/* Return failure if we did not get valid capacity data. */
19876 		if (ucmd_buf.uscsi_resid != 0) {
19877 			sd_ssc_set_info(ssc, SSC_FLAGS_INVALID_DATA, -1,
19878 			    "sd_send_scsi_READ_CAPACITY received invalid "
19879 			    "capacity data");
19880 			kmem_free(capacity_buf, SD_CAPACITY_SIZE);
19881 			return (EIO);
19882 		}
19883 		/*
19884 		 * Read capacity and block size from the READ CAPACITY 10 data.
19885 		 * This data may be adjusted later due to device specific
19886 		 * issues.
19887 		 *
19888 		 * According to the SCSI spec, the READ CAPACITY 10
19889 		 * command returns the following:
19890 		 *
19891 		 *  bytes 0-3: Maximum logical block address available.
19892 		 *		(MSB in byte:0 & LSB in byte:3)
19893 		 *
19894 		 *  bytes 4-7: Block length in bytes
19895 		 *		(MSB in byte:4 & LSB in byte:7)
19896 		 *
19897 		 */
19898 		capacity = BE_32(capacity_buf[0]);
19899 		lbasize = BE_32(capacity_buf[1]);
19900 
19901 		/*
19902 		 * Done with capacity_buf
19903 		 */
19904 		kmem_free(capacity_buf, SD_CAPACITY_SIZE);
19905 
19906 		/*
19907 		 * if the reported capacity is set to all 0xf's, then
19908 		 * this disk is too large and requires SBC-2 commands.
19909 		 * Reissue the request using READ CAPACITY 16.
19910 		 */
19911 		if (capacity == 0xffffffff) {
19912 			sd_ssc_assessment(ssc, SD_FMT_IGNORE);
19913 			status = sd_send_scsi_READ_CAPACITY_16(ssc, &capacity,
19914 			    &lbasize, &pbsize, path_flag);
19915 			if (status != 0) {
19916 				return (status);
19917 			}
19918 		}
19919 		break;	/* Success! */
19920 	case EIO:
19921 		switch (ucmd_buf.uscsi_status) {
19922 		case STATUS_RESERVATION_CONFLICT:
19923 			status = EACCES;
19924 			break;
19925 		case STATUS_CHECK:
19926 			/*
19927 			 * Check condition; look for ASC/ASCQ of 0x04/0x01
19928 			 * (LOGICAL UNIT IS IN PROCESS OF BECOMING READY)
19929 			 */
19930 			if ((ucmd_buf.uscsi_rqstatus == STATUS_GOOD) &&
19931 			    (scsi_sense_asc((uint8_t *)&sense_buf) == 0x04) &&
19932 			    (scsi_sense_ascq((uint8_t *)&sense_buf) == 0x01)) {
19933 				kmem_free(capacity_buf, SD_CAPACITY_SIZE);
19934 				return (EAGAIN);
19935 			}
19936 			break;
19937 		default:
19938 			break;
19939 		}
19940 		/* FALLTHRU */
19941 	default:
19942 		kmem_free(capacity_buf, SD_CAPACITY_SIZE);
19943 		return (status);
19944 	}
19945 
19946 	/*
19947 	 * Some ATAPI CD-ROM drives report inaccurate LBA size values
19948 	 * (2352 and 0 are common) so for these devices always force the value
19949 	 * to 2048 as required by the ATAPI specs.
19950 	 */
19951 	if ((un->un_f_cfg_is_atapi == TRUE) && (ISCD(un))) {
19952 		lbasize = 2048;
19953 	}
19954 
19955 	/*
19956 	 * Get the maximum LBA value from the READ CAPACITY data.
19957 	 * Here we assume that the Partial Medium Indicator (PMI) bit
19958 	 * was cleared when issuing the command. This means that the LBA
19959 	 * returned from the device is the LBA of the last logical block
19960 	 * on the logical unit.  The actual logical block count will be
19961 	 * this value plus one.
19962 	 */
19963 	capacity += 1;
19964 
19965 	/*
19966 	 * Currently, for removable media, the capacity is saved in terms
19967 	 * of un->un_sys_blocksize, so scale the capacity value to reflect this.
19968 	 */
19969 	if (un->un_f_has_removable_media)
19970 		capacity *= (lbasize / un->un_sys_blocksize);
19971 
19972 	/*
19973 	 * Copy the values from the READ CAPACITY command into the space
19974 	 * provided by the caller.
19975 	 */
19976 	*capp = capacity;
19977 	*lbap = lbasize;
19978 
19979 	SD_TRACE(SD_LOG_IO, un, "sd_send_scsi_READ_CAPACITY: "
19980 	    "capacity:0x%llx  lbasize:0x%x\n", capacity, lbasize);
19981 
19982 	/*
19983 	 * Both the lbasize and capacity from the device must be nonzero,
19984 	 * otherwise we assume that the values are not valid and return
19985 	 * failure to the caller. (4203735)
19986 	 */
19987 	if ((capacity == 0) || (lbasize == 0)) {
19988 		sd_ssc_set_info(ssc, SSC_FLAGS_INVALID_DATA, -1,
19989 		    "sd_send_scsi_READ_CAPACITY received invalid value "
19990 		    "capacity %llu lbasize %d", capacity, lbasize);
19991 		return (EIO);
19992 	}
19993 	sd_ssc_assessment(ssc, SD_FMT_STANDARD);
19994 	return (0);
19995 }
19996 
19997 /*
19998  *    Function: sd_send_scsi_READ_CAPACITY_16
19999  *
20000  * Description: This routine uses the scsi READ CAPACITY 16 command to
20001  *		determine the device capacity in number of blocks and the
20002  *		device native block size.  If this function returns a failure,
20003  *		then the values in *capp and *lbap are undefined.
20004  *		This routine should be called by sd_send_scsi_READ_CAPACITY
20005  *              which will apply any device specific adjustments to capacity
20006  *              and lbasize. One exception is it is also called by
20007  *              sd_get_media_info_ext. In that function, there is no need to
20008  *              adjust the capacity and lbasize.
20009  *
20010  *   Arguments: ssc   - ssc contains ptr to soft state struct for the target
20011  *		capp - ptr to unsigned 64-bit variable to receive the
20012  *			capacity value from the command.
20013  *		lbap - ptr to unsigned 32-bit varaible to receive the
20014  *			block size value from the command
20015  *              psp  - ptr to unsigned 32-bit variable to receive the
20016  *                      physical block size value from the command
20017  *		path_flag - SD_PATH_DIRECT to use the USCSI "direct" chain and
20018  *			the normal command waitq, or SD_PATH_DIRECT_PRIORITY
20019  *			to use the USCSI "direct" chain and bypass the normal
20020  *			command waitq. SD_PATH_DIRECT_PRIORITY is used when
20021  *			this command is issued as part of an error recovery
20022  *			action.
20023  *
20024  * Return Code: 0   - Success
20025  *		EIO - IO error
20026  *		EACCES - Reservation conflict detected
20027  *		EAGAIN - Device is becoming ready
20028  *		errno return code from sd_ssc_send()
20029  *
20030  *     Context: Can sleep.  Blocks until command completes.
20031  */
20032 
20033 #define	SD_CAPACITY_16_SIZE	sizeof (struct scsi_capacity_16)
20034 
20035 static int
20036 sd_send_scsi_READ_CAPACITY_16(sd_ssc_t *ssc, uint64_t *capp,
20037 	uint32_t *lbap, uint32_t *psp, int path_flag)
20038 {
20039 	struct	scsi_extended_sense	sense_buf;
20040 	struct	uscsi_cmd	ucmd_buf;
20041 	union	scsi_cdb	cdb;
20042 	uint64_t		*capacity16_buf;
20043 	uint64_t		capacity;
20044 	uint32_t		lbasize;
20045 	uint32_t		pbsize;
20046 	uint32_t		lbpb_exp;
20047 	int			status;
20048 	struct sd_lun		*un;
20049 
20050 	ASSERT(ssc != NULL);
20051 
20052 	un = ssc->ssc_un;
20053 	ASSERT(un != NULL);
20054 	ASSERT(!mutex_owned(SD_MUTEX(un)));
20055 	ASSERT(capp != NULL);
20056 	ASSERT(lbap != NULL);
20057 
20058 	SD_TRACE(SD_LOG_IO, un,
20059 	    "sd_send_scsi_READ_CAPACITY: entry: un:0x%p\n", un);
20060 
20061 	/*
20062 	 * First send a READ_CAPACITY_16 command to the target.
20063 	 *
20064 	 * Set up the CDB for the READ_CAPACITY_16 command.  The Partial
20065 	 * Medium Indicator bit is cleared.  The address field must be
20066 	 * zero if the PMI bit is zero.
20067 	 */
20068 	bzero(&cdb, sizeof (cdb));
20069 	bzero(&ucmd_buf, sizeof (ucmd_buf));
20070 
20071 	capacity16_buf = kmem_zalloc(SD_CAPACITY_16_SIZE, KM_SLEEP);
20072 
20073 	ucmd_buf.uscsi_cdb	= (char *)&cdb;
20074 	ucmd_buf.uscsi_cdblen	= CDB_GROUP4;
20075 	ucmd_buf.uscsi_bufaddr	= (caddr_t)capacity16_buf;
20076 	ucmd_buf.uscsi_buflen	= SD_CAPACITY_16_SIZE;
20077 	ucmd_buf.uscsi_rqbuf	= (caddr_t)&sense_buf;
20078 	ucmd_buf.uscsi_rqlen	= sizeof (sense_buf);
20079 	ucmd_buf.uscsi_flags	= USCSI_RQENABLE | USCSI_READ | USCSI_SILENT;
20080 	ucmd_buf.uscsi_timeout	= 60;
20081 
20082 	/*
20083 	 * Read Capacity (16) is a Service Action In command.  One
20084 	 * command byte (0x9E) is overloaded for multiple operations,
20085 	 * with the second CDB byte specifying the desired operation
20086 	 */
20087 	cdb.scc_cmd = SCMD_SVC_ACTION_IN_G4;
20088 	cdb.cdb_opaque[1] = SSVC_ACTION_READ_CAPACITY_G4;
20089 
20090 	/*
20091 	 * Fill in allocation length field
20092 	 */
20093 	FORMG4COUNT(&cdb, ucmd_buf.uscsi_buflen);
20094 
20095 	status = sd_ssc_send(ssc, &ucmd_buf, FKIOCTL,
20096 	    UIO_SYSSPACE, path_flag);
20097 
20098 	switch (status) {
20099 	case 0:
20100 		/* Return failure if we did not get valid capacity data. */
20101 		if (ucmd_buf.uscsi_resid > 20) {
20102 			sd_ssc_set_info(ssc, SSC_FLAGS_INVALID_DATA, -1,
20103 			    "sd_send_scsi_READ_CAPACITY_16 received invalid "
20104 			    "capacity data");
20105 			kmem_free(capacity16_buf, SD_CAPACITY_16_SIZE);
20106 			return (EIO);
20107 		}
20108 
20109 		/*
20110 		 * Read capacity and block size from the READ CAPACITY 10 data.
20111 		 * This data may be adjusted later due to device specific
20112 		 * issues.
20113 		 *
20114 		 * According to the SCSI spec, the READ CAPACITY 10
20115 		 * command returns the following:
20116 		 *
20117 		 *  bytes 0-7: Maximum logical block address available.
20118 		 *		(MSB in byte:0 & LSB in byte:7)
20119 		 *
20120 		 *  bytes 8-11: Block length in bytes
20121 		 *		(MSB in byte:8 & LSB in byte:11)
20122 		 *
20123 		 *  byte 13: LOGICAL BLOCKS PER PHYSICAL BLOCK EXPONENT
20124 		 */
20125 		capacity = BE_64(capacity16_buf[0]);
20126 		lbasize = BE_32(*(uint32_t *)&capacity16_buf[1]);
20127 		lbpb_exp = (BE_64(capacity16_buf[1]) >> 40) & 0x0f;
20128 
20129 		pbsize = lbasize << lbpb_exp;
20130 
20131 		/*
20132 		 * Done with capacity16_buf
20133 		 */
20134 		kmem_free(capacity16_buf, SD_CAPACITY_16_SIZE);
20135 
20136 		/*
20137 		 * if the reported capacity is set to all 0xf's, then
20138 		 * this disk is too large.  This could only happen with
20139 		 * a device that supports LBAs larger than 64 bits which
20140 		 * are not defined by any current T10 standards.
20141 		 */
20142 		if (capacity == 0xffffffffffffffff) {
20143 			sd_ssc_set_info(ssc, SSC_FLAGS_INVALID_DATA, -1,
20144 			    "disk is too large");
20145 			return (EIO);
20146 		}
20147 		break;	/* Success! */
20148 	case EIO:
20149 		switch (ucmd_buf.uscsi_status) {
20150 		case STATUS_RESERVATION_CONFLICT:
20151 			status = EACCES;
20152 			break;
20153 		case STATUS_CHECK:
20154 			/*
20155 			 * Check condition; look for ASC/ASCQ of 0x04/0x01
20156 			 * (LOGICAL UNIT IS IN PROCESS OF BECOMING READY)
20157 			 */
20158 			if ((ucmd_buf.uscsi_rqstatus == STATUS_GOOD) &&
20159 			    (scsi_sense_asc((uint8_t *)&sense_buf) == 0x04) &&
20160 			    (scsi_sense_ascq((uint8_t *)&sense_buf) == 0x01)) {
20161 				kmem_free(capacity16_buf, SD_CAPACITY_16_SIZE);
20162 				return (EAGAIN);
20163 			}
20164 			break;
20165 		default:
20166 			break;
20167 		}
20168 		/* FALLTHRU */
20169 	default:
20170 		kmem_free(capacity16_buf, SD_CAPACITY_16_SIZE);
20171 		return (status);
20172 	}
20173 
20174 	*capp = capacity;
20175 	*lbap = lbasize;
20176 	*psp = pbsize;
20177 
20178 	SD_TRACE(SD_LOG_IO, un, "sd_send_scsi_READ_CAPACITY_16: "
20179 	    "capacity:0x%llx  lbasize:0x%x, pbsize: 0x%x\n",
20180 	    capacity, lbasize, pbsize);
20181 
20182 	return (0);
20183 }
20184 
20185 
20186 /*
20187  *    Function: sd_send_scsi_START_STOP_UNIT
20188  *
20189  * Description: Issue a scsi START STOP UNIT command to the target.
20190  *
20191  *   Arguments: ssc    - ssc contatins pointer to driver soft state (unit)
20192  *                       structure for this target.
20193  *      pc_flag - SD_POWER_CONDITION
20194  *                SD_START_STOP
20195  *		flag  - SD_TARGET_START
20196  *			SD_TARGET_STOP
20197  *			SD_TARGET_EJECT
20198  *		path_flag - SD_PATH_DIRECT to use the USCSI "direct" chain and
20199  *			the normal command waitq, or SD_PATH_DIRECT_PRIORITY
20200  *			to use the USCSI "direct" chain and bypass the normal
20201  *			command waitq. SD_PATH_DIRECT_PRIORITY is used when this
20202  *			command is issued as part of an error recovery action.
20203  *
20204  * Return Code: 0   - Success
20205  *		EIO - IO error
20206  *		EACCES - Reservation conflict detected
20207  *		ENXIO  - Not Ready, medium not present
20208  *		errno return code from sd_ssc_send()
20209  *
20210  *     Context: Can sleep.
20211  */
20212 
20213 static int
20214 sd_send_scsi_START_STOP_UNIT(sd_ssc_t *ssc, int pc_flag, int flag,
20215     int path_flag)
20216 {
20217 	struct	scsi_extended_sense	sense_buf;
20218 	union scsi_cdb		cdb;
20219 	struct uscsi_cmd	ucmd_buf;
20220 	int			status;
20221 	struct sd_lun		*un;
20222 
20223 	ASSERT(ssc != NULL);
20224 	un = ssc->ssc_un;
20225 	ASSERT(un != NULL);
20226 	ASSERT(!mutex_owned(SD_MUTEX(un)));
20227 
20228 	SD_TRACE(SD_LOG_IO, un,
20229 	    "sd_send_scsi_START_STOP_UNIT: entry: un:0x%p\n", un);
20230 
20231 	if (un->un_f_check_start_stop &&
20232 	    ((pc_flag == SD_START_STOP) && (flag != SD_TARGET_EJECT)) &&
20233 	    (un->un_f_start_stop_supported != TRUE)) {
20234 		return (0);
20235 	}
20236 
20237 	/*
20238 	 * If we are performing an eject operation and
20239 	 * we receive any command other than SD_TARGET_EJECT
20240 	 * we should immediately return.
20241 	 */
20242 	if (flag != SD_TARGET_EJECT) {
20243 		mutex_enter(SD_MUTEX(un));
20244 		if (un->un_f_ejecting == TRUE) {
20245 			mutex_exit(SD_MUTEX(un));
20246 			return (EAGAIN);
20247 		}
20248 		mutex_exit(SD_MUTEX(un));
20249 	}
20250 
20251 	bzero(&cdb, sizeof (cdb));
20252 	bzero(&ucmd_buf, sizeof (ucmd_buf));
20253 	bzero(&sense_buf, sizeof (struct scsi_extended_sense));
20254 
20255 	cdb.scc_cmd = SCMD_START_STOP;
20256 	cdb.cdb_opaque[4] = (pc_flag == SD_POWER_CONDITION) ?
20257 	    (uchar_t)(flag << 4) : (uchar_t)flag;
20258 
20259 	ucmd_buf.uscsi_cdb	= (char *)&cdb;
20260 	ucmd_buf.uscsi_cdblen	= CDB_GROUP0;
20261 	ucmd_buf.uscsi_bufaddr	= NULL;
20262 	ucmd_buf.uscsi_buflen	= 0;
20263 	ucmd_buf.uscsi_rqbuf	= (caddr_t)&sense_buf;
20264 	ucmd_buf.uscsi_rqlen	= sizeof (struct scsi_extended_sense);
20265 	ucmd_buf.uscsi_flags	= USCSI_RQENABLE | USCSI_SILENT;
20266 	ucmd_buf.uscsi_timeout	= 200;
20267 
20268 	status = sd_ssc_send(ssc, &ucmd_buf, FKIOCTL,
20269 	    UIO_SYSSPACE, path_flag);
20270 
20271 	switch (status) {
20272 	case 0:
20273 		sd_ssc_assessment(ssc, SD_FMT_STANDARD);
20274 		break;	/* Success! */
20275 	case EIO:
20276 		switch (ucmd_buf.uscsi_status) {
20277 		case STATUS_RESERVATION_CONFLICT:
20278 			status = EACCES;
20279 			break;
20280 		case STATUS_CHECK:
20281 			if (ucmd_buf.uscsi_rqstatus == STATUS_GOOD) {
20282 				switch (scsi_sense_key(
20283 				    (uint8_t *)&sense_buf)) {
20284 				case KEY_ILLEGAL_REQUEST:
20285 					status = ENOTSUP;
20286 					break;
20287 				case KEY_NOT_READY:
20288 					if (scsi_sense_asc(
20289 					    (uint8_t *)&sense_buf)
20290 					    == 0x3A) {
20291 						status = ENXIO;
20292 					}
20293 					break;
20294 				default:
20295 					break;
20296 				}
20297 			}
20298 			break;
20299 		default:
20300 			break;
20301 		}
20302 		break;
20303 	default:
20304 		break;
20305 	}
20306 
20307 	SD_TRACE(SD_LOG_IO, un, "sd_send_scsi_START_STOP_UNIT: exit\n");
20308 
20309 	return (status);
20310 }
20311 
20312 
20313 /*
20314  *    Function: sd_start_stop_unit_callback
20315  *
20316  * Description: timeout(9F) callback to begin recovery process for a
20317  *		device that has spun down.
20318  *
20319  *   Arguments: arg - pointer to associated softstate struct.
20320  *
20321  *     Context: Executes in a timeout(9F) thread context
20322  */
20323 
20324 static void
20325 sd_start_stop_unit_callback(void *arg)
20326 {
20327 	struct sd_lun	*un = arg;
20328 	ASSERT(un != NULL);
20329 	ASSERT(!mutex_owned(SD_MUTEX(un)));
20330 
20331 	SD_TRACE(SD_LOG_IO, un, "sd_start_stop_unit_callback: entry\n");
20332 
20333 	(void) taskq_dispatch(sd_tq, sd_start_stop_unit_task, un, KM_NOSLEEP);
20334 }
20335 
20336 
20337 /*
20338  *    Function: sd_start_stop_unit_task
20339  *
20340  * Description: Recovery procedure when a drive is spun down.
20341  *
20342  *   Arguments: arg - pointer to associated softstate struct.
20343  *
20344  *     Context: Executes in a taskq() thread context
20345  */
20346 
20347 static void
20348 sd_start_stop_unit_task(void *arg)
20349 {
20350 	struct sd_lun	*un = arg;
20351 	sd_ssc_t	*ssc;
20352 	int		power_level;
20353 	int		rval;
20354 
20355 	ASSERT(un != NULL);
20356 	ASSERT(!mutex_owned(SD_MUTEX(un)));
20357 
20358 	SD_TRACE(SD_LOG_IO, un, "sd_start_stop_unit_task: entry\n");
20359 
20360 	/*
20361 	 * Some unformatted drives report not ready error, no need to
20362 	 * restart if format has been initiated.
20363 	 */
20364 	mutex_enter(SD_MUTEX(un));
20365 	if (un->un_f_format_in_progress == TRUE) {
20366 		mutex_exit(SD_MUTEX(un));
20367 		return;
20368 	}
20369 	mutex_exit(SD_MUTEX(un));
20370 
20371 	ssc = sd_ssc_init(un);
20372 	/*
20373 	 * When a START STOP command is issued from here, it is part of a
20374 	 * failure recovery operation and must be issued before any other
20375 	 * commands, including any pending retries. Thus it must be sent
20376 	 * using SD_PATH_DIRECT_PRIORITY. It doesn't matter if the spin up
20377 	 * succeeds or not, we will start I/O after the attempt.
20378 	 * If power condition is supported and the current power level
20379 	 * is capable of performing I/O, we should set the power condition
20380 	 * to that level. Otherwise, set the power condition to ACTIVE.
20381 	 */
20382 	if (un->un_f_power_condition_supported) {
20383 		mutex_enter(SD_MUTEX(un));
20384 		ASSERT(SD_PM_IS_LEVEL_VALID(un, un->un_power_level));
20385 		power_level = sd_pwr_pc.ran_perf[un->un_power_level]
20386 		    > 0 ? un->un_power_level : SD_SPINDLE_ACTIVE;
20387 		mutex_exit(SD_MUTEX(un));
20388 		rval = sd_send_scsi_START_STOP_UNIT(ssc, SD_POWER_CONDITION,
20389 		    sd_pl2pc[power_level], SD_PATH_DIRECT_PRIORITY);
20390 	} else {
20391 		rval = sd_send_scsi_START_STOP_UNIT(ssc, SD_START_STOP,
20392 		    SD_TARGET_START, SD_PATH_DIRECT_PRIORITY);
20393 	}
20394 
20395 	if (rval != 0)
20396 		sd_ssc_assessment(ssc, SD_FMT_IGNORE);
20397 	sd_ssc_fini(ssc);
20398 	/*
20399 	 * The above call blocks until the START_STOP_UNIT command completes.
20400 	 * Now that it has completed, we must re-try the original IO that
20401 	 * received the NOT READY condition in the first place. There are
20402 	 * three possible conditions here:
20403 	 *
20404 	 *  (1) The original IO is on un_retry_bp.
20405 	 *  (2) The original IO is on the regular wait queue, and un_retry_bp
20406 	 *	is NULL.
20407 	 *  (3) The original IO is on the regular wait queue, and un_retry_bp
20408 	 *	points to some other, unrelated bp.
20409 	 *
20410 	 * For each case, we must call sd_start_cmds() with un_retry_bp
20411 	 * as the argument. If un_retry_bp is NULL, this will initiate
20412 	 * processing of the regular wait queue.  If un_retry_bp is not NULL,
20413 	 * then this will process the bp on un_retry_bp. That may or may not
20414 	 * be the original IO, but that does not matter: the important thing
20415 	 * is to keep the IO processing going at this point.
20416 	 *
20417 	 * Note: This is a very specific error recovery sequence associated
20418 	 * with a drive that is not spun up. We attempt a START_STOP_UNIT and
20419 	 * serialize the I/O with completion of the spin-up.
20420 	 */
20421 	mutex_enter(SD_MUTEX(un));
20422 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
20423 	    "sd_start_stop_unit_task: un:0x%p starting bp:0x%p\n",
20424 	    un, un->un_retry_bp);
20425 	un->un_startstop_timeid = NULL;	/* Timeout is no longer pending */
20426 	sd_start_cmds(un, un->un_retry_bp);
20427 	mutex_exit(SD_MUTEX(un));
20428 
20429 	SD_TRACE(SD_LOG_IO, un, "sd_start_stop_unit_task: exit\n");
20430 }
20431 
20432 
20433 /*
20434  *    Function: sd_send_scsi_INQUIRY
20435  *
20436  * Description: Issue the scsi INQUIRY command.
20437  *
20438  *   Arguments: ssc   - ssc contains pointer to driver soft state (unit)
20439  *                      structure for this target.
20440  *		bufaddr
20441  *		buflen
20442  *		evpd
20443  *		page_code
20444  *		page_length
20445  *
20446  * Return Code: 0   - Success
20447  *		errno return code from sd_ssc_send()
20448  *
20449  *     Context: Can sleep. Does not return until command is completed.
20450  */
20451 
20452 static int
20453 sd_send_scsi_INQUIRY(sd_ssc_t *ssc, uchar_t *bufaddr, size_t buflen,
20454 	uchar_t evpd, uchar_t page_code, size_t *residp)
20455 {
20456 	union scsi_cdb		cdb;
20457 	struct uscsi_cmd	ucmd_buf;
20458 	int			status;
20459 	struct sd_lun		*un;
20460 
20461 	ASSERT(ssc != NULL);
20462 	un = ssc->ssc_un;
20463 	ASSERT(un != NULL);
20464 	ASSERT(!mutex_owned(SD_MUTEX(un)));
20465 	ASSERT(bufaddr != NULL);
20466 
20467 	SD_TRACE(SD_LOG_IO, un, "sd_send_scsi_INQUIRY: entry: un:0x%p\n", un);
20468 
20469 	bzero(&cdb, sizeof (cdb));
20470 	bzero(&ucmd_buf, sizeof (ucmd_buf));
20471 	bzero(bufaddr, buflen);
20472 
20473 	cdb.scc_cmd = SCMD_INQUIRY;
20474 	cdb.cdb_opaque[1] = evpd;
20475 	cdb.cdb_opaque[2] = page_code;
20476 	FORMG0COUNT(&cdb, buflen);
20477 
20478 	ucmd_buf.uscsi_cdb	= (char *)&cdb;
20479 	ucmd_buf.uscsi_cdblen	= CDB_GROUP0;
20480 	ucmd_buf.uscsi_bufaddr	= (caddr_t)bufaddr;
20481 	ucmd_buf.uscsi_buflen	= buflen;
20482 	ucmd_buf.uscsi_rqbuf	= NULL;
20483 	ucmd_buf.uscsi_rqlen	= 0;
20484 	ucmd_buf.uscsi_flags	= USCSI_READ | USCSI_SILENT;
20485 	ucmd_buf.uscsi_timeout	= 200;	/* Excessive legacy value */
20486 
20487 	status = sd_ssc_send(ssc, &ucmd_buf, FKIOCTL,
20488 	    UIO_SYSSPACE, SD_PATH_DIRECT);
20489 
20490 	/*
20491 	 * Only handle status == 0, the upper-level caller
20492 	 * will put different assessment based on the context.
20493 	 */
20494 	if (status == 0)
20495 		sd_ssc_assessment(ssc, SD_FMT_STANDARD);
20496 
20497 	if ((status == 0) && (residp != NULL)) {
20498 		*residp = ucmd_buf.uscsi_resid;
20499 	}
20500 
20501 	SD_TRACE(SD_LOG_IO, un, "sd_send_scsi_INQUIRY: exit\n");
20502 
20503 	return (status);
20504 }
20505 
20506 
20507 /*
20508  *    Function: sd_send_scsi_TEST_UNIT_READY
20509  *
20510  * Description: Issue the scsi TEST UNIT READY command.
20511  *		This routine can be told to set the flag USCSI_DIAGNOSE to
20512  *		prevent retrying failed commands. Use this when the intent
20513  *		is either to check for device readiness, to clear a Unit
20514  *		Attention, or to clear any outstanding sense data.
20515  *		However under specific conditions the expected behavior
20516  *		is for retries to bring a device ready, so use the flag
20517  *		with caution.
20518  *
20519  *   Arguments: ssc   - ssc contains pointer to driver soft state (unit)
20520  *                      structure for this target.
20521  *		flag:   SD_CHECK_FOR_MEDIA: return ENXIO if no media present
20522  *			SD_DONT_RETRY_TUR: include uscsi flag USCSI_DIAGNOSE.
20523  *			0: dont check for media present, do retries on cmd.
20524  *
20525  * Return Code: 0   - Success
20526  *		EIO - IO error
20527  *		EACCES - Reservation conflict detected
20528  *		ENXIO  - Not Ready, medium not present
20529  *		errno return code from sd_ssc_send()
20530  *
20531  *     Context: Can sleep. Does not return until command is completed.
20532  */
20533 
20534 static int
20535 sd_send_scsi_TEST_UNIT_READY(sd_ssc_t *ssc, int flag)
20536 {
20537 	struct	scsi_extended_sense	sense_buf;
20538 	union scsi_cdb		cdb;
20539 	struct uscsi_cmd	ucmd_buf;
20540 	int			status;
20541 	struct sd_lun		*un;
20542 
20543 	ASSERT(ssc != NULL);
20544 	un = ssc->ssc_un;
20545 	ASSERT(un != NULL);
20546 	ASSERT(!mutex_owned(SD_MUTEX(un)));
20547 
20548 	SD_TRACE(SD_LOG_IO, un,
20549 	    "sd_send_scsi_TEST_UNIT_READY: entry: un:0x%p\n", un);
20550 
20551 	/*
20552 	 * Some Seagate elite1 TQ devices get hung with disconnect/reconnect
20553 	 * timeouts when they receive a TUR and the queue is not empty. Check
20554 	 * the configuration flag set during attach (indicating the drive has
20555 	 * this firmware bug) and un_ncmds_in_transport before issuing the
20556 	 * TUR. If there are
20557 	 * pending commands return success, this is a bit arbitrary but is ok
20558 	 * for non-removables (i.e. the eliteI disks) and non-clustering
20559 	 * configurations.
20560 	 */
20561 	if (un->un_f_cfg_tur_check == TRUE) {
20562 		mutex_enter(SD_MUTEX(un));
20563 		if (un->un_ncmds_in_transport != 0) {
20564 			mutex_exit(SD_MUTEX(un));
20565 			return (0);
20566 		}
20567 		mutex_exit(SD_MUTEX(un));
20568 	}
20569 
20570 	bzero(&cdb, sizeof (cdb));
20571 	bzero(&ucmd_buf, sizeof (ucmd_buf));
20572 	bzero(&sense_buf, sizeof (struct scsi_extended_sense));
20573 
20574 	cdb.scc_cmd = SCMD_TEST_UNIT_READY;
20575 
20576 	ucmd_buf.uscsi_cdb	= (char *)&cdb;
20577 	ucmd_buf.uscsi_cdblen	= CDB_GROUP0;
20578 	ucmd_buf.uscsi_bufaddr	= NULL;
20579 	ucmd_buf.uscsi_buflen	= 0;
20580 	ucmd_buf.uscsi_rqbuf	= (caddr_t)&sense_buf;
20581 	ucmd_buf.uscsi_rqlen	= sizeof (struct scsi_extended_sense);
20582 	ucmd_buf.uscsi_flags	= USCSI_RQENABLE | USCSI_SILENT;
20583 
20584 	/* Use flag USCSI_DIAGNOSE to prevent retries if it fails. */
20585 	if ((flag & SD_DONT_RETRY_TUR) != 0) {
20586 		ucmd_buf.uscsi_flags |= USCSI_DIAGNOSE;
20587 	}
20588 	ucmd_buf.uscsi_timeout	= 60;
20589 
20590 	status = sd_ssc_send(ssc, &ucmd_buf, FKIOCTL,
20591 	    UIO_SYSSPACE, ((flag & SD_BYPASS_PM) ? SD_PATH_DIRECT :
20592 	    SD_PATH_STANDARD));
20593 
20594 	switch (status) {
20595 	case 0:
20596 		sd_ssc_assessment(ssc, SD_FMT_STANDARD);
20597 		break;	/* Success! */
20598 	case EIO:
20599 		switch (ucmd_buf.uscsi_status) {
20600 		case STATUS_RESERVATION_CONFLICT:
20601 			status = EACCES;
20602 			break;
20603 		case STATUS_CHECK:
20604 			if ((flag & SD_CHECK_FOR_MEDIA) == 0) {
20605 				break;
20606 			}
20607 			if ((ucmd_buf.uscsi_rqstatus == STATUS_GOOD) &&
20608 			    (scsi_sense_key((uint8_t *)&sense_buf) ==
20609 			    KEY_NOT_READY) &&
20610 			    (scsi_sense_asc((uint8_t *)&sense_buf) == 0x3A)) {
20611 				status = ENXIO;
20612 			}
20613 			break;
20614 		default:
20615 			break;
20616 		}
20617 		break;
20618 	default:
20619 		break;
20620 	}
20621 
20622 	SD_TRACE(SD_LOG_IO, un, "sd_send_scsi_TEST_UNIT_READY: exit\n");
20623 
20624 	return (status);
20625 }
20626 
20627 /*
20628  *    Function: sd_send_scsi_PERSISTENT_RESERVE_IN
20629  *
20630  * Description: Issue the scsi PERSISTENT RESERVE IN command.
20631  *
20632  *   Arguments: ssc   - ssc contains pointer to driver soft state (unit)
20633  *                      structure for this target.
20634  *
20635  * Return Code: 0   - Success
20636  *		EACCES
20637  *		ENOTSUP
20638  *		errno return code from sd_ssc_send()
20639  *
20640  *     Context: Can sleep. Does not return until command is completed.
20641  */
20642 
20643 static int
20644 sd_send_scsi_PERSISTENT_RESERVE_IN(sd_ssc_t *ssc, uchar_t  usr_cmd,
20645 	uint16_t data_len, uchar_t *data_bufp)
20646 {
20647 	struct scsi_extended_sense	sense_buf;
20648 	union scsi_cdb		cdb;
20649 	struct uscsi_cmd	ucmd_buf;
20650 	int			status;
20651 	int			no_caller_buf = FALSE;
20652 	struct sd_lun		*un;
20653 
20654 	ASSERT(ssc != NULL);
20655 	un = ssc->ssc_un;
20656 	ASSERT(un != NULL);
20657 	ASSERT(!mutex_owned(SD_MUTEX(un)));
20658 	ASSERT((usr_cmd == SD_READ_KEYS) || (usr_cmd == SD_READ_RESV));
20659 
20660 	SD_TRACE(SD_LOG_IO, un,
20661 	    "sd_send_scsi_PERSISTENT_RESERVE_IN: entry: un:0x%p\n", un);
20662 
20663 	bzero(&cdb, sizeof (cdb));
20664 	bzero(&ucmd_buf, sizeof (ucmd_buf));
20665 	bzero(&sense_buf, sizeof (struct scsi_extended_sense));
20666 	if (data_bufp == NULL) {
20667 		/* Allocate a default buf if the caller did not give one */
20668 		ASSERT(data_len == 0);
20669 		data_len  = MHIOC_RESV_KEY_SIZE;
20670 		data_bufp = kmem_zalloc(MHIOC_RESV_KEY_SIZE, KM_SLEEP);
20671 		no_caller_buf = TRUE;
20672 	}
20673 
20674 	cdb.scc_cmd = SCMD_PERSISTENT_RESERVE_IN;
20675 	cdb.cdb_opaque[1] = usr_cmd;
20676 	FORMG1COUNT(&cdb, data_len);
20677 
20678 	ucmd_buf.uscsi_cdb	= (char *)&cdb;
20679 	ucmd_buf.uscsi_cdblen	= CDB_GROUP1;
20680 	ucmd_buf.uscsi_bufaddr	= (caddr_t)data_bufp;
20681 	ucmd_buf.uscsi_buflen	= data_len;
20682 	ucmd_buf.uscsi_rqbuf	= (caddr_t)&sense_buf;
20683 	ucmd_buf.uscsi_rqlen	= sizeof (struct scsi_extended_sense);
20684 	ucmd_buf.uscsi_flags	= USCSI_RQENABLE | USCSI_READ | USCSI_SILENT;
20685 	ucmd_buf.uscsi_timeout	= 60;
20686 
20687 	status = sd_ssc_send(ssc, &ucmd_buf, FKIOCTL,
20688 	    UIO_SYSSPACE, SD_PATH_STANDARD);
20689 
20690 	switch (status) {
20691 	case 0:
20692 		sd_ssc_assessment(ssc, SD_FMT_STANDARD);
20693 
20694 		break;	/* Success! */
20695 	case EIO:
20696 		switch (ucmd_buf.uscsi_status) {
20697 		case STATUS_RESERVATION_CONFLICT:
20698 			status = EACCES;
20699 			break;
20700 		case STATUS_CHECK:
20701 			if ((ucmd_buf.uscsi_rqstatus == STATUS_GOOD) &&
20702 			    (scsi_sense_key((uint8_t *)&sense_buf) ==
20703 			    KEY_ILLEGAL_REQUEST)) {
20704 				status = ENOTSUP;
20705 			}
20706 			break;
20707 		default:
20708 			break;
20709 		}
20710 		break;
20711 	default:
20712 		break;
20713 	}
20714 
20715 	SD_TRACE(SD_LOG_IO, un, "sd_send_scsi_PERSISTENT_RESERVE_IN: exit\n");
20716 
20717 	if (no_caller_buf == TRUE) {
20718 		kmem_free(data_bufp, data_len);
20719 	}
20720 
20721 	return (status);
20722 }
20723 
20724 
20725 /*
20726  *    Function: sd_send_scsi_PERSISTENT_RESERVE_OUT
20727  *
20728  * Description: This routine is the driver entry point for handling CD-ROM
20729  *		multi-host persistent reservation requests (MHIOCGRP_INKEYS,
20730  *		MHIOCGRP_INRESV) by sending the SCSI-3 PROUT commands to the
20731  *		device.
20732  *
20733  *   Arguments: ssc  -  ssc contains un - pointer to soft state struct
20734  *                      for the target.
20735  *		usr_cmd SCSI-3 reservation facility command (one of
20736  *			SD_SCSI3_REGISTER, SD_SCSI3_RESERVE, SD_SCSI3_RELEASE,
20737  *			SD_SCSI3_PREEMPTANDABORT)
20738  *		usr_bufp - user provided pointer register, reserve descriptor or
20739  *			preempt and abort structure (mhioc_register_t,
20740  *                      mhioc_resv_desc_t, mhioc_preemptandabort_t)
20741  *
20742  * Return Code: 0   - Success
20743  *		EACCES
20744  *		ENOTSUP
20745  *		errno return code from sd_ssc_send()
20746  *
20747  *     Context: Can sleep. Does not return until command is completed.
20748  */
20749 
20750 static int
20751 sd_send_scsi_PERSISTENT_RESERVE_OUT(sd_ssc_t *ssc, uchar_t usr_cmd,
20752 	uchar_t	*usr_bufp)
20753 {
20754 	struct scsi_extended_sense	sense_buf;
20755 	union scsi_cdb		cdb;
20756 	struct uscsi_cmd	ucmd_buf;
20757 	int			status;
20758 	uchar_t			data_len = sizeof (sd_prout_t);
20759 	sd_prout_t		*prp;
20760 	struct sd_lun		*un;
20761 
20762 	ASSERT(ssc != NULL);
20763 	un = ssc->ssc_un;
20764 	ASSERT(un != NULL);
20765 	ASSERT(!mutex_owned(SD_MUTEX(un)));
20766 	ASSERT(data_len == 24);	/* required by scsi spec */
20767 
20768 	SD_TRACE(SD_LOG_IO, un,
20769 	    "sd_send_scsi_PERSISTENT_RESERVE_OUT: entry: un:0x%p\n", un);
20770 
20771 	if (usr_bufp == NULL) {
20772 		return (EINVAL);
20773 	}
20774 
20775 	bzero(&cdb, sizeof (cdb));
20776 	bzero(&ucmd_buf, sizeof (ucmd_buf));
20777 	bzero(&sense_buf, sizeof (struct scsi_extended_sense));
20778 	prp = kmem_zalloc(data_len, KM_SLEEP);
20779 
20780 	cdb.scc_cmd = SCMD_PERSISTENT_RESERVE_OUT;
20781 	cdb.cdb_opaque[1] = usr_cmd;
20782 	FORMG1COUNT(&cdb, data_len);
20783 
20784 	ucmd_buf.uscsi_cdb	= (char *)&cdb;
20785 	ucmd_buf.uscsi_cdblen	= CDB_GROUP1;
20786 	ucmd_buf.uscsi_bufaddr	= (caddr_t)prp;
20787 	ucmd_buf.uscsi_buflen	= data_len;
20788 	ucmd_buf.uscsi_rqbuf	= (caddr_t)&sense_buf;
20789 	ucmd_buf.uscsi_rqlen	= sizeof (struct scsi_extended_sense);
20790 	ucmd_buf.uscsi_flags	= USCSI_RQENABLE | USCSI_WRITE | USCSI_SILENT;
20791 	ucmd_buf.uscsi_timeout	= 60;
20792 
20793 	switch (usr_cmd) {
20794 	case SD_SCSI3_REGISTER: {
20795 		mhioc_register_t *ptr = (mhioc_register_t *)usr_bufp;
20796 
20797 		bcopy(ptr->oldkey.key, prp->res_key, MHIOC_RESV_KEY_SIZE);
20798 		bcopy(ptr->newkey.key, prp->service_key,
20799 		    MHIOC_RESV_KEY_SIZE);
20800 		prp->aptpl = ptr->aptpl;
20801 		break;
20802 	}
20803 	case SD_SCSI3_RESERVE:
20804 	case SD_SCSI3_RELEASE: {
20805 		mhioc_resv_desc_t *ptr = (mhioc_resv_desc_t *)usr_bufp;
20806 
20807 		bcopy(ptr->key.key, prp->res_key, MHIOC_RESV_KEY_SIZE);
20808 		prp->scope_address = BE_32(ptr->scope_specific_addr);
20809 		cdb.cdb_opaque[2] = ptr->type;
20810 		break;
20811 	}
20812 	case SD_SCSI3_PREEMPTANDABORT: {
20813 		mhioc_preemptandabort_t *ptr =
20814 		    (mhioc_preemptandabort_t *)usr_bufp;
20815 
20816 		bcopy(ptr->resvdesc.key.key, prp->res_key, MHIOC_RESV_KEY_SIZE);
20817 		bcopy(ptr->victim_key.key, prp->service_key,
20818 		    MHIOC_RESV_KEY_SIZE);
20819 		prp->scope_address = BE_32(ptr->resvdesc.scope_specific_addr);
20820 		cdb.cdb_opaque[2] = ptr->resvdesc.type;
20821 		ucmd_buf.uscsi_flags |= USCSI_HEAD;
20822 		break;
20823 	}
20824 	case SD_SCSI3_REGISTERANDIGNOREKEY:
20825 	{
20826 		mhioc_registerandignorekey_t *ptr;
20827 		ptr = (mhioc_registerandignorekey_t *)usr_bufp;
20828 		bcopy(ptr->newkey.key,
20829 		    prp->service_key, MHIOC_RESV_KEY_SIZE);
20830 		prp->aptpl = ptr->aptpl;
20831 		break;
20832 	}
20833 	default:
20834 		ASSERT(FALSE);
20835 		break;
20836 	}
20837 
20838 	status = sd_ssc_send(ssc, &ucmd_buf, FKIOCTL,
20839 	    UIO_SYSSPACE, SD_PATH_STANDARD);
20840 
20841 	switch (status) {
20842 	case 0:
20843 		sd_ssc_assessment(ssc, SD_FMT_STANDARD);
20844 		break;	/* Success! */
20845 	case EIO:
20846 		switch (ucmd_buf.uscsi_status) {
20847 		case STATUS_RESERVATION_CONFLICT:
20848 			status = EACCES;
20849 			break;
20850 		case STATUS_CHECK:
20851 			if ((ucmd_buf.uscsi_rqstatus == STATUS_GOOD) &&
20852 			    (scsi_sense_key((uint8_t *)&sense_buf) ==
20853 			    KEY_ILLEGAL_REQUEST)) {
20854 				status = ENOTSUP;
20855 			}
20856 			break;
20857 		default:
20858 			break;
20859 		}
20860 		break;
20861 	default:
20862 		break;
20863 	}
20864 
20865 	kmem_free(prp, data_len);
20866 	SD_TRACE(SD_LOG_IO, un, "sd_send_scsi_PERSISTENT_RESERVE_OUT: exit\n");
20867 	return (status);
20868 }
20869 
20870 
20871 /*
20872  *    Function: sd_send_scsi_SYNCHRONIZE_CACHE
20873  *
20874  * Description: Issues a scsi SYNCHRONIZE CACHE command to the target
20875  *
20876  *   Arguments: un - pointer to the target's soft state struct
20877  *              dkc - pointer to the callback structure
20878  *
20879  * Return Code: 0 - success
20880  *		errno-type error code
20881  *
20882  *     Context: kernel thread context only.
20883  *
20884  *  _______________________________________________________________
20885  * | dkc_flag &   | dkc_callback | DKIOCFLUSHWRITECACHE            |
20886  * |FLUSH_VOLATILE|              | operation                       |
20887  * |______________|______________|_________________________________|
20888  * | 0            | NULL         | Synchronous flush on both       |
20889  * |              |              | volatile and non-volatile cache |
20890  * |______________|______________|_________________________________|
20891  * | 1            | NULL         | Synchronous flush on volatile   |
20892  * |              |              | cache; disk drivers may suppress|
20893  * |              |              | flush if disk table indicates   |
20894  * |              |              | non-volatile cache              |
20895  * |______________|______________|_________________________________|
20896  * | 0            | !NULL        | Asynchronous flush on both      |
20897  * |              |              | volatile and non-volatile cache;|
20898  * |______________|______________|_________________________________|
20899  * | 1            | !NULL        | Asynchronous flush on volatile  |
20900  * |              |              | cache; disk drivers may suppress|
20901  * |              |              | flush if disk table indicates   |
20902  * |              |              | non-volatile cache              |
20903  * |______________|______________|_________________________________|
20904  *
20905  */
20906 
20907 static int
20908 sd_send_scsi_SYNCHRONIZE_CACHE(struct sd_lun *un, struct dk_callback *dkc)
20909 {
20910 	struct sd_uscsi_info	*uip;
20911 	struct uscsi_cmd	*uscmd;
20912 	union scsi_cdb		*cdb;
20913 	struct buf		*bp;
20914 	int			rval = 0;
20915 	int			is_async;
20916 
20917 	SD_TRACE(SD_LOG_IO, un,
20918 	    "sd_send_scsi_SYNCHRONIZE_CACHE: entry: un:0x%p\n", un);
20919 
20920 	ASSERT(un != NULL);
20921 	ASSERT(!mutex_owned(SD_MUTEX(un)));
20922 
20923 	if (dkc == NULL || dkc->dkc_callback == NULL) {
20924 		is_async = FALSE;
20925 	} else {
20926 		is_async = TRUE;
20927 	}
20928 
20929 	mutex_enter(SD_MUTEX(un));
20930 	/* check whether cache flush should be suppressed */
20931 	if (un->un_f_suppress_cache_flush == TRUE) {
20932 		mutex_exit(SD_MUTEX(un));
20933 		/*
20934 		 * suppress the cache flush if the device is told to do
20935 		 * so by sd.conf or disk table
20936 		 */
20937 		SD_TRACE(SD_LOG_IO, un, "sd_send_scsi_SYNCHRONIZE_CACHE: \
20938 		    skip the cache flush since suppress_cache_flush is %d!\n",
20939 		    un->un_f_suppress_cache_flush);
20940 
20941 		if (is_async == TRUE) {
20942 			/* invoke callback for asynchronous flush */
20943 			(*dkc->dkc_callback)(dkc->dkc_cookie, 0);
20944 		}
20945 		return (rval);
20946 	}
20947 	mutex_exit(SD_MUTEX(un));
20948 
20949 	/*
20950 	 * check dkc_flag & FLUSH_VOLATILE so SYNC_NV bit can be
20951 	 * set properly
20952 	 */
20953 	cdb = kmem_zalloc(CDB_GROUP1, KM_SLEEP);
20954 	cdb->scc_cmd = SCMD_SYNCHRONIZE_CACHE;
20955 
20956 	mutex_enter(SD_MUTEX(un));
20957 	if (dkc != NULL && un->un_f_sync_nv_supported &&
20958 	    (dkc->dkc_flag & FLUSH_VOLATILE)) {
20959 		/*
20960 		 * if the device supports SYNC_NV bit, turn on
20961 		 * the SYNC_NV bit to only flush volatile cache
20962 		 */
20963 		cdb->cdb_un.tag |= SD_SYNC_NV_BIT;
20964 	}
20965 	mutex_exit(SD_MUTEX(un));
20966 
20967 	/*
20968 	 * First get some memory for the uscsi_cmd struct and cdb
20969 	 * and initialize for SYNCHRONIZE_CACHE cmd.
20970 	 */
20971 	uscmd = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
20972 	uscmd->uscsi_cdblen = CDB_GROUP1;
20973 	uscmd->uscsi_cdb = (caddr_t)cdb;
20974 	uscmd->uscsi_bufaddr = NULL;
20975 	uscmd->uscsi_buflen = 0;
20976 	uscmd->uscsi_rqbuf = kmem_zalloc(SENSE_LENGTH, KM_SLEEP);
20977 	uscmd->uscsi_rqlen = SENSE_LENGTH;
20978 	uscmd->uscsi_rqresid = SENSE_LENGTH;
20979 	uscmd->uscsi_flags = USCSI_RQENABLE | USCSI_SILENT;
20980 	uscmd->uscsi_timeout = sd_io_time;
20981 
20982 	/*
20983 	 * Allocate an sd_uscsi_info struct and fill it with the info
20984 	 * needed by sd_initpkt_for_uscsi().  Then put the pointer into
20985 	 * b_private in the buf for sd_initpkt_for_uscsi().  Note that
20986 	 * since we allocate the buf here in this function, we do not
20987 	 * need to preserve the prior contents of b_private.
20988 	 * The sd_uscsi_info struct is also used by sd_uscsi_strategy()
20989 	 */
20990 	uip = kmem_zalloc(sizeof (struct sd_uscsi_info), KM_SLEEP);
20991 	uip->ui_flags = SD_PATH_DIRECT;
20992 	uip->ui_cmdp  = uscmd;
20993 
20994 	bp = getrbuf(KM_SLEEP);
20995 	bp->b_private = uip;
20996 
20997 	/*
20998 	 * Setup buffer to carry uscsi request.
20999 	 */
21000 	bp->b_flags  = B_BUSY;
21001 	bp->b_bcount = 0;
21002 	bp->b_blkno  = 0;
21003 
21004 	if (is_async == TRUE) {
21005 		bp->b_iodone = sd_send_scsi_SYNCHRONIZE_CACHE_biodone;
21006 		uip->ui_dkc = *dkc;
21007 	}
21008 
21009 	bp->b_edev = SD_GET_DEV(un);
21010 	bp->b_dev = cmpdev(bp->b_edev);	/* maybe unnecessary? */
21011 
21012 	/*
21013 	 * Unset un_f_sync_cache_required flag
21014 	 */
21015 	mutex_enter(SD_MUTEX(un));
21016 	un->un_f_sync_cache_required = FALSE;
21017 	mutex_exit(SD_MUTEX(un));
21018 
21019 	(void) sd_uscsi_strategy(bp);
21020 
21021 	/*
21022 	 * If synchronous request, wait for completion
21023 	 * If async just return and let b_iodone callback
21024 	 * cleanup.
21025 	 * NOTE: On return, u_ncmds_in_driver will be decremented,
21026 	 * but it was also incremented in sd_uscsi_strategy(), so
21027 	 * we should be ok.
21028 	 */
21029 	if (is_async == FALSE) {
21030 		(void) biowait(bp);
21031 		rval = sd_send_scsi_SYNCHRONIZE_CACHE_biodone(bp);
21032 	}
21033 
21034 	return (rval);
21035 }
21036 
21037 
21038 static int
21039 sd_send_scsi_SYNCHRONIZE_CACHE_biodone(struct buf *bp)
21040 {
21041 	struct sd_uscsi_info *uip;
21042 	struct uscsi_cmd *uscmd;
21043 	uint8_t *sense_buf;
21044 	struct sd_lun *un;
21045 	int status;
21046 	union scsi_cdb *cdb;
21047 
21048 	uip = (struct sd_uscsi_info *)(bp->b_private);
21049 	ASSERT(uip != NULL);
21050 
21051 	uscmd = uip->ui_cmdp;
21052 	ASSERT(uscmd != NULL);
21053 
21054 	sense_buf = (uint8_t *)uscmd->uscsi_rqbuf;
21055 	ASSERT(sense_buf != NULL);
21056 
21057 	un = ddi_get_soft_state(sd_state, SD_GET_INSTANCE_FROM_BUF(bp));
21058 	ASSERT(un != NULL);
21059 
21060 	cdb = (union scsi_cdb *)uscmd->uscsi_cdb;
21061 
21062 	status = geterror(bp);
21063 	switch (status) {
21064 	case 0:
21065 		break;	/* Success! */
21066 	case EIO:
21067 		switch (uscmd->uscsi_status) {
21068 		case STATUS_RESERVATION_CONFLICT:
21069 			/* Ignore reservation conflict */
21070 			status = 0;
21071 			goto done;
21072 
21073 		case STATUS_CHECK:
21074 			if ((uscmd->uscsi_rqstatus == STATUS_GOOD) &&
21075 			    (scsi_sense_key(sense_buf) ==
21076 			    KEY_ILLEGAL_REQUEST)) {
21077 				/* Ignore Illegal Request error */
21078 				if (cdb->cdb_un.tag&SD_SYNC_NV_BIT) {
21079 					mutex_enter(SD_MUTEX(un));
21080 					un->un_f_sync_nv_supported = FALSE;
21081 					mutex_exit(SD_MUTEX(un));
21082 					status = 0;
21083 					SD_TRACE(SD_LOG_IO, un,
21084 					    "un_f_sync_nv_supported \
21085 					    is set to false.\n");
21086 					goto done;
21087 				}
21088 
21089 				mutex_enter(SD_MUTEX(un));
21090 				un->un_f_sync_cache_supported = FALSE;
21091 				mutex_exit(SD_MUTEX(un));
21092 				SD_TRACE(SD_LOG_IO, un,
21093 				    "sd_send_scsi_SYNCHRONIZE_CACHE_biodone: \
21094 				    un_f_sync_cache_supported set to false \
21095 				    with asc = %x, ascq = %x\n",
21096 				    scsi_sense_asc(sense_buf),
21097 				    scsi_sense_ascq(sense_buf));
21098 				status = ENOTSUP;
21099 				goto done;
21100 			}
21101 			break;
21102 		default:
21103 			break;
21104 		}
21105 		/* FALLTHRU */
21106 	default:
21107 		/*
21108 		 * Turn on the un_f_sync_cache_required flag
21109 		 * since the SYNC CACHE command failed
21110 		 */
21111 		mutex_enter(SD_MUTEX(un));
21112 		un->un_f_sync_cache_required = TRUE;
21113 		mutex_exit(SD_MUTEX(un));
21114 
21115 		/*
21116 		 * Don't log an error message if this device
21117 		 * has removable media.
21118 		 */
21119 		if (!un->un_f_has_removable_media) {
21120 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
21121 			    "SYNCHRONIZE CACHE command failed (%d)\n", status);
21122 		}
21123 		break;
21124 	}
21125 
21126 done:
21127 	if (uip->ui_dkc.dkc_callback != NULL) {
21128 		(*uip->ui_dkc.dkc_callback)(uip->ui_dkc.dkc_cookie, status);
21129 	}
21130 
21131 	ASSERT((bp->b_flags & B_REMAPPED) == 0);
21132 	freerbuf(bp);
21133 	kmem_free(uip, sizeof (struct sd_uscsi_info));
21134 	kmem_free(uscmd->uscsi_rqbuf, SENSE_LENGTH);
21135 	kmem_free(uscmd->uscsi_cdb, (size_t)uscmd->uscsi_cdblen);
21136 	kmem_free(uscmd, sizeof (struct uscsi_cmd));
21137 
21138 	return (status);
21139 }
21140 
21141 
21142 /*
21143  *    Function: sd_send_scsi_GET_CONFIGURATION
21144  *
21145  * Description: Issues the get configuration command to the device.
21146  *		Called from sd_check_for_writable_cd & sd_get_media_info
21147  *		caller needs to ensure that buflen = SD_PROFILE_HEADER_LEN
21148  *   Arguments: ssc
21149  *		ucmdbuf
21150  *		rqbuf
21151  *		rqbuflen
21152  *		bufaddr
21153  *		buflen
21154  *		path_flag
21155  *
21156  * Return Code: 0   - Success
21157  *		errno return code from sd_ssc_send()
21158  *
21159  *     Context: Can sleep. Does not return until command is completed.
21160  *
21161  */
21162 
21163 static int
21164 sd_send_scsi_GET_CONFIGURATION(sd_ssc_t *ssc, struct uscsi_cmd *ucmdbuf,
21165 	uchar_t *rqbuf, uint_t rqbuflen, uchar_t *bufaddr, uint_t buflen,
21166 	int path_flag)
21167 {
21168 	char	cdb[CDB_GROUP1];
21169 	int	status;
21170 	struct sd_lun	*un;
21171 
21172 	ASSERT(ssc != NULL);
21173 	un = ssc->ssc_un;
21174 	ASSERT(un != NULL);
21175 	ASSERT(!mutex_owned(SD_MUTEX(un)));
21176 	ASSERT(bufaddr != NULL);
21177 	ASSERT(ucmdbuf != NULL);
21178 	ASSERT(rqbuf != NULL);
21179 
21180 	SD_TRACE(SD_LOG_IO, un,
21181 	    "sd_send_scsi_GET_CONFIGURATION: entry: un:0x%p\n", un);
21182 
21183 	bzero(cdb, sizeof (cdb));
21184 	bzero(ucmdbuf, sizeof (struct uscsi_cmd));
21185 	bzero(rqbuf, rqbuflen);
21186 	bzero(bufaddr, buflen);
21187 
21188 	/*
21189 	 * Set up cdb field for the get configuration command.
21190 	 */
21191 	cdb[0] = SCMD_GET_CONFIGURATION;
21192 	cdb[1] = 0x02;  /* Requested Type */
21193 	cdb[8] = SD_PROFILE_HEADER_LEN;
21194 	ucmdbuf->uscsi_cdb = cdb;
21195 	ucmdbuf->uscsi_cdblen = CDB_GROUP1;
21196 	ucmdbuf->uscsi_bufaddr = (caddr_t)bufaddr;
21197 	ucmdbuf->uscsi_buflen = buflen;
21198 	ucmdbuf->uscsi_timeout = sd_io_time;
21199 	ucmdbuf->uscsi_rqbuf = (caddr_t)rqbuf;
21200 	ucmdbuf->uscsi_rqlen = rqbuflen;
21201 	ucmdbuf->uscsi_flags = USCSI_RQENABLE|USCSI_SILENT|USCSI_READ;
21202 
21203 	status = sd_ssc_send(ssc, ucmdbuf, FKIOCTL,
21204 	    UIO_SYSSPACE, path_flag);
21205 
21206 	switch (status) {
21207 	case 0:
21208 		sd_ssc_assessment(ssc, SD_FMT_STANDARD);
21209 		break;  /* Success! */
21210 	case EIO:
21211 		switch (ucmdbuf->uscsi_status) {
21212 		case STATUS_RESERVATION_CONFLICT:
21213 			status = EACCES;
21214 			break;
21215 		default:
21216 			break;
21217 		}
21218 		break;
21219 	default:
21220 		break;
21221 	}
21222 
21223 	if (status == 0) {
21224 		SD_DUMP_MEMORY(un, SD_LOG_IO,
21225 		    "sd_send_scsi_GET_CONFIGURATION: data",
21226 		    (uchar_t *)bufaddr, SD_PROFILE_HEADER_LEN, SD_LOG_HEX);
21227 	}
21228 
21229 	SD_TRACE(SD_LOG_IO, un,
21230 	    "sd_send_scsi_GET_CONFIGURATION: exit\n");
21231 
21232 	return (status);
21233 }
21234 
21235 /*
21236  *    Function: sd_send_scsi_feature_GET_CONFIGURATION
21237  *
21238  * Description: Issues the get configuration command to the device to
21239  *              retrieve a specific feature. Called from
21240  *		sd_check_for_writable_cd & sd_set_mmc_caps.
21241  *   Arguments: ssc
21242  *              ucmdbuf
21243  *              rqbuf
21244  *              rqbuflen
21245  *              bufaddr
21246  *              buflen
21247  *		feature
21248  *
21249  * Return Code: 0   - Success
21250  *              errno return code from sd_ssc_send()
21251  *
21252  *     Context: Can sleep. Does not return until command is completed.
21253  *
21254  */
21255 static int
21256 sd_send_scsi_feature_GET_CONFIGURATION(sd_ssc_t *ssc,
21257 	struct uscsi_cmd *ucmdbuf, uchar_t *rqbuf, uint_t rqbuflen,
21258 	uchar_t *bufaddr, uint_t buflen, char feature, int path_flag)
21259 {
21260 	char    cdb[CDB_GROUP1];
21261 	int	status;
21262 	struct sd_lun	*un;
21263 
21264 	ASSERT(ssc != NULL);
21265 	un = ssc->ssc_un;
21266 	ASSERT(un != NULL);
21267 	ASSERT(!mutex_owned(SD_MUTEX(un)));
21268 	ASSERT(bufaddr != NULL);
21269 	ASSERT(ucmdbuf != NULL);
21270 	ASSERT(rqbuf != NULL);
21271 
21272 	SD_TRACE(SD_LOG_IO, un,
21273 	    "sd_send_scsi_feature_GET_CONFIGURATION: entry: un:0x%p\n", un);
21274 
21275 	bzero(cdb, sizeof (cdb));
21276 	bzero(ucmdbuf, sizeof (struct uscsi_cmd));
21277 	bzero(rqbuf, rqbuflen);
21278 	bzero(bufaddr, buflen);
21279 
21280 	/*
21281 	 * Set up cdb field for the get configuration command.
21282 	 */
21283 	cdb[0] = SCMD_GET_CONFIGURATION;
21284 	cdb[1] = 0x02;  /* Requested Type */
21285 	cdb[3] = feature;
21286 	cdb[8] = buflen;
21287 	ucmdbuf->uscsi_cdb = cdb;
21288 	ucmdbuf->uscsi_cdblen = CDB_GROUP1;
21289 	ucmdbuf->uscsi_bufaddr = (caddr_t)bufaddr;
21290 	ucmdbuf->uscsi_buflen = buflen;
21291 	ucmdbuf->uscsi_timeout = sd_io_time;
21292 	ucmdbuf->uscsi_rqbuf = (caddr_t)rqbuf;
21293 	ucmdbuf->uscsi_rqlen = rqbuflen;
21294 	ucmdbuf->uscsi_flags = USCSI_RQENABLE|USCSI_SILENT|USCSI_READ;
21295 
21296 	status = sd_ssc_send(ssc, ucmdbuf, FKIOCTL,
21297 	    UIO_SYSSPACE, path_flag);
21298 
21299 	switch (status) {
21300 	case 0:
21301 
21302 		break;  /* Success! */
21303 	case EIO:
21304 		switch (ucmdbuf->uscsi_status) {
21305 		case STATUS_RESERVATION_CONFLICT:
21306 			status = EACCES;
21307 			break;
21308 		default:
21309 			break;
21310 		}
21311 		break;
21312 	default:
21313 		break;
21314 	}
21315 
21316 	if (status == 0) {
21317 		SD_DUMP_MEMORY(un, SD_LOG_IO,
21318 		    "sd_send_scsi_feature_GET_CONFIGURATION: data",
21319 		    (uchar_t *)bufaddr, SD_PROFILE_HEADER_LEN, SD_LOG_HEX);
21320 	}
21321 
21322 	SD_TRACE(SD_LOG_IO, un,
21323 	    "sd_send_scsi_feature_GET_CONFIGURATION: exit\n");
21324 
21325 	return (status);
21326 }
21327 
21328 
21329 /*
21330  *    Function: sd_send_scsi_MODE_SENSE
21331  *
21332  * Description: Utility function for issuing a scsi MODE SENSE command.
21333  *		Note: This routine uses a consistent implementation for Group0,
21334  *		Group1, and Group2 commands across all platforms. ATAPI devices
21335  *		use Group 1 Read/Write commands and Group 2 Mode Sense/Select
21336  *
21337  *   Arguments: ssc   - ssc contains pointer to driver soft state (unit)
21338  *                      structure for this target.
21339  *		cdbsize - size CDB to be used (CDB_GROUP0 (6 byte), or
21340  *			  CDB_GROUP[1|2] (10 byte).
21341  *		bufaddr - buffer for page data retrieved from the target.
21342  *		buflen - size of page to be retrieved.
21343  *		page_code - page code of data to be retrieved from the target.
21344  *		path_flag - SD_PATH_DIRECT to use the USCSI "direct" chain and
21345  *			the normal command waitq, or SD_PATH_DIRECT_PRIORITY
21346  *			to use the USCSI "direct" chain and bypass the normal
21347  *			command waitq.
21348  *
21349  * Return Code: 0   - Success
21350  *		errno return code from sd_ssc_send()
21351  *
21352  *     Context: Can sleep. Does not return until command is completed.
21353  */
21354 
21355 static int
21356 sd_send_scsi_MODE_SENSE(sd_ssc_t *ssc, int cdbsize, uchar_t *bufaddr,
21357 	size_t buflen,  uchar_t page_code, int path_flag)
21358 {
21359 	struct	scsi_extended_sense	sense_buf;
21360 	union scsi_cdb		cdb;
21361 	struct uscsi_cmd	ucmd_buf;
21362 	int			status;
21363 	int			headlen;
21364 	struct sd_lun		*un;
21365 
21366 	ASSERT(ssc != NULL);
21367 	un = ssc->ssc_un;
21368 	ASSERT(un != NULL);
21369 	ASSERT(!mutex_owned(SD_MUTEX(un)));
21370 	ASSERT(bufaddr != NULL);
21371 	ASSERT((cdbsize == CDB_GROUP0) || (cdbsize == CDB_GROUP1) ||
21372 	    (cdbsize == CDB_GROUP2));
21373 
21374 	SD_TRACE(SD_LOG_IO, un,
21375 	    "sd_send_scsi_MODE_SENSE: entry: un:0x%p\n", un);
21376 
21377 	bzero(&cdb, sizeof (cdb));
21378 	bzero(&ucmd_buf, sizeof (ucmd_buf));
21379 	bzero(&sense_buf, sizeof (struct scsi_extended_sense));
21380 	bzero(bufaddr, buflen);
21381 
21382 	if (cdbsize == CDB_GROUP0) {
21383 		cdb.scc_cmd = SCMD_MODE_SENSE;
21384 		cdb.cdb_opaque[2] = page_code;
21385 		FORMG0COUNT(&cdb, buflen);
21386 		headlen = MODE_HEADER_LENGTH;
21387 	} else {
21388 		cdb.scc_cmd = SCMD_MODE_SENSE_G1;
21389 		cdb.cdb_opaque[2] = page_code;
21390 		FORMG1COUNT(&cdb, buflen);
21391 		headlen = MODE_HEADER_LENGTH_GRP2;
21392 	}
21393 
21394 	ASSERT(headlen <= buflen);
21395 	SD_FILL_SCSI1_LUN_CDB(un, &cdb);
21396 
21397 	ucmd_buf.uscsi_cdb	= (char *)&cdb;
21398 	ucmd_buf.uscsi_cdblen	= (uchar_t)cdbsize;
21399 	ucmd_buf.uscsi_bufaddr	= (caddr_t)bufaddr;
21400 	ucmd_buf.uscsi_buflen	= buflen;
21401 	ucmd_buf.uscsi_rqbuf	= (caddr_t)&sense_buf;
21402 	ucmd_buf.uscsi_rqlen	= sizeof (struct scsi_extended_sense);
21403 	ucmd_buf.uscsi_flags	= USCSI_RQENABLE | USCSI_READ | USCSI_SILENT;
21404 	ucmd_buf.uscsi_timeout	= 60;
21405 
21406 	status = sd_ssc_send(ssc, &ucmd_buf, FKIOCTL,
21407 	    UIO_SYSSPACE, path_flag);
21408 
21409 	switch (status) {
21410 	case 0:
21411 		/*
21412 		 * sr_check_wp() uses 0x3f page code and check the header of
21413 		 * mode page to determine if target device is write-protected.
21414 		 * But some USB devices return 0 bytes for 0x3f page code. For
21415 		 * this case, make sure that mode page header is returned at
21416 		 * least.
21417 		 */
21418 		if (buflen - ucmd_buf.uscsi_resid <  headlen) {
21419 			status = EIO;
21420 			sd_ssc_set_info(ssc, SSC_FLAGS_INVALID_DATA, -1,
21421 			    "mode page header is not returned");
21422 		}
21423 		break;	/* Success! */
21424 	case EIO:
21425 		switch (ucmd_buf.uscsi_status) {
21426 		case STATUS_RESERVATION_CONFLICT:
21427 			status = EACCES;
21428 			break;
21429 		default:
21430 			break;
21431 		}
21432 		break;
21433 	default:
21434 		break;
21435 	}
21436 
21437 	if (status == 0) {
21438 		SD_DUMP_MEMORY(un, SD_LOG_IO, "sd_send_scsi_MODE_SENSE: data",
21439 		    (uchar_t *)bufaddr, buflen, SD_LOG_HEX);
21440 	}
21441 	SD_TRACE(SD_LOG_IO, un, "sd_send_scsi_MODE_SENSE: exit\n");
21442 
21443 	return (status);
21444 }
21445 
21446 
21447 /*
21448  *    Function: sd_send_scsi_MODE_SELECT
21449  *
21450  * Description: Utility function for issuing a scsi MODE SELECT command.
21451  *		Note: This routine uses a consistent implementation for Group0,
21452  *		Group1, and Group2 commands across all platforms. ATAPI devices
21453  *		use Group 1 Read/Write commands and Group 2 Mode Sense/Select
21454  *
21455  *   Arguments: ssc   - ssc contains pointer to driver soft state (unit)
21456  *                      structure for this target.
21457  *		cdbsize - size CDB to be used (CDB_GROUP0 (6 byte), or
21458  *			  CDB_GROUP[1|2] (10 byte).
21459  *		bufaddr - buffer for page data retrieved from the target.
21460  *		buflen - size of page to be retrieved.
21461  *		save_page - boolean to determin if SP bit should be set.
21462  *		path_flag - SD_PATH_DIRECT to use the USCSI "direct" chain and
21463  *			the normal command waitq, or SD_PATH_DIRECT_PRIORITY
21464  *			to use the USCSI "direct" chain and bypass the normal
21465  *			command waitq.
21466  *
21467  * Return Code: 0   - Success
21468  *		errno return code from sd_ssc_send()
21469  *
21470  *     Context: Can sleep. Does not return until command is completed.
21471  */
21472 
21473 static int
21474 sd_send_scsi_MODE_SELECT(sd_ssc_t *ssc, int cdbsize, uchar_t *bufaddr,
21475 	size_t buflen,  uchar_t save_page, int path_flag)
21476 {
21477 	struct	scsi_extended_sense	sense_buf;
21478 	union scsi_cdb		cdb;
21479 	struct uscsi_cmd	ucmd_buf;
21480 	int			status;
21481 	struct sd_lun		*un;
21482 
21483 	ASSERT(ssc != NULL);
21484 	un = ssc->ssc_un;
21485 	ASSERT(un != NULL);
21486 	ASSERT(!mutex_owned(SD_MUTEX(un)));
21487 	ASSERT(bufaddr != NULL);
21488 	ASSERT((cdbsize == CDB_GROUP0) || (cdbsize == CDB_GROUP1) ||
21489 	    (cdbsize == CDB_GROUP2));
21490 
21491 	SD_TRACE(SD_LOG_IO, un,
21492 	    "sd_send_scsi_MODE_SELECT: entry: un:0x%p\n", un);
21493 
21494 	bzero(&cdb, sizeof (cdb));
21495 	bzero(&ucmd_buf, sizeof (ucmd_buf));
21496 	bzero(&sense_buf, sizeof (struct scsi_extended_sense));
21497 
21498 	/* Set the PF bit for many third party drives */
21499 	cdb.cdb_opaque[1] = 0x10;
21500 
21501 	/* Set the savepage(SP) bit if given */
21502 	if (save_page == SD_SAVE_PAGE) {
21503 		cdb.cdb_opaque[1] |= 0x01;
21504 	}
21505 
21506 	if (cdbsize == CDB_GROUP0) {
21507 		cdb.scc_cmd = SCMD_MODE_SELECT;
21508 		FORMG0COUNT(&cdb, buflen);
21509 	} else {
21510 		cdb.scc_cmd = SCMD_MODE_SELECT_G1;
21511 		FORMG1COUNT(&cdb, buflen);
21512 	}
21513 
21514 	SD_FILL_SCSI1_LUN_CDB(un, &cdb);
21515 
21516 	ucmd_buf.uscsi_cdb	= (char *)&cdb;
21517 	ucmd_buf.uscsi_cdblen	= (uchar_t)cdbsize;
21518 	ucmd_buf.uscsi_bufaddr	= (caddr_t)bufaddr;
21519 	ucmd_buf.uscsi_buflen	= buflen;
21520 	ucmd_buf.uscsi_rqbuf	= (caddr_t)&sense_buf;
21521 	ucmd_buf.uscsi_rqlen	= sizeof (struct scsi_extended_sense);
21522 	ucmd_buf.uscsi_flags	= USCSI_RQENABLE | USCSI_WRITE | USCSI_SILENT;
21523 	ucmd_buf.uscsi_timeout	= 60;
21524 
21525 	status = sd_ssc_send(ssc, &ucmd_buf, FKIOCTL,
21526 	    UIO_SYSSPACE, path_flag);
21527 
21528 	switch (status) {
21529 	case 0:
21530 		sd_ssc_assessment(ssc, SD_FMT_STANDARD);
21531 		break;	/* Success! */
21532 	case EIO:
21533 		switch (ucmd_buf.uscsi_status) {
21534 		case STATUS_RESERVATION_CONFLICT:
21535 			status = EACCES;
21536 			break;
21537 		default:
21538 			break;
21539 		}
21540 		break;
21541 	default:
21542 		break;
21543 	}
21544 
21545 	if (status == 0) {
21546 		SD_DUMP_MEMORY(un, SD_LOG_IO, "sd_send_scsi_MODE_SELECT: data",
21547 		    (uchar_t *)bufaddr, buflen, SD_LOG_HEX);
21548 	}
21549 	SD_TRACE(SD_LOG_IO, un, "sd_send_scsi_MODE_SELECT: exit\n");
21550 
21551 	return (status);
21552 }
21553 
21554 
21555 /*
21556  *    Function: sd_send_scsi_RDWR
21557  *
21558  * Description: Issue a scsi READ or WRITE command with the given parameters.
21559  *
21560  *   Arguments: ssc   - ssc contains pointer to driver soft state (unit)
21561  *                      structure for this target.
21562  *		cmd:	 SCMD_READ or SCMD_WRITE
21563  *		bufaddr: Address of caller's buffer to receive the RDWR data
21564  *		buflen:  Length of caller's buffer receive the RDWR data.
21565  *		start_block: Block number for the start of the RDWR operation.
21566  *			 (Assumes target-native block size.)
21567  *		residp:  Pointer to variable to receive the redisual of the
21568  *			 RDWR operation (may be NULL of no residual requested).
21569  *		path_flag - SD_PATH_DIRECT to use the USCSI "direct" chain and
21570  *			the normal command waitq, or SD_PATH_DIRECT_PRIORITY
21571  *			to use the USCSI "direct" chain and bypass the normal
21572  *			command waitq.
21573  *
21574  * Return Code: 0   - Success
21575  *		errno return code from sd_ssc_send()
21576  *
21577  *     Context: Can sleep. Does not return until command is completed.
21578  */
21579 
21580 static int
21581 sd_send_scsi_RDWR(sd_ssc_t *ssc, uchar_t cmd, void *bufaddr,
21582 	size_t buflen, daddr_t start_block, int path_flag)
21583 {
21584 	struct	scsi_extended_sense	sense_buf;
21585 	union scsi_cdb		cdb;
21586 	struct uscsi_cmd	ucmd_buf;
21587 	uint32_t		block_count;
21588 	int			status;
21589 	int			cdbsize;
21590 	uchar_t			flag;
21591 	struct sd_lun		*un;
21592 
21593 	ASSERT(ssc != NULL);
21594 	un = ssc->ssc_un;
21595 	ASSERT(un != NULL);
21596 	ASSERT(!mutex_owned(SD_MUTEX(un)));
21597 	ASSERT(bufaddr != NULL);
21598 	ASSERT((cmd == SCMD_READ) || (cmd == SCMD_WRITE));
21599 
21600 	SD_TRACE(SD_LOG_IO, un, "sd_send_scsi_RDWR: entry: un:0x%p\n", un);
21601 
21602 	if (un->un_f_tgt_blocksize_is_valid != TRUE) {
21603 		return (EINVAL);
21604 	}
21605 
21606 	mutex_enter(SD_MUTEX(un));
21607 	block_count = SD_BYTES2TGTBLOCKS(un, buflen);
21608 	mutex_exit(SD_MUTEX(un));
21609 
21610 	flag = (cmd == SCMD_READ) ? USCSI_READ : USCSI_WRITE;
21611 
21612 	SD_INFO(SD_LOG_IO, un, "sd_send_scsi_RDWR: "
21613 	    "bufaddr:0x%p buflen:0x%x start_block:0x%p block_count:0x%x\n",
21614 	    bufaddr, buflen, start_block, block_count);
21615 
21616 	bzero(&cdb, sizeof (cdb));
21617 	bzero(&ucmd_buf, sizeof (ucmd_buf));
21618 	bzero(&sense_buf, sizeof (struct scsi_extended_sense));
21619 
21620 	/* Compute CDB size to use */
21621 	if (start_block > 0xffffffff)
21622 		cdbsize = CDB_GROUP4;
21623 	else if ((start_block & 0xFFE00000) ||
21624 	    (un->un_f_cfg_is_atapi == TRUE))
21625 		cdbsize = CDB_GROUP1;
21626 	else
21627 		cdbsize = CDB_GROUP0;
21628 
21629 	switch (cdbsize) {
21630 	case CDB_GROUP0:	/* 6-byte CDBs */
21631 		cdb.scc_cmd = cmd;
21632 		FORMG0ADDR(&cdb, start_block);
21633 		FORMG0COUNT(&cdb, block_count);
21634 		break;
21635 	case CDB_GROUP1:	/* 10-byte CDBs */
21636 		cdb.scc_cmd = cmd | SCMD_GROUP1;
21637 		FORMG1ADDR(&cdb, start_block);
21638 		FORMG1COUNT(&cdb, block_count);
21639 		break;
21640 	case CDB_GROUP4:	/* 16-byte CDBs */
21641 		cdb.scc_cmd = cmd | SCMD_GROUP4;
21642 		FORMG4LONGADDR(&cdb, (uint64_t)start_block);
21643 		FORMG4COUNT(&cdb, block_count);
21644 		break;
21645 	case CDB_GROUP5:	/* 12-byte CDBs (currently unsupported) */
21646 	default:
21647 		/* All others reserved */
21648 		return (EINVAL);
21649 	}
21650 
21651 	/* Set LUN bit(s) in CDB if this is a SCSI-1 device */
21652 	SD_FILL_SCSI1_LUN_CDB(un, &cdb);
21653 
21654 	ucmd_buf.uscsi_cdb	= (char *)&cdb;
21655 	ucmd_buf.uscsi_cdblen	= (uchar_t)cdbsize;
21656 	ucmd_buf.uscsi_bufaddr	= bufaddr;
21657 	ucmd_buf.uscsi_buflen	= buflen;
21658 	ucmd_buf.uscsi_rqbuf	= (caddr_t)&sense_buf;
21659 	ucmd_buf.uscsi_rqlen	= sizeof (struct scsi_extended_sense);
21660 	ucmd_buf.uscsi_flags	= flag | USCSI_RQENABLE | USCSI_SILENT;
21661 	ucmd_buf.uscsi_timeout	= 60;
21662 	status = sd_ssc_send(ssc, &ucmd_buf, FKIOCTL,
21663 	    UIO_SYSSPACE, path_flag);
21664 
21665 	switch (status) {
21666 	case 0:
21667 		sd_ssc_assessment(ssc, SD_FMT_STANDARD);
21668 		break;	/* Success! */
21669 	case EIO:
21670 		switch (ucmd_buf.uscsi_status) {
21671 		case STATUS_RESERVATION_CONFLICT:
21672 			status = EACCES;
21673 			break;
21674 		default:
21675 			break;
21676 		}
21677 		break;
21678 	default:
21679 		break;
21680 	}
21681 
21682 	if (status == 0) {
21683 		SD_DUMP_MEMORY(un, SD_LOG_IO, "sd_send_scsi_RDWR: data",
21684 		    (uchar_t *)bufaddr, buflen, SD_LOG_HEX);
21685 	}
21686 
21687 	SD_TRACE(SD_LOG_IO, un, "sd_send_scsi_RDWR: exit\n");
21688 
21689 	return (status);
21690 }
21691 
21692 
21693 /*
21694  *    Function: sd_send_scsi_LOG_SENSE
21695  *
21696  * Description: Issue a scsi LOG_SENSE command with the given parameters.
21697  *
21698  *   Arguments: ssc   - ssc contains pointer to driver soft state (unit)
21699  *                      structure for this target.
21700  *
21701  * Return Code: 0   - Success
21702  *		errno return code from sd_ssc_send()
21703  *
21704  *     Context: Can sleep. Does not return until command is completed.
21705  */
21706 
21707 static int
21708 sd_send_scsi_LOG_SENSE(sd_ssc_t *ssc, uchar_t *bufaddr, uint16_t buflen,
21709 	uchar_t page_code, uchar_t page_control, uint16_t param_ptr,
21710 	int path_flag)
21711 
21712 {
21713 	struct scsi_extended_sense	sense_buf;
21714 	union scsi_cdb		cdb;
21715 	struct uscsi_cmd	ucmd_buf;
21716 	int			status;
21717 	struct sd_lun		*un;
21718 
21719 	ASSERT(ssc != NULL);
21720 	un = ssc->ssc_un;
21721 	ASSERT(un != NULL);
21722 	ASSERT(!mutex_owned(SD_MUTEX(un)));
21723 
21724 	SD_TRACE(SD_LOG_IO, un, "sd_send_scsi_LOG_SENSE: entry: un:0x%p\n", un);
21725 
21726 	bzero(&cdb, sizeof (cdb));
21727 	bzero(&ucmd_buf, sizeof (ucmd_buf));
21728 	bzero(&sense_buf, sizeof (struct scsi_extended_sense));
21729 
21730 	cdb.scc_cmd = SCMD_LOG_SENSE_G1;
21731 	cdb.cdb_opaque[2] = (page_control << 6) | page_code;
21732 	cdb.cdb_opaque[5] = (uchar_t)((param_ptr & 0xFF00) >> 8);
21733 	cdb.cdb_opaque[6] = (uchar_t)(param_ptr  & 0x00FF);
21734 	FORMG1COUNT(&cdb, buflen);
21735 
21736 	ucmd_buf.uscsi_cdb	= (char *)&cdb;
21737 	ucmd_buf.uscsi_cdblen	= CDB_GROUP1;
21738 	ucmd_buf.uscsi_bufaddr	= (caddr_t)bufaddr;
21739 	ucmd_buf.uscsi_buflen	= buflen;
21740 	ucmd_buf.uscsi_rqbuf	= (caddr_t)&sense_buf;
21741 	ucmd_buf.uscsi_rqlen	= sizeof (struct scsi_extended_sense);
21742 	ucmd_buf.uscsi_flags	= USCSI_RQENABLE | USCSI_READ | USCSI_SILENT;
21743 	ucmd_buf.uscsi_timeout	= 60;
21744 
21745 	status = sd_ssc_send(ssc, &ucmd_buf, FKIOCTL,
21746 	    UIO_SYSSPACE, path_flag);
21747 
21748 	switch (status) {
21749 	case 0:
21750 		break;
21751 	case EIO:
21752 		switch (ucmd_buf.uscsi_status) {
21753 		case STATUS_RESERVATION_CONFLICT:
21754 			status = EACCES;
21755 			break;
21756 		case STATUS_CHECK:
21757 			if ((ucmd_buf.uscsi_rqstatus == STATUS_GOOD) &&
21758 			    (scsi_sense_key((uint8_t *)&sense_buf) ==
21759 				KEY_ILLEGAL_REQUEST) &&
21760 			    (scsi_sense_asc((uint8_t *)&sense_buf) == 0x24)) {
21761 				/*
21762 				 * ASC 0x24: INVALID FIELD IN CDB
21763 				 */
21764 				switch (page_code) {
21765 				case START_STOP_CYCLE_PAGE:
21766 					/*
21767 					 * The start stop cycle counter is
21768 					 * implemented as page 0x31 in earlier
21769 					 * generation disks. In new generation
21770 					 * disks the start stop cycle counter is
21771 					 * implemented as page 0xE. To properly
21772 					 * handle this case if an attempt for
21773 					 * log page 0xE is made and fails we
21774 					 * will try again using page 0x31.
21775 					 *
21776 					 * Network storage BU committed to
21777 					 * maintain the page 0x31 for this
21778 					 * purpose and will not have any other
21779 					 * page implemented with page code 0x31
21780 					 * until all disks transition to the
21781 					 * standard page.
21782 					 */
21783 					mutex_enter(SD_MUTEX(un));
21784 					un->un_start_stop_cycle_page =
21785 					    START_STOP_CYCLE_VU_PAGE;
21786 					cdb.cdb_opaque[2] =
21787 					    (char)(page_control << 6) |
21788 					    un->un_start_stop_cycle_page;
21789 					mutex_exit(SD_MUTEX(un));
21790 					sd_ssc_assessment(ssc, SD_FMT_IGNORE);
21791 					status = sd_ssc_send(
21792 					    ssc, &ucmd_buf, FKIOCTL,
21793 					    UIO_SYSSPACE, path_flag);
21794 
21795 					break;
21796 				case TEMPERATURE_PAGE:
21797 					status = ENOTTY;
21798 					break;
21799 				default:
21800 					break;
21801 				}
21802 			}
21803 			break;
21804 		default:
21805 			break;
21806 		}
21807 		break;
21808 	default:
21809 		break;
21810 	}
21811 
21812 	if (status == 0) {
21813 		sd_ssc_assessment(ssc, SD_FMT_STANDARD);
21814 		SD_DUMP_MEMORY(un, SD_LOG_IO, "sd_send_scsi_LOG_SENSE: data",
21815 		    (uchar_t *)bufaddr, buflen, SD_LOG_HEX);
21816 	}
21817 
21818 	SD_TRACE(SD_LOG_IO, un, "sd_send_scsi_LOG_SENSE: exit\n");
21819 
21820 	return (status);
21821 }
21822 
21823 
21824 /*
21825  *    Function: sdioctl
21826  *
21827  * Description: Driver's ioctl(9e) entry point function.
21828  *
21829  *   Arguments: dev     - device number
21830  *		cmd     - ioctl operation to be performed
21831  *		arg     - user argument, contains data to be set or reference
21832  *			  parameter for get
21833  *		flag    - bit flag, indicating open settings, 32/64 bit type
21834  *		cred_p  - user credential pointer
21835  *		rval_p  - calling process return value (OPT)
21836  *
21837  * Return Code: EINVAL
21838  *		ENOTTY
21839  *		ENXIO
21840  *		EIO
21841  *		EFAULT
21842  *		ENOTSUP
21843  *		EPERM
21844  *
21845  *     Context: Called from the device switch at normal priority.
21846  */
21847 
21848 static int
21849 sdioctl(dev_t dev, int cmd, intptr_t arg, int flag, cred_t *cred_p, int *rval_p)
21850 {
21851 	struct sd_lun	*un = NULL;
21852 	int		err = 0;
21853 	int		i = 0;
21854 	cred_t		*cr;
21855 	int		tmprval = EINVAL;
21856 	boolean_t	is_valid;
21857 	sd_ssc_t	*ssc;
21858 
21859 	/*
21860 	 * All device accesses go thru sdstrategy where we check on suspend
21861 	 * status
21862 	 */
21863 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
21864 		return (ENXIO);
21865 	}
21866 
21867 	ASSERT(!mutex_owned(SD_MUTEX(un)));
21868 
21869 	/* Initialize sd_ssc_t for internal uscsi commands */
21870 	ssc = sd_ssc_init(un);
21871 
21872 	is_valid = SD_IS_VALID_LABEL(un);
21873 
21874 	/*
21875 	 * Moved this wait from sd_uscsi_strategy to here for
21876 	 * reasons of deadlock prevention. Internal driver commands,
21877 	 * specifically those to change a devices power level, result
21878 	 * in a call to sd_uscsi_strategy.
21879 	 */
21880 	mutex_enter(SD_MUTEX(un));
21881 	while ((un->un_state == SD_STATE_SUSPENDED) ||
21882 	    (un->un_state == SD_STATE_PM_CHANGING)) {
21883 		cv_wait(&un->un_suspend_cv, SD_MUTEX(un));
21884 	}
21885 	/*
21886 	 * Twiddling the counter here protects commands from now
21887 	 * through to the top of sd_uscsi_strategy. Without the
21888 	 * counter inc. a power down, for example, could get in
21889 	 * after the above check for state is made and before
21890 	 * execution gets to the top of sd_uscsi_strategy.
21891 	 * That would cause problems.
21892 	 */
21893 	un->un_ncmds_in_driver++;
21894 
21895 	if (!is_valid &&
21896 	    (flag & (FNDELAY | FNONBLOCK))) {
21897 		switch (cmd) {
21898 		case DKIOCGGEOM:	/* SD_PATH_DIRECT */
21899 		case DKIOCGVTOC:
21900 		case DKIOCGEXTVTOC:
21901 		case DKIOCGAPART:
21902 		case DKIOCPARTINFO:
21903 		case DKIOCEXTPARTINFO:
21904 		case DKIOCSGEOM:
21905 		case DKIOCSAPART:
21906 		case DKIOCGETEFI:
21907 		case DKIOCPARTITION:
21908 		case DKIOCSVTOC:
21909 		case DKIOCSEXTVTOC:
21910 		case DKIOCSETEFI:
21911 		case DKIOCGMBOOT:
21912 		case DKIOCSMBOOT:
21913 		case DKIOCG_PHYGEOM:
21914 		case DKIOCG_VIRTGEOM:
21915 #if defined(__i386) || defined(__amd64)
21916 		case DKIOCSETEXTPART:
21917 #endif
21918 			/* let cmlb handle it */
21919 			goto skip_ready_valid;
21920 
21921 		case CDROMPAUSE:
21922 		case CDROMRESUME:
21923 		case CDROMPLAYMSF:
21924 		case CDROMPLAYTRKIND:
21925 		case CDROMREADTOCHDR:
21926 		case CDROMREADTOCENTRY:
21927 		case CDROMSTOP:
21928 		case CDROMSTART:
21929 		case CDROMVOLCTRL:
21930 		case CDROMSUBCHNL:
21931 		case CDROMREADMODE2:
21932 		case CDROMREADMODE1:
21933 		case CDROMREADOFFSET:
21934 		case CDROMSBLKMODE:
21935 		case CDROMGBLKMODE:
21936 		case CDROMGDRVSPEED:
21937 		case CDROMSDRVSPEED:
21938 		case CDROMCDDA:
21939 		case CDROMCDXA:
21940 		case CDROMSUBCODE:
21941 			if (!ISCD(un)) {
21942 				un->un_ncmds_in_driver--;
21943 				ASSERT(un->un_ncmds_in_driver >= 0);
21944 				mutex_exit(SD_MUTEX(un));
21945 				err = ENOTTY;
21946 				goto done_without_assess;
21947 			}
21948 			break;
21949 		case FDEJECT:
21950 		case DKIOCEJECT:
21951 		case CDROMEJECT:
21952 			if (!un->un_f_eject_media_supported) {
21953 				un->un_ncmds_in_driver--;
21954 				ASSERT(un->un_ncmds_in_driver >= 0);
21955 				mutex_exit(SD_MUTEX(un));
21956 				err = ENOTTY;
21957 				goto done_without_assess;
21958 			}
21959 			break;
21960 		case DKIOCFLUSHWRITECACHE:
21961 			mutex_exit(SD_MUTEX(un));
21962 			err = sd_send_scsi_TEST_UNIT_READY(ssc, 0);
21963 			if (err != 0) {
21964 				mutex_enter(SD_MUTEX(un));
21965 				un->un_ncmds_in_driver--;
21966 				ASSERT(un->un_ncmds_in_driver >= 0);
21967 				mutex_exit(SD_MUTEX(un));
21968 				err = EIO;
21969 				goto done_quick_assess;
21970 			}
21971 			mutex_enter(SD_MUTEX(un));
21972 			/* FALLTHROUGH */
21973 		case DKIOCREMOVABLE:
21974 		case DKIOCHOTPLUGGABLE:
21975 		case DKIOCINFO:
21976 		case DKIOCGMEDIAINFO:
21977 		case DKIOCGMEDIAINFOEXT:
21978 		case MHIOCENFAILFAST:
21979 		case MHIOCSTATUS:
21980 		case MHIOCTKOWN:
21981 		case MHIOCRELEASE:
21982 		case MHIOCGRP_INKEYS:
21983 		case MHIOCGRP_INRESV:
21984 		case MHIOCGRP_REGISTER:
21985 		case MHIOCGRP_RESERVE:
21986 		case MHIOCGRP_PREEMPTANDABORT:
21987 		case MHIOCGRP_REGISTERANDIGNOREKEY:
21988 		case CDROMCLOSETRAY:
21989 		case USCSICMD:
21990 			goto skip_ready_valid;
21991 		default:
21992 			break;
21993 		}
21994 
21995 		mutex_exit(SD_MUTEX(un));
21996 		err = sd_ready_and_valid(ssc, SDPART(dev));
21997 		mutex_enter(SD_MUTEX(un));
21998 
21999 		if (err != SD_READY_VALID) {
22000 			switch (cmd) {
22001 			case DKIOCSTATE:
22002 			case CDROMGDRVSPEED:
22003 			case CDROMSDRVSPEED:
22004 			case FDEJECT:	/* for eject command */
22005 			case DKIOCEJECT:
22006 			case CDROMEJECT:
22007 			case DKIOCREMOVABLE:
22008 			case DKIOCHOTPLUGGABLE:
22009 				break;
22010 			default:
22011 				if (un->un_f_has_removable_media) {
22012 					err = ENXIO;
22013 				} else {
22014 				/* Do not map SD_RESERVED_BY_OTHERS to EIO */
22015 					if (err == SD_RESERVED_BY_OTHERS) {
22016 						err = EACCES;
22017 					} else {
22018 						err = EIO;
22019 					}
22020 				}
22021 				un->un_ncmds_in_driver--;
22022 				ASSERT(un->un_ncmds_in_driver >= 0);
22023 				mutex_exit(SD_MUTEX(un));
22024 
22025 				goto done_without_assess;
22026 			}
22027 		}
22028 	}
22029 
22030 skip_ready_valid:
22031 	mutex_exit(SD_MUTEX(un));
22032 
22033 	switch (cmd) {
22034 	case DKIOCINFO:
22035 		SD_TRACE(SD_LOG_IOCTL, un, "DKIOCINFO\n");
22036 		err = sd_dkio_ctrl_info(dev, (caddr_t)arg, flag);
22037 		break;
22038 
22039 	case DKIOCGMEDIAINFO:
22040 		SD_TRACE(SD_LOG_IOCTL, un, "DKIOCGMEDIAINFO\n");
22041 		err = sd_get_media_info(dev, (caddr_t)arg, flag);
22042 		break;
22043 
22044 	case DKIOCGMEDIAINFOEXT:
22045 		SD_TRACE(SD_LOG_IOCTL, un, "DKIOCGMEDIAINFOEXT\n");
22046 		err = sd_get_media_info_ext(dev, (caddr_t)arg, flag);
22047 		break;
22048 
22049 	case DKIOCGGEOM:
22050 	case DKIOCGVTOC:
22051 	case DKIOCGEXTVTOC:
22052 	case DKIOCGAPART:
22053 	case DKIOCPARTINFO:
22054 	case DKIOCEXTPARTINFO:
22055 	case DKIOCSGEOM:
22056 	case DKIOCSAPART:
22057 	case DKIOCGETEFI:
22058 	case DKIOCPARTITION:
22059 	case DKIOCSVTOC:
22060 	case DKIOCSEXTVTOC:
22061 	case DKIOCSETEFI:
22062 	case DKIOCGMBOOT:
22063 	case DKIOCSMBOOT:
22064 	case DKIOCG_PHYGEOM:
22065 	case DKIOCG_VIRTGEOM:
22066 #if defined(__i386) || defined(__amd64)
22067 	case DKIOCSETEXTPART:
22068 #endif
22069 		SD_TRACE(SD_LOG_IOCTL, un, "DKIOC %d\n", cmd);
22070 
22071 		/* TUR should spin up */
22072 
22073 		if (un->un_f_has_removable_media)
22074 			err = sd_send_scsi_TEST_UNIT_READY(ssc,
22075 			    SD_CHECK_FOR_MEDIA);
22076 
22077 		else
22078 			err = sd_send_scsi_TEST_UNIT_READY(ssc, 0);
22079 
22080 		if (err != 0)
22081 			goto done_with_assess;
22082 
22083 		err = cmlb_ioctl(un->un_cmlbhandle, dev,
22084 		    cmd, arg, flag, cred_p, rval_p, (void *)SD_PATH_DIRECT);
22085 
22086 		if ((err == 0) &&
22087 		    ((cmd == DKIOCSETEFI) ||
22088 		    (un->un_f_pkstats_enabled) &&
22089 		    (cmd == DKIOCSAPART || cmd == DKIOCSVTOC ||
22090 		    cmd == DKIOCSEXTVTOC))) {
22091 
22092 			tmprval = cmlb_validate(un->un_cmlbhandle, CMLB_SILENT,
22093 			    (void *)SD_PATH_DIRECT);
22094 			if ((tmprval == 0) && un->un_f_pkstats_enabled) {
22095 				sd_set_pstats(un);
22096 				SD_TRACE(SD_LOG_IO_PARTITION, un,
22097 				    "sd_ioctl: un:0x%p pstats created and "
22098 				    "set\n", un);
22099 			}
22100 		}
22101 
22102 		if ((cmd == DKIOCSVTOC || cmd == DKIOCSEXTVTOC) ||
22103 		    ((cmd == DKIOCSETEFI) && (tmprval == 0))) {
22104 
22105 			mutex_enter(SD_MUTEX(un));
22106 			if (un->un_f_devid_supported &&
22107 			    (un->un_f_opt_fab_devid == TRUE)) {
22108 				if (un->un_devid == NULL) {
22109 					sd_register_devid(ssc, SD_DEVINFO(un),
22110 					    SD_TARGET_IS_UNRESERVED);
22111 				} else {
22112 					/*
22113 					 * The device id for this disk
22114 					 * has been fabricated. The
22115 					 * device id must be preserved
22116 					 * by writing it back out to
22117 					 * disk.
22118 					 */
22119 					if (sd_write_deviceid(ssc) != 0) {
22120 						ddi_devid_free(un->un_devid);
22121 						un->un_devid = NULL;
22122 					}
22123 				}
22124 			}
22125 			mutex_exit(SD_MUTEX(un));
22126 		}
22127 
22128 		break;
22129 
22130 	case DKIOCLOCK:
22131 		SD_TRACE(SD_LOG_IOCTL, un, "DKIOCLOCK\n");
22132 		err = sd_send_scsi_DOORLOCK(ssc, SD_REMOVAL_PREVENT,
22133 		    SD_PATH_STANDARD);
22134 		goto done_with_assess;
22135 
22136 	case DKIOCUNLOCK:
22137 		SD_TRACE(SD_LOG_IOCTL, un, "DKIOCUNLOCK\n");
22138 		err = sd_send_scsi_DOORLOCK(ssc, SD_REMOVAL_ALLOW,
22139 		    SD_PATH_STANDARD);
22140 		goto done_with_assess;
22141 
22142 	case DKIOCSTATE: {
22143 		enum dkio_state		state;
22144 		SD_TRACE(SD_LOG_IOCTL, un, "DKIOCSTATE\n");
22145 
22146 		if (ddi_copyin((void *)arg, &state, sizeof (int), flag) != 0) {
22147 			err = EFAULT;
22148 		} else {
22149 			err = sd_check_media(dev, state);
22150 			if (err == 0) {
22151 				if (ddi_copyout(&un->un_mediastate, (void *)arg,
22152 				    sizeof (int), flag) != 0)
22153 					err = EFAULT;
22154 			}
22155 		}
22156 		break;
22157 	}
22158 
22159 	case DKIOCREMOVABLE:
22160 		SD_TRACE(SD_LOG_IOCTL, un, "DKIOCREMOVABLE\n");
22161 		i = un->un_f_has_removable_media ? 1 : 0;
22162 		if (ddi_copyout(&i, (void *)arg, sizeof (int), flag) != 0) {
22163 			err = EFAULT;
22164 		} else {
22165 			err = 0;
22166 		}
22167 		break;
22168 
22169 	case DKIOCHOTPLUGGABLE:
22170 		SD_TRACE(SD_LOG_IOCTL, un, "DKIOCHOTPLUGGABLE\n");
22171 		i = un->un_f_is_hotpluggable ? 1 : 0;
22172 		if (ddi_copyout(&i, (void *)arg, sizeof (int), flag) != 0) {
22173 			err = EFAULT;
22174 		} else {
22175 			err = 0;
22176 		}
22177 		break;
22178 
22179 	case DKIOCGTEMPERATURE:
22180 		SD_TRACE(SD_LOG_IOCTL, un, "DKIOCGTEMPERATURE\n");
22181 		err = sd_dkio_get_temp(dev, (caddr_t)arg, flag);
22182 		break;
22183 
22184 	case MHIOCENFAILFAST:
22185 		SD_TRACE(SD_LOG_IOCTL, un, "MHIOCENFAILFAST\n");
22186 		if ((err = drv_priv(cred_p)) == 0) {
22187 			err = sd_mhdioc_failfast(dev, (caddr_t)arg, flag);
22188 		}
22189 		break;
22190 
22191 	case MHIOCTKOWN:
22192 		SD_TRACE(SD_LOG_IOCTL, un, "MHIOCTKOWN\n");
22193 		if ((err = drv_priv(cred_p)) == 0) {
22194 			err = sd_mhdioc_takeown(dev, (caddr_t)arg, flag);
22195 		}
22196 		break;
22197 
22198 	case MHIOCRELEASE:
22199 		SD_TRACE(SD_LOG_IOCTL, un, "MHIOCRELEASE\n");
22200 		if ((err = drv_priv(cred_p)) == 0) {
22201 			err = sd_mhdioc_release(dev);
22202 		}
22203 		break;
22204 
22205 	case MHIOCSTATUS:
22206 		SD_TRACE(SD_LOG_IOCTL, un, "MHIOCSTATUS\n");
22207 		if ((err = drv_priv(cred_p)) == 0) {
22208 			switch (sd_send_scsi_TEST_UNIT_READY(ssc, 0)) {
22209 			case 0:
22210 				err = 0;
22211 				break;
22212 			case EACCES:
22213 				*rval_p = 1;
22214 				err = 0;
22215 				sd_ssc_assessment(ssc, SD_FMT_IGNORE);
22216 				break;
22217 			default:
22218 				err = EIO;
22219 				goto done_with_assess;
22220 			}
22221 		}
22222 		break;
22223 
22224 	case MHIOCQRESERVE:
22225 		SD_TRACE(SD_LOG_IOCTL, un, "MHIOCQRESERVE\n");
22226 		if ((err = drv_priv(cred_p)) == 0) {
22227 			err = sd_reserve_release(dev, SD_RESERVE);
22228 		}
22229 		break;
22230 
22231 	case MHIOCREREGISTERDEVID:
22232 		SD_TRACE(SD_LOG_IOCTL, un, "MHIOCREREGISTERDEVID\n");
22233 		if (drv_priv(cred_p) == EPERM) {
22234 			err = EPERM;
22235 		} else if (!un->un_f_devid_supported) {
22236 			err = ENOTTY;
22237 		} else {
22238 			err = sd_mhdioc_register_devid(dev);
22239 		}
22240 		break;
22241 
22242 	case MHIOCGRP_INKEYS:
22243 		SD_TRACE(SD_LOG_IOCTL, un, "MHIOCGRP_INKEYS\n");
22244 		if (((err = drv_priv(cred_p)) != EPERM) && arg != NULL) {
22245 			if (un->un_reservation_type == SD_SCSI2_RESERVATION) {
22246 				err = ENOTSUP;
22247 			} else {
22248 				err = sd_mhdioc_inkeys(dev, (caddr_t)arg,
22249 				    flag);
22250 			}
22251 		}
22252 		break;
22253 
22254 	case MHIOCGRP_INRESV:
22255 		SD_TRACE(SD_LOG_IOCTL, un, "MHIOCGRP_INRESV\n");
22256 		if (((err = drv_priv(cred_p)) != EPERM) && arg != NULL) {
22257 			if (un->un_reservation_type == SD_SCSI2_RESERVATION) {
22258 				err = ENOTSUP;
22259 			} else {
22260 				err = sd_mhdioc_inresv(dev, (caddr_t)arg, flag);
22261 			}
22262 		}
22263 		break;
22264 
22265 	case MHIOCGRP_REGISTER:
22266 		SD_TRACE(SD_LOG_IOCTL, un, "MHIOCGRP_REGISTER\n");
22267 		if ((err = drv_priv(cred_p)) != EPERM) {
22268 			if (un->un_reservation_type == SD_SCSI2_RESERVATION) {
22269 				err = ENOTSUP;
22270 			} else if (arg != NULL) {
22271 				mhioc_register_t reg;
22272 				if (ddi_copyin((void *)arg, &reg,
22273 				    sizeof (mhioc_register_t), flag) != 0) {
22274 					err = EFAULT;
22275 				} else {
22276 					err =
22277 					    sd_send_scsi_PERSISTENT_RESERVE_OUT(
22278 					    ssc, SD_SCSI3_REGISTER,
22279 					    (uchar_t *)&reg);
22280 					if (err != 0)
22281 						goto done_with_assess;
22282 				}
22283 			}
22284 		}
22285 		break;
22286 
22287 	case MHIOCGRP_RESERVE:
22288 		SD_TRACE(SD_LOG_IOCTL, un, "MHIOCGRP_RESERVE\n");
22289 		if ((err = drv_priv(cred_p)) != EPERM) {
22290 			if (un->un_reservation_type == SD_SCSI2_RESERVATION) {
22291 				err = ENOTSUP;
22292 			} else if (arg != NULL) {
22293 				mhioc_resv_desc_t resv_desc;
22294 				if (ddi_copyin((void *)arg, &resv_desc,
22295 				    sizeof (mhioc_resv_desc_t), flag) != 0) {
22296 					err = EFAULT;
22297 				} else {
22298 					err =
22299 					    sd_send_scsi_PERSISTENT_RESERVE_OUT(
22300 					    ssc, SD_SCSI3_RESERVE,
22301 					    (uchar_t *)&resv_desc);
22302 					if (err != 0)
22303 						goto done_with_assess;
22304 				}
22305 			}
22306 		}
22307 		break;
22308 
22309 	case MHIOCGRP_PREEMPTANDABORT:
22310 		SD_TRACE(SD_LOG_IOCTL, un, "MHIOCGRP_PREEMPTANDABORT\n");
22311 		if ((err = drv_priv(cred_p)) != EPERM) {
22312 			if (un->un_reservation_type == SD_SCSI2_RESERVATION) {
22313 				err = ENOTSUP;
22314 			} else if (arg != NULL) {
22315 				mhioc_preemptandabort_t preempt_abort;
22316 				if (ddi_copyin((void *)arg, &preempt_abort,
22317 				    sizeof (mhioc_preemptandabort_t),
22318 				    flag) != 0) {
22319 					err = EFAULT;
22320 				} else {
22321 					err =
22322 					    sd_send_scsi_PERSISTENT_RESERVE_OUT(
22323 					    ssc, SD_SCSI3_PREEMPTANDABORT,
22324 					    (uchar_t *)&preempt_abort);
22325 					if (err != 0)
22326 						goto done_with_assess;
22327 				}
22328 			}
22329 		}
22330 		break;
22331 
22332 	case MHIOCGRP_REGISTERANDIGNOREKEY:
22333 		SD_TRACE(SD_LOG_IOCTL, un, "MHIOCGRP_REGISTERANDIGNOREKEY\n");
22334 		if ((err = drv_priv(cred_p)) != EPERM) {
22335 			if (un->un_reservation_type == SD_SCSI2_RESERVATION) {
22336 				err = ENOTSUP;
22337 			} else if (arg != NULL) {
22338 				mhioc_registerandignorekey_t r_and_i;
22339 				if (ddi_copyin((void *)arg, (void *)&r_and_i,
22340 				    sizeof (mhioc_registerandignorekey_t),
22341 				    flag) != 0) {
22342 					err = EFAULT;
22343 				} else {
22344 					err =
22345 					    sd_send_scsi_PERSISTENT_RESERVE_OUT(
22346 					    ssc, SD_SCSI3_REGISTERANDIGNOREKEY,
22347 					    (uchar_t *)&r_and_i);
22348 					if (err != 0)
22349 						goto done_with_assess;
22350 				}
22351 			}
22352 		}
22353 		break;
22354 
22355 	case USCSICMD:
22356 		SD_TRACE(SD_LOG_IOCTL, un, "USCSICMD\n");
22357 		cr = ddi_get_cred();
22358 		if ((drv_priv(cred_p) != 0) && (drv_priv(cr) != 0)) {
22359 			err = EPERM;
22360 		} else {
22361 			enum uio_seg	uioseg;
22362 
22363 			uioseg = (flag & FKIOCTL) ? UIO_SYSSPACE :
22364 			    UIO_USERSPACE;
22365 			if (un->un_f_format_in_progress == TRUE) {
22366 				err = EAGAIN;
22367 				break;
22368 			}
22369 
22370 			err = sd_ssc_send(ssc,
22371 			    (struct uscsi_cmd *)arg,
22372 			    flag, uioseg, SD_PATH_STANDARD);
22373 			if (err != 0)
22374 				goto done_with_assess;
22375 			else
22376 				sd_ssc_assessment(ssc, SD_FMT_STANDARD);
22377 		}
22378 		break;
22379 
22380 	case CDROMPAUSE:
22381 	case CDROMRESUME:
22382 		SD_TRACE(SD_LOG_IOCTL, un, "PAUSE-RESUME\n");
22383 		if (!ISCD(un)) {
22384 			err = ENOTTY;
22385 		} else {
22386 			err = sr_pause_resume(dev, cmd);
22387 		}
22388 		break;
22389 
22390 	case CDROMPLAYMSF:
22391 		SD_TRACE(SD_LOG_IOCTL, un, "CDROMPLAYMSF\n");
22392 		if (!ISCD(un)) {
22393 			err = ENOTTY;
22394 		} else {
22395 			err = sr_play_msf(dev, (caddr_t)arg, flag);
22396 		}
22397 		break;
22398 
22399 	case CDROMPLAYTRKIND:
22400 		SD_TRACE(SD_LOG_IOCTL, un, "CDROMPLAYTRKIND\n");
22401 #if defined(__i386) || defined(__amd64)
22402 		/*
22403 		 * not supported on ATAPI CD drives, use CDROMPLAYMSF instead
22404 		 */
22405 		if (!ISCD(un) || (un->un_f_cfg_is_atapi == TRUE)) {
22406 #else
22407 		if (!ISCD(un)) {
22408 #endif
22409 			err = ENOTTY;
22410 		} else {
22411 			err = sr_play_trkind(dev, (caddr_t)arg, flag);
22412 		}
22413 		break;
22414 
22415 	case CDROMREADTOCHDR:
22416 		SD_TRACE(SD_LOG_IOCTL, un, "CDROMREADTOCHDR\n");
22417 		if (!ISCD(un)) {
22418 			err = ENOTTY;
22419 		} else {
22420 			err = sr_read_tochdr(dev, (caddr_t)arg, flag);
22421 		}
22422 		break;
22423 
22424 	case CDROMREADTOCENTRY:
22425 		SD_TRACE(SD_LOG_IOCTL, un, "CDROMREADTOCENTRY\n");
22426 		if (!ISCD(un)) {
22427 			err = ENOTTY;
22428 		} else {
22429 			err = sr_read_tocentry(dev, (caddr_t)arg, flag);
22430 		}
22431 		break;
22432 
22433 	case CDROMSTOP:
22434 		SD_TRACE(SD_LOG_IOCTL, un, "CDROMSTOP\n");
22435 		if (!ISCD(un)) {
22436 			err = ENOTTY;
22437 		} else {
22438 			err = sd_send_scsi_START_STOP_UNIT(ssc, SD_START_STOP,
22439 			    SD_TARGET_STOP, SD_PATH_STANDARD);
22440 			goto done_with_assess;
22441 		}
22442 		break;
22443 
22444 	case CDROMSTART:
22445 		SD_TRACE(SD_LOG_IOCTL, un, "CDROMSTART\n");
22446 		if (!ISCD(un)) {
22447 			err = ENOTTY;
22448 		} else {
22449 			err = sd_send_scsi_START_STOP_UNIT(ssc, SD_START_STOP,
22450 			    SD_TARGET_START, SD_PATH_STANDARD);
22451 			goto done_with_assess;
22452 		}
22453 		break;
22454 
22455 	case CDROMCLOSETRAY:
22456 		SD_TRACE(SD_LOG_IOCTL, un, "CDROMCLOSETRAY\n");
22457 		if (!ISCD(un)) {
22458 			err = ENOTTY;
22459 		} else {
22460 			err = sd_send_scsi_START_STOP_UNIT(ssc, SD_START_STOP,
22461 			    SD_TARGET_CLOSE, SD_PATH_STANDARD);
22462 			goto done_with_assess;
22463 		}
22464 		break;
22465 
22466 	case FDEJECT:	/* for eject command */
22467 	case DKIOCEJECT:
22468 	case CDROMEJECT:
22469 		SD_TRACE(SD_LOG_IOCTL, un, "EJECT\n");
22470 		if (!un->un_f_eject_media_supported) {
22471 			err = ENOTTY;
22472 		} else {
22473 			err = sr_eject(dev);
22474 		}
22475 		break;
22476 
22477 	case CDROMVOLCTRL:
22478 		SD_TRACE(SD_LOG_IOCTL, un, "CDROMVOLCTRL\n");
22479 		if (!ISCD(un)) {
22480 			err = ENOTTY;
22481 		} else {
22482 			err = sr_volume_ctrl(dev, (caddr_t)arg, flag);
22483 		}
22484 		break;
22485 
22486 	case CDROMSUBCHNL:
22487 		SD_TRACE(SD_LOG_IOCTL, un, "CDROMSUBCHNL\n");
22488 		if (!ISCD(un)) {
22489 			err = ENOTTY;
22490 		} else {
22491 			err = sr_read_subchannel(dev, (caddr_t)arg, flag);
22492 		}
22493 		break;
22494 
22495 	case CDROMREADMODE2:
22496 		SD_TRACE(SD_LOG_IOCTL, un, "CDROMREADMODE2\n");
22497 		if (!ISCD(un)) {
22498 			err = ENOTTY;
22499 		} else if (un->un_f_cfg_is_atapi == TRUE) {
22500 			/*
22501 			 * If the drive supports READ CD, use that instead of
22502 			 * switching the LBA size via a MODE SELECT
22503 			 * Block Descriptor
22504 			 */
22505 			err = sr_read_cd_mode2(dev, (caddr_t)arg, flag);
22506 		} else {
22507 			err = sr_read_mode2(dev, (caddr_t)arg, flag);
22508 		}
22509 		break;
22510 
22511 	case CDROMREADMODE1:
22512 		SD_TRACE(SD_LOG_IOCTL, un, "CDROMREADMODE1\n");
22513 		if (!ISCD(un)) {
22514 			err = ENOTTY;
22515 		} else {
22516 			err = sr_read_mode1(dev, (caddr_t)arg, flag);
22517 		}
22518 		break;
22519 
22520 	case CDROMREADOFFSET:
22521 		SD_TRACE(SD_LOG_IOCTL, un, "CDROMREADOFFSET\n");
22522 		if (!ISCD(un)) {
22523 			err = ENOTTY;
22524 		} else {
22525 			err = sr_read_sony_session_offset(dev, (caddr_t)arg,
22526 			    flag);
22527 		}
22528 		break;
22529 
22530 	case CDROMSBLKMODE:
22531 		SD_TRACE(SD_LOG_IOCTL, un, "CDROMSBLKMODE\n");
22532 		/*
22533 		 * There is no means of changing block size in case of atapi
22534 		 * drives, thus return ENOTTY if drive type is atapi
22535 		 */
22536 		if (!ISCD(un) || (un->un_f_cfg_is_atapi == TRUE)) {
22537 			err = ENOTTY;
22538 		} else if (un->un_f_mmc_cap == TRUE) {
22539 
22540 			/*
22541 			 * MMC Devices do not support changing the
22542 			 * logical block size
22543 			 *
22544 			 * Note: EINVAL is being returned instead of ENOTTY to
22545 			 * maintain consistancy with the original mmc
22546 			 * driver update.
22547 			 */
22548 			err = EINVAL;
22549 		} else {
22550 			mutex_enter(SD_MUTEX(un));
22551 			if ((!(un->un_exclopen & (1<<SDPART(dev)))) ||
22552 			    (un->un_ncmds_in_transport > 0)) {
22553 				mutex_exit(SD_MUTEX(un));
22554 				err = EINVAL;
22555 			} else {
22556 				mutex_exit(SD_MUTEX(un));
22557 				err = sr_change_blkmode(dev, cmd, arg, flag);
22558 			}
22559 		}
22560 		break;
22561 
22562 	case CDROMGBLKMODE:
22563 		SD_TRACE(SD_LOG_IOCTL, un, "CDROMGBLKMODE\n");
22564 		if (!ISCD(un)) {
22565 			err = ENOTTY;
22566 		} else if ((un->un_f_cfg_is_atapi != FALSE) &&
22567 		    (un->un_f_blockcount_is_valid != FALSE)) {
22568 			/*
22569 			 * Drive is an ATAPI drive so return target block
22570 			 * size for ATAPI drives since we cannot change the
22571 			 * blocksize on ATAPI drives. Used primarily to detect
22572 			 * if an ATAPI cdrom is present.
22573 			 */
22574 			if (ddi_copyout(&un->un_tgt_blocksize, (void *)arg,
22575 			    sizeof (int), flag) != 0) {
22576 				err = EFAULT;
22577 			} else {
22578 				err = 0;
22579 			}
22580 
22581 		} else {
22582 			/*
22583 			 * Drive supports changing block sizes via a Mode
22584 			 * Select.
22585 			 */
22586 			err = sr_change_blkmode(dev, cmd, arg, flag);
22587 		}
22588 		break;
22589 
22590 	case CDROMGDRVSPEED:
22591 	case CDROMSDRVSPEED:
22592 		SD_TRACE(SD_LOG_IOCTL, un, "CDROMXDRVSPEED\n");
22593 		if (!ISCD(un)) {
22594 			err = ENOTTY;
22595 		} else if (un->un_f_mmc_cap == TRUE) {
22596 			/*
22597 			 * Note: In the future the driver implementation
22598 			 * for getting and
22599 			 * setting cd speed should entail:
22600 			 * 1) If non-mmc try the Toshiba mode page
22601 			 *    (sr_change_speed)
22602 			 * 2) If mmc but no support for Real Time Streaming try
22603 			 *    the SET CD SPEED (0xBB) command
22604 			 *   (sr_atapi_change_speed)
22605 			 * 3) If mmc and support for Real Time Streaming
22606 			 *    try the GET PERFORMANCE and SET STREAMING
22607 			 *    commands (not yet implemented, 4380808)
22608 			 */
22609 			/*
22610 			 * As per recent MMC spec, CD-ROM speed is variable
22611 			 * and changes with LBA. Since there is no such
22612 			 * things as drive speed now, fail this ioctl.
22613 			 *
22614 			 * Note: EINVAL is returned for consistancy of original
22615 			 * implementation which included support for getting
22616 			 * the drive speed of mmc devices but not setting
22617 			 * the drive speed. Thus EINVAL would be returned
22618 			 * if a set request was made for an mmc device.
22619 			 * We no longer support get or set speed for
22620 			 * mmc but need to remain consistent with regard
22621 			 * to the error code returned.
22622 			 */
22623 			err = EINVAL;
22624 		} else if (un->un_f_cfg_is_atapi == TRUE) {
22625 			err = sr_atapi_change_speed(dev, cmd, arg, flag);
22626 		} else {
22627 			err = sr_change_speed(dev, cmd, arg, flag);
22628 		}
22629 		break;
22630 
22631 	case CDROMCDDA:
22632 		SD_TRACE(SD_LOG_IOCTL, un, "CDROMCDDA\n");
22633 		if (!ISCD(un)) {
22634 			err = ENOTTY;
22635 		} else {
22636 			err = sr_read_cdda(dev, (void *)arg, flag);
22637 		}
22638 		break;
22639 
22640 	case CDROMCDXA:
22641 		SD_TRACE(SD_LOG_IOCTL, un, "CDROMCDXA\n");
22642 		if (!ISCD(un)) {
22643 			err = ENOTTY;
22644 		} else {
22645 			err = sr_read_cdxa(dev, (caddr_t)arg, flag);
22646 		}
22647 		break;
22648 
22649 	case CDROMSUBCODE:
22650 		SD_TRACE(SD_LOG_IOCTL, un, "CDROMSUBCODE\n");
22651 		if (!ISCD(un)) {
22652 			err = ENOTTY;
22653 		} else {
22654 			err = sr_read_all_subcodes(dev, (caddr_t)arg, flag);
22655 		}
22656 		break;
22657 
22658 
22659 #ifdef SDDEBUG
22660 /* RESET/ABORTS testing ioctls */
22661 	case DKIOCRESET: {
22662 		int	reset_level;
22663 
22664 		if (ddi_copyin((void *)arg, &reset_level, sizeof (int), flag)) {
22665 			err = EFAULT;
22666 		} else {
22667 			SD_INFO(SD_LOG_IOCTL, un, "sdioctl: DKIOCRESET: "
22668 			    "reset_level = 0x%lx\n", reset_level);
22669 			if (scsi_reset(SD_ADDRESS(un), reset_level)) {
22670 				err = 0;
22671 			} else {
22672 				err = EIO;
22673 			}
22674 		}
22675 		break;
22676 	}
22677 
22678 	case DKIOCABORT:
22679 		SD_INFO(SD_LOG_IOCTL, un, "sdioctl: DKIOCABORT:\n");
22680 		if (scsi_abort(SD_ADDRESS(un), NULL)) {
22681 			err = 0;
22682 		} else {
22683 			err = EIO;
22684 		}
22685 		break;
22686 #endif
22687 
22688 #ifdef SD_FAULT_INJECTION
22689 /* SDIOC FaultInjection testing ioctls */
22690 	case SDIOCSTART:
22691 	case SDIOCSTOP:
22692 	case SDIOCINSERTPKT:
22693 	case SDIOCINSERTXB:
22694 	case SDIOCINSERTUN:
22695 	case SDIOCINSERTARQ:
22696 	case SDIOCPUSH:
22697 	case SDIOCRETRIEVE:
22698 	case SDIOCRUN:
22699 		SD_INFO(SD_LOG_SDTEST, un, "sdioctl:"
22700 		    "SDIOC detected cmd:0x%X:\n", cmd);
22701 		/* call error generator */
22702 		sd_faultinjection_ioctl(cmd, arg, un);
22703 		err = 0;
22704 		break;
22705 
22706 #endif /* SD_FAULT_INJECTION */
22707 
22708 	case DKIOCFLUSHWRITECACHE:
22709 		{
22710 			struct dk_callback *dkc = (struct dk_callback *)arg;
22711 
22712 			mutex_enter(SD_MUTEX(un));
22713 			if (!un->un_f_sync_cache_supported ||
22714 			    !un->un_f_write_cache_enabled) {
22715 				err = un->un_f_sync_cache_supported ?
22716 				    0 : ENOTSUP;
22717 				mutex_exit(SD_MUTEX(un));
22718 				if ((flag & FKIOCTL) && dkc != NULL &&
22719 				    dkc->dkc_callback != NULL) {
22720 					(*dkc->dkc_callback)(dkc->dkc_cookie,
22721 					    err);
22722 					/*
22723 					 * Did callback and reported error.
22724 					 * Since we did a callback, ioctl
22725 					 * should return 0.
22726 					 */
22727 					err = 0;
22728 				}
22729 				break;
22730 			}
22731 			mutex_exit(SD_MUTEX(un));
22732 
22733 			if ((flag & FKIOCTL) && dkc != NULL &&
22734 			    dkc->dkc_callback != NULL) {
22735 				/* async SYNC CACHE request */
22736 				err = sd_send_scsi_SYNCHRONIZE_CACHE(un, dkc);
22737 			} else {
22738 				/* synchronous SYNC CACHE request */
22739 				err = sd_send_scsi_SYNCHRONIZE_CACHE(un, NULL);
22740 			}
22741 		}
22742 		break;
22743 
22744 	case DKIOCGETWCE: {
22745 
22746 		int wce;
22747 
22748 		if ((err = sd_get_write_cache_enabled(ssc, &wce)) != 0) {
22749 			break;
22750 		}
22751 
22752 		if (ddi_copyout(&wce, (void *)arg, sizeof (wce), flag)) {
22753 			err = EFAULT;
22754 		}
22755 		break;
22756 	}
22757 
22758 	case DKIOCSETWCE: {
22759 
22760 		int wce, sync_supported;
22761 
22762 		if (ddi_copyin((void *)arg, &wce, sizeof (wce), flag)) {
22763 			err = EFAULT;
22764 			break;
22765 		}
22766 
22767 		/*
22768 		 * Synchronize multiple threads trying to enable
22769 		 * or disable the cache via the un_f_wcc_cv
22770 		 * condition variable.
22771 		 */
22772 		mutex_enter(SD_MUTEX(un));
22773 
22774 		/*
22775 		 * Don't allow the cache to be enabled if the
22776 		 * config file has it disabled.
22777 		 */
22778 		if (un->un_f_opt_disable_cache && wce) {
22779 			mutex_exit(SD_MUTEX(un));
22780 			err = EINVAL;
22781 			break;
22782 		}
22783 
22784 		/*
22785 		 * Wait for write cache change in progress
22786 		 * bit to be clear before proceeding.
22787 		 */
22788 		while (un->un_f_wcc_inprog)
22789 			cv_wait(&un->un_wcc_cv, SD_MUTEX(un));
22790 
22791 		un->un_f_wcc_inprog = 1;
22792 
22793 		if (un->un_f_write_cache_enabled && wce == 0) {
22794 			/*
22795 			 * Disable the write cache.  Don't clear
22796 			 * un_f_write_cache_enabled until after
22797 			 * the mode select and flush are complete.
22798 			 */
22799 			sync_supported = un->un_f_sync_cache_supported;
22800 
22801 			/*
22802 			 * If cache flush is suppressed, we assume that the
22803 			 * controller firmware will take care of managing the
22804 			 * write cache for us: no need to explicitly
22805 			 * disable it.
22806 			 */
22807 			if (!un->un_f_suppress_cache_flush) {
22808 				mutex_exit(SD_MUTEX(un));
22809 				if ((err = sd_cache_control(ssc,
22810 				    SD_CACHE_NOCHANGE,
22811 				    SD_CACHE_DISABLE)) == 0 &&
22812 				    sync_supported) {
22813 					err = sd_send_scsi_SYNCHRONIZE_CACHE(un,
22814 					    NULL);
22815 				}
22816 			} else {
22817 				mutex_exit(SD_MUTEX(un));
22818 			}
22819 
22820 			mutex_enter(SD_MUTEX(un));
22821 			if (err == 0) {
22822 				un->un_f_write_cache_enabled = 0;
22823 			}
22824 
22825 		} else if (!un->un_f_write_cache_enabled && wce != 0) {
22826 			/*
22827 			 * Set un_f_write_cache_enabled first, so there is
22828 			 * no window where the cache is enabled, but the
22829 			 * bit says it isn't.
22830 			 */
22831 			un->un_f_write_cache_enabled = 1;
22832 
22833 			/*
22834 			 * If cache flush is suppressed, we assume that the
22835 			 * controller firmware will take care of managing the
22836 			 * write cache for us: no need to explicitly
22837 			 * enable it.
22838 			 */
22839 			if (!un->un_f_suppress_cache_flush) {
22840 				mutex_exit(SD_MUTEX(un));
22841 				err = sd_cache_control(ssc, SD_CACHE_NOCHANGE,
22842 				    SD_CACHE_ENABLE);
22843 			} else {
22844 				mutex_exit(SD_MUTEX(un));
22845 			}
22846 
22847 			mutex_enter(SD_MUTEX(un));
22848 
22849 			if (err) {
22850 				un->un_f_write_cache_enabled = 0;
22851 			}
22852 		}
22853 
22854 		un->un_f_wcc_inprog = 0;
22855 		cv_broadcast(&un->un_wcc_cv);
22856 		mutex_exit(SD_MUTEX(un));
22857 		break;
22858 	}
22859 
22860 	default:
22861 		err = ENOTTY;
22862 		break;
22863 	}
22864 	mutex_enter(SD_MUTEX(un));
22865 	un->un_ncmds_in_driver--;
22866 	ASSERT(un->un_ncmds_in_driver >= 0);
22867 	mutex_exit(SD_MUTEX(un));
22868 
22869 
22870 done_without_assess:
22871 	sd_ssc_fini(ssc);
22872 
22873 	SD_TRACE(SD_LOG_IOCTL, un, "sdioctl: exit: %d\n", err);
22874 	return (err);
22875 
22876 done_with_assess:
22877 	mutex_enter(SD_MUTEX(un));
22878 	un->un_ncmds_in_driver--;
22879 	ASSERT(un->un_ncmds_in_driver >= 0);
22880 	mutex_exit(SD_MUTEX(un));
22881 
22882 done_quick_assess:
22883 	if (err != 0)
22884 		sd_ssc_assessment(ssc, SD_FMT_IGNORE);
22885 	/* Uninitialize sd_ssc_t pointer */
22886 	sd_ssc_fini(ssc);
22887 
22888 	SD_TRACE(SD_LOG_IOCTL, un, "sdioctl: exit: %d\n", err);
22889 	return (err);
22890 }
22891 
22892 
22893 /*
22894  *    Function: sd_dkio_ctrl_info
22895  *
22896  * Description: This routine is the driver entry point for handling controller
22897  *		information ioctl requests (DKIOCINFO).
22898  *
22899  *   Arguments: dev  - the device number
22900  *		arg  - pointer to user provided dk_cinfo structure
22901  *		       specifying the controller type and attributes.
22902  *		flag - this argument is a pass through to ddi_copyxxx()
22903  *		       directly from the mode argument of ioctl().
22904  *
22905  * Return Code: 0
22906  *		EFAULT
22907  *		ENXIO
22908  */
22909 
22910 static int
22911 sd_dkio_ctrl_info(dev_t dev, caddr_t arg, int flag)
22912 {
22913 	struct sd_lun	*un = NULL;
22914 	struct dk_cinfo	*info;
22915 	dev_info_t	*pdip;
22916 	int		lun, tgt;
22917 
22918 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
22919 		return (ENXIO);
22920 	}
22921 
22922 	info = (struct dk_cinfo *)
22923 	    kmem_zalloc(sizeof (struct dk_cinfo), KM_SLEEP);
22924 
22925 	switch (un->un_ctype) {
22926 	case CTYPE_CDROM:
22927 		info->dki_ctype = DKC_CDROM;
22928 		break;
22929 	default:
22930 		info->dki_ctype = DKC_SCSI_CCS;
22931 		break;
22932 	}
22933 	pdip = ddi_get_parent(SD_DEVINFO(un));
22934 	info->dki_cnum = ddi_get_instance(pdip);
22935 	if (strlen(ddi_get_name(pdip)) < DK_DEVLEN) {
22936 		(void) strcpy(info->dki_cname, ddi_get_name(pdip));
22937 	} else {
22938 		(void) strncpy(info->dki_cname, ddi_node_name(pdip),
22939 		    DK_DEVLEN - 1);
22940 	}
22941 
22942 	lun = ddi_prop_get_int(DDI_DEV_T_ANY, SD_DEVINFO(un),
22943 	    DDI_PROP_DONTPASS, SCSI_ADDR_PROP_LUN, 0);
22944 	tgt = ddi_prop_get_int(DDI_DEV_T_ANY, SD_DEVINFO(un),
22945 	    DDI_PROP_DONTPASS, SCSI_ADDR_PROP_TARGET, 0);
22946 
22947 	/* Unit Information */
22948 	info->dki_unit = ddi_get_instance(SD_DEVINFO(un));
22949 	info->dki_slave = ((tgt << 3) | lun);
22950 	(void) strncpy(info->dki_dname, ddi_driver_name(SD_DEVINFO(un)),
22951 	    DK_DEVLEN - 1);
22952 	info->dki_flags = DKI_FMTVOL;
22953 	info->dki_partition = SDPART(dev);
22954 
22955 	/* Max Transfer size of this device in blocks */
22956 	info->dki_maxtransfer = un->un_max_xfer_size / un->un_sys_blocksize;
22957 	info->dki_addr = 0;
22958 	info->dki_space = 0;
22959 	info->dki_prio = 0;
22960 	info->dki_vec = 0;
22961 
22962 	if (ddi_copyout(info, arg, sizeof (struct dk_cinfo), flag) != 0) {
22963 		kmem_free(info, sizeof (struct dk_cinfo));
22964 		return (EFAULT);
22965 	} else {
22966 		kmem_free(info, sizeof (struct dk_cinfo));
22967 		return (0);
22968 	}
22969 }
22970 
22971 
22972 /*
22973  *    Function: sd_get_media_info
22974  *
22975  * Description: This routine is the driver entry point for handling ioctl
22976  *		requests for the media type or command set profile used by the
22977  *		drive to operate on the media (DKIOCGMEDIAINFO).
22978  *
22979  *   Arguments: dev	- the device number
22980  *		arg	- pointer to user provided dk_minfo structure
22981  *			  specifying the media type, logical block size and
22982  *			  drive capacity.
22983  *		flag	- this argument is a pass through to ddi_copyxxx()
22984  *			  directly from the mode argument of ioctl().
22985  *
22986  * Return Code: 0
22987  *		EACCESS
22988  *		EFAULT
22989  *		ENXIO
22990  *		EIO
22991  */
22992 
22993 static int
22994 sd_get_media_info(dev_t dev, caddr_t arg, int flag)
22995 {
22996 	struct sd_lun		*un = NULL;
22997 	struct uscsi_cmd	com;
22998 	struct scsi_inquiry	*sinq;
22999 	struct dk_minfo		media_info;
23000 	u_longlong_t		media_capacity;
23001 	uint64_t		capacity;
23002 	uint_t			lbasize;
23003 	uchar_t			*out_data;
23004 	uchar_t			*rqbuf;
23005 	int			rval = 0;
23006 	int			rtn;
23007 	sd_ssc_t		*ssc;
23008 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL ||
23009 	    (un->un_state == SD_STATE_OFFLINE)) {
23010 		return (ENXIO);
23011 	}
23012 
23013 	SD_TRACE(SD_LOG_IOCTL_DKIO, un, "sd_get_media_info: entry\n");
23014 
23015 	out_data = kmem_zalloc(SD_PROFILE_HEADER_LEN, KM_SLEEP);
23016 	rqbuf = kmem_zalloc(SENSE_LENGTH, KM_SLEEP);
23017 
23018 	/* Issue a TUR to determine if the drive is ready with media present */
23019 	ssc = sd_ssc_init(un);
23020 	rval = sd_send_scsi_TEST_UNIT_READY(ssc, SD_CHECK_FOR_MEDIA);
23021 	if (rval == ENXIO) {
23022 		goto done;
23023 	} else if (rval != 0) {
23024 		sd_ssc_assessment(ssc, SD_FMT_IGNORE);
23025 	}
23026 
23027 	/* Now get configuration data */
23028 	if (ISCD(un)) {
23029 		media_info.dki_media_type = DK_CDROM;
23030 
23031 		/* Allow SCMD_GET_CONFIGURATION to MMC devices only */
23032 		if (un->un_f_mmc_cap == TRUE) {
23033 			rtn = sd_send_scsi_GET_CONFIGURATION(ssc, &com, rqbuf,
23034 			    SENSE_LENGTH, out_data, SD_PROFILE_HEADER_LEN,
23035 			    SD_PATH_STANDARD);
23036 
23037 			if (rtn) {
23038 				/*
23039 				 * We ignore all failures for CD and need to
23040 				 * put the assessment before processing code
23041 				 * to avoid missing assessment for FMA.
23042 				 */
23043 				sd_ssc_assessment(ssc, SD_FMT_IGNORE);
23044 				/*
23045 				 * Failed for other than an illegal request
23046 				 * or command not supported
23047 				 */
23048 				if ((com.uscsi_status == STATUS_CHECK) &&
23049 				    (com.uscsi_rqstatus == STATUS_GOOD)) {
23050 					if ((rqbuf[2] != KEY_ILLEGAL_REQUEST) ||
23051 					    (rqbuf[12] != 0x20)) {
23052 						rval = EIO;
23053 						goto no_assessment;
23054 					}
23055 				}
23056 			} else {
23057 				/*
23058 				 * The GET CONFIGURATION command succeeded
23059 				 * so set the media type according to the
23060 				 * returned data
23061 				 */
23062 				media_info.dki_media_type = out_data[6];
23063 				media_info.dki_media_type <<= 8;
23064 				media_info.dki_media_type |= out_data[7];
23065 			}
23066 		}
23067 	} else {
23068 		/*
23069 		 * The profile list is not available, so we attempt to identify
23070 		 * the media type based on the inquiry data
23071 		 */
23072 		sinq = un->un_sd->sd_inq;
23073 		if ((sinq->inq_dtype == DTYPE_DIRECT) ||
23074 		    (sinq->inq_dtype == DTYPE_OPTICAL)) {
23075 			/* This is a direct access device  or optical disk */
23076 			media_info.dki_media_type = DK_FIXED_DISK;
23077 
23078 			if ((bcmp(sinq->inq_vid, "IOMEGA", 6) == 0) ||
23079 			    (bcmp(sinq->inq_vid, "iomega", 6) == 0)) {
23080 				if ((bcmp(sinq->inq_pid, "ZIP", 3) == 0)) {
23081 					media_info.dki_media_type = DK_ZIP;
23082 				} else if (
23083 				    (bcmp(sinq->inq_pid, "jaz", 3) == 0)) {
23084 					media_info.dki_media_type = DK_JAZ;
23085 				}
23086 			}
23087 		} else {
23088 			/*
23089 			 * Not a CD, direct access or optical disk so return
23090 			 * unknown media
23091 			 */
23092 			media_info.dki_media_type = DK_UNKNOWN;
23093 		}
23094 	}
23095 
23096 	/* Now read the capacity so we can provide the lbasize and capacity */
23097 	rval = sd_send_scsi_READ_CAPACITY(ssc, &capacity, &lbasize,
23098 	    SD_PATH_DIRECT);
23099 	switch (rval) {
23100 	case 0:
23101 		break;
23102 	case EACCES:
23103 		rval = EACCES;
23104 		goto done;
23105 	default:
23106 		rval = EIO;
23107 		goto done;
23108 	}
23109 
23110 	/*
23111 	 * If lun is expanded dynamically, update the un structure.
23112 	 */
23113 	mutex_enter(SD_MUTEX(un));
23114 	if ((un->un_f_blockcount_is_valid == TRUE) &&
23115 	    (un->un_f_tgt_blocksize_is_valid == TRUE) &&
23116 	    (capacity > un->un_blockcount)) {
23117 		sd_update_block_info(un, lbasize, capacity);
23118 	}
23119 	mutex_exit(SD_MUTEX(un));
23120 
23121 	media_info.dki_lbsize = lbasize;
23122 	media_capacity = capacity;
23123 
23124 	/*
23125 	 * sd_send_scsi_READ_CAPACITY() reports capacity in
23126 	 * un->un_sys_blocksize chunks. So we need to convert it into
23127 	 * cap.lbasize chunks.
23128 	 */
23129 	media_capacity *= un->un_sys_blocksize;
23130 	media_capacity /= lbasize;
23131 	media_info.dki_capacity = media_capacity;
23132 
23133 	if (ddi_copyout(&media_info, arg, sizeof (struct dk_minfo), flag)) {
23134 		rval = EFAULT;
23135 		/* Put goto. Anybody might add some code below in future */
23136 		goto no_assessment;
23137 	}
23138 done:
23139 	if (rval != 0) {
23140 		if (rval == EIO)
23141 			sd_ssc_assessment(ssc, SD_FMT_STATUS_CHECK);
23142 		else
23143 			sd_ssc_assessment(ssc, SD_FMT_IGNORE);
23144 	}
23145 no_assessment:
23146 	sd_ssc_fini(ssc);
23147 	kmem_free(out_data, SD_PROFILE_HEADER_LEN);
23148 	kmem_free(rqbuf, SENSE_LENGTH);
23149 	return (rval);
23150 }
23151 
23152 /*
23153  *    Function: sd_get_media_info_ext
23154  *
23155  * Description: This routine is the driver entry point for handling ioctl
23156  *		requests for the media type or command set profile used by the
23157  *		drive to operate on the media (DKIOCGMEDIAINFOEXT). The
23158  *		difference this ioctl and DKIOCGMEDIAINFO is the return value
23159  *		of this ioctl contains both logical block size and physical
23160  *		block size.
23161  *
23162  *
23163  *   Arguments: dev	- the device number
23164  *		arg	- pointer to user provided dk_minfo_ext structure
23165  *			  specifying the media type, logical block size,
23166  *			  physical block size and disk capacity.
23167  *		flag	- this argument is a pass through to ddi_copyxxx()
23168  *			  directly from the mode argument of ioctl().
23169  *
23170  * Return Code: 0
23171  *		EACCESS
23172  *		EFAULT
23173  *		ENXIO
23174  *		EIO
23175  */
23176 
23177 static int
23178 sd_get_media_info_ext(dev_t dev, caddr_t arg, int flag)
23179 {
23180 	struct sd_lun		*un = NULL;
23181 	struct uscsi_cmd	com;
23182 	struct scsi_inquiry	*sinq;
23183 	struct dk_minfo_ext	media_info_ext;
23184 	u_longlong_t		media_capacity;
23185 	uint64_t		capacity;
23186 	uint_t			lbasize;
23187 	uint_t			pbsize;
23188 	uchar_t			*out_data;
23189 	uchar_t			*rqbuf;
23190 	int			rval = 0;
23191 	int			rtn;
23192 	sd_ssc_t		*ssc;
23193 
23194 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL ||
23195 	    (un->un_state == SD_STATE_OFFLINE)) {
23196 		return (ENXIO);
23197 	}
23198 
23199 	SD_TRACE(SD_LOG_IOCTL_DKIO, un, "sd_get_media_info_ext: entry\n");
23200 
23201 	out_data = kmem_zalloc(SD_PROFILE_HEADER_LEN, KM_SLEEP);
23202 	rqbuf = kmem_zalloc(SENSE_LENGTH, KM_SLEEP);
23203 	ssc = sd_ssc_init(un);
23204 
23205 	/* Issue a TUR to determine if the drive is ready with media present */
23206 	rval = sd_send_scsi_TEST_UNIT_READY(ssc, SD_CHECK_FOR_MEDIA);
23207 	if (rval == ENXIO) {
23208 		goto done;
23209 	} else if (rval != 0) {
23210 		sd_ssc_assessment(ssc, SD_FMT_IGNORE);
23211 	}
23212 
23213 	/* Now get configuration data */
23214 	if (ISCD(un)) {
23215 		media_info_ext.dki_media_type = DK_CDROM;
23216 
23217 		/* Allow SCMD_GET_CONFIGURATION to MMC devices only */
23218 		if (un->un_f_mmc_cap == TRUE) {
23219 			rtn = sd_send_scsi_GET_CONFIGURATION(ssc, &com, rqbuf,
23220 			    SENSE_LENGTH, out_data, SD_PROFILE_HEADER_LEN,
23221 			    SD_PATH_STANDARD);
23222 
23223 			if (rtn) {
23224 				/*
23225 				 * We ignore all failures for CD and need to
23226 				 * put the assessment before processing code
23227 				 * to avoid missing assessment for FMA.
23228 				 */
23229 				sd_ssc_assessment(ssc, SD_FMT_IGNORE);
23230 				/*
23231 				 * Failed for other than an illegal request
23232 				 * or command not supported
23233 				 */
23234 				if ((com.uscsi_status == STATUS_CHECK) &&
23235 				    (com.uscsi_rqstatus == STATUS_GOOD)) {
23236 					if ((rqbuf[2] != KEY_ILLEGAL_REQUEST) ||
23237 					    (rqbuf[12] != 0x20)) {
23238 						rval = EIO;
23239 						goto no_assessment;
23240 					}
23241 				}
23242 			} else {
23243 				/*
23244 				 * The GET CONFIGURATION command succeeded
23245 				 * so set the media type according to the
23246 				 * returned data
23247 				 */
23248 				media_info_ext.dki_media_type = out_data[6];
23249 				media_info_ext.dki_media_type <<= 8;
23250 				media_info_ext.dki_media_type |= out_data[7];
23251 			}
23252 		}
23253 	} else {
23254 		/*
23255 		 * The profile list is not available, so we attempt to identify
23256 		 * the media type based on the inquiry data
23257 		 */
23258 		sinq = un->un_sd->sd_inq;
23259 		if ((sinq->inq_dtype == DTYPE_DIRECT) ||
23260 		    (sinq->inq_dtype == DTYPE_OPTICAL)) {
23261 			/* This is a direct access device  or optical disk */
23262 			media_info_ext.dki_media_type = DK_FIXED_DISK;
23263 
23264 			if ((bcmp(sinq->inq_vid, "IOMEGA", 6) == 0) ||
23265 			    (bcmp(sinq->inq_vid, "iomega", 6) == 0)) {
23266 				if ((bcmp(sinq->inq_pid, "ZIP", 3) == 0)) {
23267 					media_info_ext.dki_media_type = DK_ZIP;
23268 				} else if (
23269 				    (bcmp(sinq->inq_pid, "jaz", 3) == 0)) {
23270 					media_info_ext.dki_media_type = DK_JAZ;
23271 				}
23272 			}
23273 		} else {
23274 			/*
23275 			 * Not a CD, direct access or optical disk so return
23276 			 * unknown media
23277 			 */
23278 			media_info_ext.dki_media_type = DK_UNKNOWN;
23279 		}
23280 	}
23281 
23282 	/*
23283 	 * Now read the capacity so we can provide the lbasize,
23284 	 * pbsize and capacity.
23285 	 */
23286 	rval = sd_send_scsi_READ_CAPACITY_16(ssc, &capacity, &lbasize, &pbsize,
23287 	    SD_PATH_DIRECT);
23288 
23289 	if (rval != 0) {
23290 		rval = sd_send_scsi_READ_CAPACITY(ssc, &capacity, &lbasize,
23291 		    SD_PATH_DIRECT);
23292 
23293 		switch (rval) {
23294 		case 0:
23295 			pbsize = lbasize;
23296 			media_capacity = capacity;
23297 			/*
23298 			 * sd_send_scsi_READ_CAPACITY() reports capacity in
23299 			 * un->un_sys_blocksize chunks. So we need to convert
23300 			 * it into cap.lbsize chunks.
23301 			 */
23302 			if (un->un_f_has_removable_media) {
23303 				media_capacity *= un->un_sys_blocksize;
23304 				media_capacity /= lbasize;
23305 			}
23306 			break;
23307 		case EACCES:
23308 			rval = EACCES;
23309 			goto done;
23310 		default:
23311 			rval = EIO;
23312 			goto done;
23313 		}
23314 	} else {
23315 		media_capacity = capacity;
23316 	}
23317 
23318 	/*
23319 	 * If lun is expanded dynamically, update the un structure.
23320 	 */
23321 	mutex_enter(SD_MUTEX(un));
23322 	if ((un->un_f_blockcount_is_valid == TRUE) &&
23323 	    (un->un_f_tgt_blocksize_is_valid == TRUE) &&
23324 	    (capacity > un->un_blockcount)) {
23325 		sd_update_block_info(un, lbasize, capacity);
23326 	}
23327 	mutex_exit(SD_MUTEX(un));
23328 
23329 	media_info_ext.dki_lbsize = lbasize;
23330 	media_info_ext.dki_capacity = media_capacity;
23331 	media_info_ext.dki_pbsize = pbsize;
23332 
23333 	if (ddi_copyout(&media_info_ext, arg, sizeof (struct dk_minfo_ext),
23334 	    flag)) {
23335 		rval = EFAULT;
23336 		goto no_assessment;
23337 	}
23338 done:
23339 	if (rval != 0) {
23340 		if (rval == EIO)
23341 			sd_ssc_assessment(ssc, SD_FMT_STATUS_CHECK);
23342 		else
23343 			sd_ssc_assessment(ssc, SD_FMT_IGNORE);
23344 	}
23345 no_assessment:
23346 	sd_ssc_fini(ssc);
23347 	kmem_free(out_data, SD_PROFILE_HEADER_LEN);
23348 	kmem_free(rqbuf, SENSE_LENGTH);
23349 	return (rval);
23350 }
23351 
23352 /*
23353  *    Function: sd_check_media
23354  *
23355  * Description: This utility routine implements the functionality for the
23356  *		DKIOCSTATE ioctl. This ioctl blocks the user thread until the
23357  *		driver state changes from that specified by the user
23358  *		(inserted or ejected). For example, if the user specifies
23359  *		DKIO_EJECTED and the current media state is inserted this
23360  *		routine will immediately return DKIO_INSERTED. However, if the
23361  *		current media state is not inserted the user thread will be
23362  *		blocked until the drive state changes. If DKIO_NONE is specified
23363  *		the user thread will block until a drive state change occurs.
23364  *
23365  *   Arguments: dev  - the device number
23366  *		state  - user pointer to a dkio_state, updated with the current
23367  *			drive state at return.
23368  *
23369  * Return Code: ENXIO
23370  *		EIO
23371  *		EAGAIN
23372  *		EINTR
23373  */
23374 
23375 static int
23376 sd_check_media(dev_t dev, enum dkio_state state)
23377 {
23378 	struct sd_lun		*un = NULL;
23379 	enum dkio_state		prev_state;
23380 	opaque_t		token = NULL;
23381 	int			rval = 0;
23382 	sd_ssc_t		*ssc;
23383 	dev_t			sub_dev;
23384 
23385 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
23386 		return (ENXIO);
23387 	}
23388 
23389 	/*
23390 	 * sub_dev is used when submitting request to scsi watch.
23391 	 * All submissions are unified to use same device number.
23392 	 */
23393 	sub_dev = sd_make_device(SD_DEVINFO(un));
23394 
23395 	SD_TRACE(SD_LOG_COMMON, un, "sd_check_media: entry\n");
23396 
23397 	ssc = sd_ssc_init(un);
23398 
23399 	mutex_enter(SD_MUTEX(un));
23400 
23401 	SD_TRACE(SD_LOG_COMMON, un, "sd_check_media: "
23402 	    "state=%x, mediastate=%x\n", state, un->un_mediastate);
23403 
23404 	prev_state = un->un_mediastate;
23405 
23406 	/* is there anything to do? */
23407 	if (state == un->un_mediastate || un->un_mediastate == DKIO_NONE) {
23408 		/*
23409 		 * submit the request to the scsi_watch service;
23410 		 * scsi_media_watch_cb() does the real work
23411 		 */
23412 		mutex_exit(SD_MUTEX(un));
23413 
23414 		/*
23415 		 * This change handles the case where a scsi watch request is
23416 		 * added to a device that is powered down. To accomplish this
23417 		 * we power up the device before adding the scsi watch request,
23418 		 * since the scsi watch sends a TUR directly to the device
23419 		 * which the device cannot handle if it is powered down.
23420 		 */
23421 		if (sd_pm_entry(un) != DDI_SUCCESS) {
23422 			mutex_enter(SD_MUTEX(un));
23423 			goto done;
23424 		}
23425 
23426 		token = scsi_watch_request_submit(SD_SCSI_DEVP(un),
23427 		    sd_check_media_time, SENSE_LENGTH, sd_media_watch_cb,
23428 		    (caddr_t)sub_dev);
23429 
23430 		sd_pm_exit(un);
23431 
23432 		mutex_enter(SD_MUTEX(un));
23433 		if (token == NULL) {
23434 			rval = EAGAIN;
23435 			goto done;
23436 		}
23437 
23438 		/*
23439 		 * This is a special case IOCTL that doesn't return
23440 		 * until the media state changes. Routine sdpower
23441 		 * knows about and handles this so don't count it
23442 		 * as an active cmd in the driver, which would
23443 		 * keep the device busy to the pm framework.
23444 		 * If the count isn't decremented the device can't
23445 		 * be powered down.
23446 		 */
23447 		un->un_ncmds_in_driver--;
23448 		ASSERT(un->un_ncmds_in_driver >= 0);
23449 
23450 		/*
23451 		 * if a prior request had been made, this will be the same
23452 		 * token, as scsi_watch was designed that way.
23453 		 */
23454 		un->un_swr_token = token;
23455 		un->un_specified_mediastate = state;
23456 
23457 		/*
23458 		 * now wait for media change
23459 		 * we will not be signalled unless mediastate == state but it is
23460 		 * still better to test for this condition, since there is a
23461 		 * 2 sec cv_broadcast delay when mediastate == DKIO_INSERTED
23462 		 */
23463 		SD_TRACE(SD_LOG_COMMON, un,
23464 		    "sd_check_media: waiting for media state change\n");
23465 		while (un->un_mediastate == state) {
23466 			if (cv_wait_sig(&un->un_state_cv, SD_MUTEX(un)) == 0) {
23467 				SD_TRACE(SD_LOG_COMMON, un,
23468 				    "sd_check_media: waiting for media state "
23469 				    "was interrupted\n");
23470 				un->un_ncmds_in_driver++;
23471 				rval = EINTR;
23472 				goto done;
23473 			}
23474 			SD_TRACE(SD_LOG_COMMON, un,
23475 			    "sd_check_media: received signal, state=%x\n",
23476 			    un->un_mediastate);
23477 		}
23478 		/*
23479 		 * Inc the counter to indicate the device once again
23480 		 * has an active outstanding cmd.
23481 		 */
23482 		un->un_ncmds_in_driver++;
23483 	}
23484 
23485 	/* invalidate geometry */
23486 	if (prev_state == DKIO_INSERTED && un->un_mediastate == DKIO_EJECTED) {
23487 		sr_ejected(un);
23488 	}
23489 
23490 	if (un->un_mediastate == DKIO_INSERTED && prev_state != DKIO_INSERTED) {
23491 		uint64_t	capacity;
23492 		uint_t		lbasize;
23493 
23494 		SD_TRACE(SD_LOG_COMMON, un, "sd_check_media: media inserted\n");
23495 		mutex_exit(SD_MUTEX(un));
23496 		/*
23497 		 * Since the following routines use SD_PATH_DIRECT, we must
23498 		 * call PM directly before the upcoming disk accesses. This
23499 		 * may cause the disk to be power/spin up.
23500 		 */
23501 
23502 		if (sd_pm_entry(un) == DDI_SUCCESS) {
23503 			rval = sd_send_scsi_READ_CAPACITY(ssc,
23504 			    &capacity, &lbasize, SD_PATH_DIRECT);
23505 			if (rval != 0) {
23506 				sd_pm_exit(un);
23507 				if (rval == EIO)
23508 					sd_ssc_assessment(ssc,
23509 					    SD_FMT_STATUS_CHECK);
23510 				else
23511 					sd_ssc_assessment(ssc, SD_FMT_IGNORE);
23512 				mutex_enter(SD_MUTEX(un));
23513 				goto done;
23514 			}
23515 		} else {
23516 			rval = EIO;
23517 			mutex_enter(SD_MUTEX(un));
23518 			goto done;
23519 		}
23520 		mutex_enter(SD_MUTEX(un));
23521 
23522 		sd_update_block_info(un, lbasize, capacity);
23523 
23524 		/*
23525 		 *  Check if the media in the device is writable or not
23526 		 */
23527 		if (ISCD(un)) {
23528 			sd_check_for_writable_cd(ssc, SD_PATH_DIRECT);
23529 		}
23530 
23531 		mutex_exit(SD_MUTEX(un));
23532 		cmlb_invalidate(un->un_cmlbhandle, (void *)SD_PATH_DIRECT);
23533 		if ((cmlb_validate(un->un_cmlbhandle, 0,
23534 		    (void *)SD_PATH_DIRECT) == 0) && un->un_f_pkstats_enabled) {
23535 			sd_set_pstats(un);
23536 			SD_TRACE(SD_LOG_IO_PARTITION, un,
23537 			    "sd_check_media: un:0x%p pstats created and "
23538 			    "set\n", un);
23539 		}
23540 
23541 		rval = sd_send_scsi_DOORLOCK(ssc, SD_REMOVAL_PREVENT,
23542 		    SD_PATH_DIRECT);
23543 
23544 		sd_pm_exit(un);
23545 
23546 		if (rval != 0) {
23547 			if (rval == EIO)
23548 				sd_ssc_assessment(ssc, SD_FMT_STATUS_CHECK);
23549 			else
23550 				sd_ssc_assessment(ssc, SD_FMT_IGNORE);
23551 		}
23552 
23553 		mutex_enter(SD_MUTEX(un));
23554 	}
23555 done:
23556 	sd_ssc_fini(ssc);
23557 	un->un_f_watcht_stopped = FALSE;
23558 	if (token != NULL && un->un_swr_token != NULL) {
23559 		/*
23560 		 * Use of this local token and the mutex ensures that we avoid
23561 		 * some race conditions associated with terminating the
23562 		 * scsi watch.
23563 		 */
23564 		token = un->un_swr_token;
23565 		mutex_exit(SD_MUTEX(un));
23566 		(void) scsi_watch_request_terminate(token,
23567 		    SCSI_WATCH_TERMINATE_WAIT);
23568 		if (scsi_watch_get_ref_count(token) == 0) {
23569 			mutex_enter(SD_MUTEX(un));
23570 			un->un_swr_token = (opaque_t)NULL;
23571 		} else {
23572 			mutex_enter(SD_MUTEX(un));
23573 		}
23574 	}
23575 
23576 	/*
23577 	 * Update the capacity kstat value, if no media previously
23578 	 * (capacity kstat is 0) and a media has been inserted
23579 	 * (un_f_blockcount_is_valid == TRUE)
23580 	 */
23581 	if (un->un_errstats) {
23582 		struct sd_errstats	*stp = NULL;
23583 
23584 		stp = (struct sd_errstats *)un->un_errstats->ks_data;
23585 		if ((stp->sd_capacity.value.ui64 == 0) &&
23586 		    (un->un_f_blockcount_is_valid == TRUE)) {
23587 			stp->sd_capacity.value.ui64 =
23588 			    (uint64_t)((uint64_t)un->un_blockcount *
23589 			    un->un_sys_blocksize);
23590 		}
23591 	}
23592 	mutex_exit(SD_MUTEX(un));
23593 	SD_TRACE(SD_LOG_COMMON, un, "sd_check_media: done\n");
23594 	return (rval);
23595 }
23596 
23597 
23598 /*
23599  *    Function: sd_delayed_cv_broadcast
23600  *
23601  * Description: Delayed cv_broadcast to allow for target to recover from media
23602  *		insertion.
23603  *
23604  *   Arguments: arg - driver soft state (unit) structure
23605  */
23606 
23607 static void
23608 sd_delayed_cv_broadcast(void *arg)
23609 {
23610 	struct sd_lun *un = arg;
23611 
23612 	SD_TRACE(SD_LOG_COMMON, un, "sd_delayed_cv_broadcast\n");
23613 
23614 	mutex_enter(SD_MUTEX(un));
23615 	un->un_dcvb_timeid = NULL;
23616 	cv_broadcast(&un->un_state_cv);
23617 	mutex_exit(SD_MUTEX(un));
23618 }
23619 
23620 
23621 /*
23622  *    Function: sd_media_watch_cb
23623  *
23624  * Description: Callback routine used for support of the DKIOCSTATE ioctl. This
23625  *		routine processes the TUR sense data and updates the driver
23626  *		state if a transition has occurred. The user thread
23627  *		(sd_check_media) is then signalled.
23628  *
23629  *   Arguments: arg -   the device 'dev_t' is used for context to discriminate
23630  *			among multiple watches that share this callback function
23631  *		resultp - scsi watch facility result packet containing scsi
23632  *			  packet, status byte and sense data
23633  *
23634  * Return Code: 0 for success, -1 for failure
23635  */
23636 
23637 static int
23638 sd_media_watch_cb(caddr_t arg, struct scsi_watch_result *resultp)
23639 {
23640 	struct sd_lun			*un;
23641 	struct scsi_status		*statusp = resultp->statusp;
23642 	uint8_t				*sensep = (uint8_t *)resultp->sensep;
23643 	enum dkio_state			state = DKIO_NONE;
23644 	dev_t				dev = (dev_t)arg;
23645 	uchar_t				actual_sense_length;
23646 	uint8_t				skey, asc, ascq;
23647 
23648 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
23649 		return (-1);
23650 	}
23651 	actual_sense_length = resultp->actual_sense_length;
23652 
23653 	mutex_enter(SD_MUTEX(un));
23654 	SD_TRACE(SD_LOG_COMMON, un,
23655 	    "sd_media_watch_cb: status=%x, sensep=%p, len=%x\n",
23656 	    *((char *)statusp), (void *)sensep, actual_sense_length);
23657 
23658 	if (resultp->pkt->pkt_reason == CMD_DEV_GONE) {
23659 		un->un_mediastate = DKIO_DEV_GONE;
23660 		cv_broadcast(&un->un_state_cv);
23661 		mutex_exit(SD_MUTEX(un));
23662 
23663 		return (0);
23664 	}
23665 
23666 	/*
23667 	 * If there was a check condition then sensep points to valid sense data
23668 	 * If status was not a check condition but a reservation or busy status
23669 	 * then the new state is DKIO_NONE
23670 	 */
23671 	if (sensep != NULL) {
23672 		skey = scsi_sense_key(sensep);
23673 		asc = scsi_sense_asc(sensep);
23674 		ascq = scsi_sense_ascq(sensep);
23675 
23676 		SD_INFO(SD_LOG_COMMON, un,
23677 		    "sd_media_watch_cb: sense KEY=%x, ASC=%x, ASCQ=%x\n",
23678 		    skey, asc, ascq);
23679 		/* This routine only uses up to 13 bytes of sense data. */
23680 		if (actual_sense_length >= 13) {
23681 			if (skey == KEY_UNIT_ATTENTION) {
23682 				if (asc == 0x28) {
23683 					state = DKIO_INSERTED;
23684 				}
23685 			} else if (skey == KEY_NOT_READY) {
23686 				/*
23687 				 * Sense data of 02/06/00 means that the
23688 				 * drive could not read the media (No
23689 				 * reference position found). In this case
23690 				 * to prevent a hang on the DKIOCSTATE IOCTL
23691 				 * we set the media state to DKIO_INSERTED.
23692 				 */
23693 				if (asc == 0x06 && ascq == 0x00)
23694 					state = DKIO_INSERTED;
23695 
23696 				/*
23697 				 * if 02/04/02  means that the host
23698 				 * should send start command. Explicitly
23699 				 * leave the media state as is
23700 				 * (inserted) as the media is inserted
23701 				 * and host has stopped device for PM
23702 				 * reasons. Upon next true read/write
23703 				 * to this media will bring the
23704 				 * device to the right state good for
23705 				 * media access.
23706 				 */
23707 				if (asc == 0x3a) {
23708 					state = DKIO_EJECTED;
23709 				} else {
23710 					/*
23711 					 * If the drive is busy with an
23712 					 * operation or long write, keep the
23713 					 * media in an inserted state.
23714 					 */
23715 
23716 					if ((asc == 0x04) &&
23717 					    ((ascq == 0x02) ||
23718 					    (ascq == 0x07) ||
23719 					    (ascq == 0x08))) {
23720 						state = DKIO_INSERTED;
23721 					}
23722 				}
23723 			} else if (skey == KEY_NO_SENSE) {
23724 				if ((asc == 0x00) && (ascq == 0x00)) {
23725 					/*
23726 					 * Sense Data 00/00/00 does not provide
23727 					 * any information about the state of
23728 					 * the media. Ignore it.
23729 					 */
23730 					mutex_exit(SD_MUTEX(un));
23731 					return (0);
23732 				}
23733 			}
23734 		}
23735 	} else if ((*((char *)statusp) == STATUS_GOOD) &&
23736 	    (resultp->pkt->pkt_reason == CMD_CMPLT)) {
23737 		state = DKIO_INSERTED;
23738 	}
23739 
23740 	SD_TRACE(SD_LOG_COMMON, un,
23741 	    "sd_media_watch_cb: state=%x, specified=%x\n",
23742 	    state, un->un_specified_mediastate);
23743 
23744 	/*
23745 	 * now signal the waiting thread if this is *not* the specified state;
23746 	 * delay the signal if the state is DKIO_INSERTED to allow the target
23747 	 * to recover
23748 	 */
23749 	if (state != un->un_specified_mediastate) {
23750 		un->un_mediastate = state;
23751 		if (state == DKIO_INSERTED) {
23752 			/*
23753 			 * delay the signal to give the drive a chance
23754 			 * to do what it apparently needs to do
23755 			 */
23756 			SD_TRACE(SD_LOG_COMMON, un,
23757 			    "sd_media_watch_cb: delayed cv_broadcast\n");
23758 			if (un->un_dcvb_timeid == NULL) {
23759 				un->un_dcvb_timeid =
23760 				    timeout(sd_delayed_cv_broadcast, un,
23761 				    drv_usectohz((clock_t)MEDIA_ACCESS_DELAY));
23762 			}
23763 		} else {
23764 			SD_TRACE(SD_LOG_COMMON, un,
23765 			    "sd_media_watch_cb: immediate cv_broadcast\n");
23766 			cv_broadcast(&un->un_state_cv);
23767 		}
23768 	}
23769 	mutex_exit(SD_MUTEX(un));
23770 	return (0);
23771 }
23772 
23773 
23774 /*
23775  *    Function: sd_dkio_get_temp
23776  *
23777  * Description: This routine is the driver entry point for handling ioctl
23778  *		requests to get the disk temperature.
23779  *
23780  *   Arguments: dev  - the device number
23781  *		arg  - pointer to user provided dk_temperature structure.
23782  *		flag - this argument is a pass through to ddi_copyxxx()
23783  *		       directly from the mode argument of ioctl().
23784  *
23785  * Return Code: 0
23786  *		EFAULT
23787  *		ENXIO
23788  *		EAGAIN
23789  */
23790 
23791 static int
23792 sd_dkio_get_temp(dev_t dev, caddr_t arg, int flag)
23793 {
23794 	struct sd_lun		*un = NULL;
23795 	struct dk_temperature	*dktemp = NULL;
23796 	uchar_t			*temperature_page;
23797 	int			rval = 0;
23798 	int			path_flag = SD_PATH_STANDARD;
23799 	sd_ssc_t		*ssc;
23800 
23801 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
23802 		return (ENXIO);
23803 	}
23804 
23805 	ssc = sd_ssc_init(un);
23806 	dktemp = kmem_zalloc(sizeof (struct dk_temperature), KM_SLEEP);
23807 
23808 	/* copyin the disk temp argument to get the user flags */
23809 	if (ddi_copyin((void *)arg, dktemp,
23810 	    sizeof (struct dk_temperature), flag) != 0) {
23811 		rval = EFAULT;
23812 		goto done;
23813 	}
23814 
23815 	/* Initialize the temperature to invalid. */
23816 	dktemp->dkt_cur_temp = (short)DKT_INVALID_TEMP;
23817 	dktemp->dkt_ref_temp = (short)DKT_INVALID_TEMP;
23818 
23819 	/*
23820 	 * Note: Investigate removing the "bypass pm" semantic.
23821 	 * Can we just bypass PM always?
23822 	 */
23823 	if (dktemp->dkt_flags & DKT_BYPASS_PM) {
23824 		path_flag = SD_PATH_DIRECT;
23825 		ASSERT(!mutex_owned(&un->un_pm_mutex));
23826 		mutex_enter(&un->un_pm_mutex);
23827 		if (SD_DEVICE_IS_IN_LOW_POWER(un)) {
23828 			/*
23829 			 * If DKT_BYPASS_PM is set, and the drive happens to be
23830 			 * in low power mode, we can not wake it up, Need to
23831 			 * return EAGAIN.
23832 			 */
23833 			mutex_exit(&un->un_pm_mutex);
23834 			rval = EAGAIN;
23835 			goto done;
23836 		} else {
23837 			/*
23838 			 * Indicate to PM the device is busy. This is required
23839 			 * to avoid a race - i.e. the ioctl is issuing a
23840 			 * command and the pm framework brings down the device
23841 			 * to low power mode (possible power cut-off on some
23842 			 * platforms).
23843 			 */
23844 			mutex_exit(&un->un_pm_mutex);
23845 			if (sd_pm_entry(un) != DDI_SUCCESS) {
23846 				rval = EAGAIN;
23847 				goto done;
23848 			}
23849 		}
23850 	}
23851 
23852 	temperature_page = kmem_zalloc(TEMPERATURE_PAGE_SIZE, KM_SLEEP);
23853 
23854 	rval = sd_send_scsi_LOG_SENSE(ssc, temperature_page,
23855 	    TEMPERATURE_PAGE_SIZE, TEMPERATURE_PAGE, 1, 0, path_flag);
23856 	if (rval != 0)
23857 		goto done2;
23858 
23859 	/*
23860 	 * For the current temperature verify that the parameter length is 0x02
23861 	 * and the parameter code is 0x00
23862 	 */
23863 	if ((temperature_page[7] == 0x02) && (temperature_page[4] == 0x00) &&
23864 	    (temperature_page[5] == 0x00)) {
23865 		if (temperature_page[9] == 0xFF) {
23866 			dktemp->dkt_cur_temp = (short)DKT_INVALID_TEMP;
23867 		} else {
23868 			dktemp->dkt_cur_temp = (short)(temperature_page[9]);
23869 		}
23870 	}
23871 
23872 	/*
23873 	 * For the reference temperature verify that the parameter
23874 	 * length is 0x02 and the parameter code is 0x01
23875 	 */
23876 	if ((temperature_page[13] == 0x02) && (temperature_page[10] == 0x00) &&
23877 	    (temperature_page[11] == 0x01)) {
23878 		if (temperature_page[15] == 0xFF) {
23879 			dktemp->dkt_ref_temp = (short)DKT_INVALID_TEMP;
23880 		} else {
23881 			dktemp->dkt_ref_temp = (short)(temperature_page[15]);
23882 		}
23883 	}
23884 
23885 	/* Do the copyout regardless of the temperature commands status. */
23886 	if (ddi_copyout(dktemp, (void *)arg, sizeof (struct dk_temperature),
23887 	    flag) != 0) {
23888 		rval = EFAULT;
23889 		goto done1;
23890 	}
23891 
23892 done2:
23893 	if (rval != 0) {
23894 		if (rval == EIO)
23895 			sd_ssc_assessment(ssc, SD_FMT_STATUS_CHECK);
23896 		else
23897 			sd_ssc_assessment(ssc, SD_FMT_IGNORE);
23898 	}
23899 done1:
23900 	if (path_flag == SD_PATH_DIRECT) {
23901 		sd_pm_exit(un);
23902 	}
23903 
23904 	kmem_free(temperature_page, TEMPERATURE_PAGE_SIZE);
23905 done:
23906 	sd_ssc_fini(ssc);
23907 	if (dktemp != NULL) {
23908 		kmem_free(dktemp, sizeof (struct dk_temperature));
23909 	}
23910 
23911 	return (rval);
23912 }
23913 
23914 
23915 /*
23916  *    Function: sd_log_page_supported
23917  *
23918  * Description: This routine uses sd_send_scsi_LOG_SENSE to find the list of
23919  *		supported log pages.
23920  *
23921  *   Arguments: ssc   - ssc contains pointer to driver soft state (unit)
23922  *                      structure for this target.
23923  *		log_page -
23924  *
23925  * Return Code: -1 - on error (log sense is optional and may not be supported).
23926  *		0  - log page not found.
23927  *  		1  - log page found.
23928  */
23929 
23930 static int
23931 sd_log_page_supported(sd_ssc_t *ssc, int log_page)
23932 {
23933 	uchar_t *log_page_data;
23934 	int	i;
23935 	int	match = 0;
23936 	int	log_size;
23937 	int	status = 0;
23938 	struct sd_lun	*un;
23939 
23940 	ASSERT(ssc != NULL);
23941 	un = ssc->ssc_un;
23942 	ASSERT(un != NULL);
23943 
23944 	log_page_data = kmem_zalloc(0xFF, KM_SLEEP);
23945 
23946 	status = sd_send_scsi_LOG_SENSE(ssc, log_page_data, 0xFF, 0, 0x01, 0,
23947 	    SD_PATH_DIRECT);
23948 
23949 	if (status != 0) {
23950 		if (status == EIO) {
23951 			/*
23952 			 * Some disks do not support log sense, we
23953 			 * should ignore this kind of error(sense key is
23954 			 * 0x5 - illegal request).
23955 			 */
23956 			uint8_t *sensep;
23957 			int senlen;
23958 
23959 			sensep = (uint8_t *)ssc->ssc_uscsi_cmd->uscsi_rqbuf;
23960 			senlen = (int)(ssc->ssc_uscsi_cmd->uscsi_rqlen -
23961 			    ssc->ssc_uscsi_cmd->uscsi_rqresid);
23962 
23963 			if (senlen > 0 &&
23964 			    scsi_sense_key(sensep) == KEY_ILLEGAL_REQUEST) {
23965 				sd_ssc_assessment(ssc,
23966 				    SD_FMT_IGNORE_COMPROMISE);
23967 			} else {
23968 				sd_ssc_assessment(ssc, SD_FMT_STATUS_CHECK);
23969 			}
23970 		} else {
23971 			sd_ssc_assessment(ssc, SD_FMT_IGNORE);
23972 		}
23973 
23974 		SD_ERROR(SD_LOG_COMMON, un,
23975 		    "sd_log_page_supported: failed log page retrieval\n");
23976 		kmem_free(log_page_data, 0xFF);
23977 		return (-1);
23978 	}
23979 
23980 	log_size = log_page_data[3];
23981 
23982 	/*
23983 	 * The list of supported log pages start from the fourth byte. Check
23984 	 * until we run out of log pages or a match is found.
23985 	 */
23986 	for (i = 4; (i < (log_size + 4)) && !match; i++) {
23987 		if (log_page_data[i] == log_page) {
23988 			match++;
23989 		}
23990 	}
23991 	kmem_free(log_page_data, 0xFF);
23992 	return (match);
23993 }
23994 
23995 
23996 /*
23997  *    Function: sd_mhdioc_failfast
23998  *
23999  * Description: This routine is the driver entry point for handling ioctl
24000  *		requests to enable/disable the multihost failfast option.
24001  *		(MHIOCENFAILFAST)
24002  *
24003  *   Arguments: dev	- the device number
24004  *		arg	- user specified probing interval.
24005  *		flag	- this argument is a pass through to ddi_copyxxx()
24006  *			  directly from the mode argument of ioctl().
24007  *
24008  * Return Code: 0
24009  *		EFAULT
24010  *		ENXIO
24011  */
24012 
24013 static int
24014 sd_mhdioc_failfast(dev_t dev, caddr_t arg, int flag)
24015 {
24016 	struct sd_lun	*un = NULL;
24017 	int		mh_time;
24018 	int		rval = 0;
24019 
24020 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
24021 		return (ENXIO);
24022 	}
24023 
24024 	if (ddi_copyin((void *)arg, &mh_time, sizeof (int), flag))
24025 		return (EFAULT);
24026 
24027 	if (mh_time) {
24028 		mutex_enter(SD_MUTEX(un));
24029 		un->un_resvd_status |= SD_FAILFAST;
24030 		mutex_exit(SD_MUTEX(un));
24031 		/*
24032 		 * If mh_time is INT_MAX, then this ioctl is being used for
24033 		 * SCSI-3 PGR purposes, and we don't need to spawn watch thread.
24034 		 */
24035 		if (mh_time != INT_MAX) {
24036 			rval = sd_check_mhd(dev, mh_time);
24037 		}
24038 	} else {
24039 		(void) sd_check_mhd(dev, 0);
24040 		mutex_enter(SD_MUTEX(un));
24041 		un->un_resvd_status &= ~SD_FAILFAST;
24042 		mutex_exit(SD_MUTEX(un));
24043 	}
24044 	return (rval);
24045 }
24046 
24047 
24048 /*
24049  *    Function: sd_mhdioc_takeown
24050  *
24051  * Description: This routine is the driver entry point for handling ioctl
24052  *		requests to forcefully acquire exclusive access rights to the
24053  *		multihost disk (MHIOCTKOWN).
24054  *
24055  *   Arguments: dev	- the device number
24056  *		arg	- user provided structure specifying the delay
24057  *			  parameters in milliseconds
24058  *		flag	- this argument is a pass through to ddi_copyxxx()
24059  *			  directly from the mode argument of ioctl().
24060  *
24061  * Return Code: 0
24062  *		EFAULT
24063  *		ENXIO
24064  */
24065 
24066 static int
24067 sd_mhdioc_takeown(dev_t dev, caddr_t arg, int flag)
24068 {
24069 	struct sd_lun		*un = NULL;
24070 	struct mhioctkown	*tkown = NULL;
24071 	int			rval = 0;
24072 
24073 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
24074 		return (ENXIO);
24075 	}
24076 
24077 	if (arg != NULL) {
24078 		tkown = (struct mhioctkown *)
24079 		    kmem_zalloc(sizeof (struct mhioctkown), KM_SLEEP);
24080 		rval = ddi_copyin(arg, tkown, sizeof (struct mhioctkown), flag);
24081 		if (rval != 0) {
24082 			rval = EFAULT;
24083 			goto error;
24084 		}
24085 	}
24086 
24087 	rval = sd_take_ownership(dev, tkown);
24088 	mutex_enter(SD_MUTEX(un));
24089 	if (rval == 0) {
24090 		un->un_resvd_status |= SD_RESERVE;
24091 		if (tkown != NULL && tkown->reinstate_resv_delay != 0) {
24092 			sd_reinstate_resv_delay =
24093 			    tkown->reinstate_resv_delay * 1000;
24094 		} else {
24095 			sd_reinstate_resv_delay = SD_REINSTATE_RESV_DELAY;
24096 		}
24097 		/*
24098 		 * Give the scsi_watch routine interval set by
24099 		 * the MHIOCENFAILFAST ioctl precedence here.
24100 		 */
24101 		if ((un->un_resvd_status & SD_FAILFAST) == 0) {
24102 			mutex_exit(SD_MUTEX(un));
24103 			(void) sd_check_mhd(dev, sd_reinstate_resv_delay/1000);
24104 			SD_TRACE(SD_LOG_IOCTL_MHD, un,
24105 			    "sd_mhdioc_takeown : %d\n",
24106 			    sd_reinstate_resv_delay);
24107 		} else {
24108 			mutex_exit(SD_MUTEX(un));
24109 		}
24110 		(void) scsi_reset_notify(SD_ADDRESS(un), SCSI_RESET_NOTIFY,
24111 		    sd_mhd_reset_notify_cb, (caddr_t)un);
24112 	} else {
24113 		un->un_resvd_status &= ~SD_RESERVE;
24114 		mutex_exit(SD_MUTEX(un));
24115 	}
24116 
24117 error:
24118 	if (tkown != NULL) {
24119 		kmem_free(tkown, sizeof (struct mhioctkown));
24120 	}
24121 	return (rval);
24122 }
24123 
24124 
24125 /*
24126  *    Function: sd_mhdioc_release
24127  *
24128  * Description: This routine is the driver entry point for handling ioctl
24129  *		requests to release exclusive access rights to the multihost
24130  *		disk (MHIOCRELEASE).
24131  *
24132  *   Arguments: dev	- the device number
24133  *
24134  * Return Code: 0
24135  *		ENXIO
24136  */
24137 
24138 static int
24139 sd_mhdioc_release(dev_t dev)
24140 {
24141 	struct sd_lun		*un = NULL;
24142 	timeout_id_t		resvd_timeid_save;
24143 	int			resvd_status_save;
24144 	int			rval = 0;
24145 
24146 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
24147 		return (ENXIO);
24148 	}
24149 
24150 	mutex_enter(SD_MUTEX(un));
24151 	resvd_status_save = un->un_resvd_status;
24152 	un->un_resvd_status &=
24153 	    ~(SD_RESERVE | SD_LOST_RESERVE | SD_WANT_RESERVE);
24154 	if (un->un_resvd_timeid) {
24155 		resvd_timeid_save = un->un_resvd_timeid;
24156 		un->un_resvd_timeid = NULL;
24157 		mutex_exit(SD_MUTEX(un));
24158 		(void) untimeout(resvd_timeid_save);
24159 	} else {
24160 		mutex_exit(SD_MUTEX(un));
24161 	}
24162 
24163 	/*
24164 	 * destroy any pending timeout thread that may be attempting to
24165 	 * reinstate reservation on this device.
24166 	 */
24167 	sd_rmv_resv_reclaim_req(dev);
24168 
24169 	if ((rval = sd_reserve_release(dev, SD_RELEASE)) == 0) {
24170 		mutex_enter(SD_MUTEX(un));
24171 		if ((un->un_mhd_token) &&
24172 		    ((un->un_resvd_status & SD_FAILFAST) == 0)) {
24173 			mutex_exit(SD_MUTEX(un));
24174 			(void) sd_check_mhd(dev, 0);
24175 		} else {
24176 			mutex_exit(SD_MUTEX(un));
24177 		}
24178 		(void) scsi_reset_notify(SD_ADDRESS(un), SCSI_RESET_CANCEL,
24179 		    sd_mhd_reset_notify_cb, (caddr_t)un);
24180 	} else {
24181 		/*
24182 		 * sd_mhd_watch_cb will restart the resvd recover timeout thread
24183 		 */
24184 		mutex_enter(SD_MUTEX(un));
24185 		un->un_resvd_status = resvd_status_save;
24186 		mutex_exit(SD_MUTEX(un));
24187 	}
24188 	return (rval);
24189 }
24190 
24191 
24192 /*
24193  *    Function: sd_mhdioc_register_devid
24194  *
24195  * Description: This routine is the driver entry point for handling ioctl
24196  *		requests to register the device id (MHIOCREREGISTERDEVID).
24197  *
24198  *		Note: The implementation for this ioctl has been updated to
24199  *		be consistent with the original PSARC case (1999/357)
24200  *		(4375899, 4241671, 4220005)
24201  *
24202  *   Arguments: dev	- the device number
24203  *
24204  * Return Code: 0
24205  *		ENXIO
24206  */
24207 
24208 static int
24209 sd_mhdioc_register_devid(dev_t dev)
24210 {
24211 	struct sd_lun	*un = NULL;
24212 	int		rval = 0;
24213 	sd_ssc_t	*ssc;
24214 
24215 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
24216 		return (ENXIO);
24217 	}
24218 
24219 	ASSERT(!mutex_owned(SD_MUTEX(un)));
24220 
24221 	mutex_enter(SD_MUTEX(un));
24222 
24223 	/* If a devid already exists, de-register it */
24224 	if (un->un_devid != NULL) {
24225 		ddi_devid_unregister(SD_DEVINFO(un));
24226 		/*
24227 		 * After unregister devid, needs to free devid memory
24228 		 */
24229 		ddi_devid_free(un->un_devid);
24230 		un->un_devid = NULL;
24231 	}
24232 
24233 	/* Check for reservation conflict */
24234 	mutex_exit(SD_MUTEX(un));
24235 	ssc = sd_ssc_init(un);
24236 	rval = sd_send_scsi_TEST_UNIT_READY(ssc, 0);
24237 	mutex_enter(SD_MUTEX(un));
24238 
24239 	switch (rval) {
24240 	case 0:
24241 		sd_register_devid(ssc, SD_DEVINFO(un), SD_TARGET_IS_UNRESERVED);
24242 		break;
24243 	case EACCES:
24244 		break;
24245 	default:
24246 		rval = EIO;
24247 	}
24248 
24249 	mutex_exit(SD_MUTEX(un));
24250 	if (rval != 0) {
24251 		if (rval == EIO)
24252 			sd_ssc_assessment(ssc, SD_FMT_STATUS_CHECK);
24253 		else
24254 			sd_ssc_assessment(ssc, SD_FMT_IGNORE);
24255 	}
24256 	sd_ssc_fini(ssc);
24257 	return (rval);
24258 }
24259 
24260 
24261 /*
24262  *    Function: sd_mhdioc_inkeys
24263  *
24264  * Description: This routine is the driver entry point for handling ioctl
24265  *		requests to issue the SCSI-3 Persistent In Read Keys command
24266  *		to the device (MHIOCGRP_INKEYS).
24267  *
24268  *   Arguments: dev	- the device number
24269  *		arg	- user provided in_keys structure
24270  *		flag	- this argument is a pass through to ddi_copyxxx()
24271  *			  directly from the mode argument of ioctl().
24272  *
24273  * Return Code: code returned by sd_persistent_reservation_in_read_keys()
24274  *		ENXIO
24275  *		EFAULT
24276  */
24277 
24278 static int
24279 sd_mhdioc_inkeys(dev_t dev, caddr_t arg, int flag)
24280 {
24281 	struct sd_lun		*un;
24282 	mhioc_inkeys_t		inkeys;
24283 	int			rval = 0;
24284 
24285 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
24286 		return (ENXIO);
24287 	}
24288 
24289 #ifdef _MULTI_DATAMODEL
24290 	switch (ddi_model_convert_from(flag & FMODELS)) {
24291 	case DDI_MODEL_ILP32: {
24292 		struct mhioc_inkeys32	inkeys32;
24293 
24294 		if (ddi_copyin(arg, &inkeys32,
24295 		    sizeof (struct mhioc_inkeys32), flag) != 0) {
24296 			return (EFAULT);
24297 		}
24298 		inkeys.li = (mhioc_key_list_t *)(uintptr_t)inkeys32.li;
24299 		if ((rval = sd_persistent_reservation_in_read_keys(un,
24300 		    &inkeys, flag)) != 0) {
24301 			return (rval);
24302 		}
24303 		inkeys32.generation = inkeys.generation;
24304 		if (ddi_copyout(&inkeys32, arg, sizeof (struct mhioc_inkeys32),
24305 		    flag) != 0) {
24306 			return (EFAULT);
24307 		}
24308 		break;
24309 	}
24310 	case DDI_MODEL_NONE:
24311 		if (ddi_copyin(arg, &inkeys, sizeof (mhioc_inkeys_t),
24312 		    flag) != 0) {
24313 			return (EFAULT);
24314 		}
24315 		if ((rval = sd_persistent_reservation_in_read_keys(un,
24316 		    &inkeys, flag)) != 0) {
24317 			return (rval);
24318 		}
24319 		if (ddi_copyout(&inkeys, arg, sizeof (mhioc_inkeys_t),
24320 		    flag) != 0) {
24321 			return (EFAULT);
24322 		}
24323 		break;
24324 	}
24325 
24326 #else /* ! _MULTI_DATAMODEL */
24327 
24328 	if (ddi_copyin(arg, &inkeys, sizeof (mhioc_inkeys_t), flag) != 0) {
24329 		return (EFAULT);
24330 	}
24331 	rval = sd_persistent_reservation_in_read_keys(un, &inkeys, flag);
24332 	if (rval != 0) {
24333 		return (rval);
24334 	}
24335 	if (ddi_copyout(&inkeys, arg, sizeof (mhioc_inkeys_t), flag) != 0) {
24336 		return (EFAULT);
24337 	}
24338 
24339 #endif /* _MULTI_DATAMODEL */
24340 
24341 	return (rval);
24342 }
24343 
24344 
24345 /*
24346  *    Function: sd_mhdioc_inresv
24347  *
24348  * Description: This routine is the driver entry point for handling ioctl
24349  *		requests to issue the SCSI-3 Persistent In Read Reservations
24350  *		command to the device (MHIOCGRP_INKEYS).
24351  *
24352  *   Arguments: dev	- the device number
24353  *		arg	- user provided in_resv structure
24354  *		flag	- this argument is a pass through to ddi_copyxxx()
24355  *			  directly from the mode argument of ioctl().
24356  *
24357  * Return Code: code returned by sd_persistent_reservation_in_read_resv()
24358  *		ENXIO
24359  *		EFAULT
24360  */
24361 
24362 static int
24363 sd_mhdioc_inresv(dev_t dev, caddr_t arg, int flag)
24364 {
24365 	struct sd_lun		*un;
24366 	mhioc_inresvs_t		inresvs;
24367 	int			rval = 0;
24368 
24369 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
24370 		return (ENXIO);
24371 	}
24372 
24373 #ifdef _MULTI_DATAMODEL
24374 
24375 	switch (ddi_model_convert_from(flag & FMODELS)) {
24376 	case DDI_MODEL_ILP32: {
24377 		struct mhioc_inresvs32	inresvs32;
24378 
24379 		if (ddi_copyin(arg, &inresvs32,
24380 		    sizeof (struct mhioc_inresvs32), flag) != 0) {
24381 			return (EFAULT);
24382 		}
24383 		inresvs.li = (mhioc_resv_desc_list_t *)(uintptr_t)inresvs32.li;
24384 		if ((rval = sd_persistent_reservation_in_read_resv(un,
24385 		    &inresvs, flag)) != 0) {
24386 			return (rval);
24387 		}
24388 		inresvs32.generation = inresvs.generation;
24389 		if (ddi_copyout(&inresvs32, arg,
24390 		    sizeof (struct mhioc_inresvs32), flag) != 0) {
24391 			return (EFAULT);
24392 		}
24393 		break;
24394 	}
24395 	case DDI_MODEL_NONE:
24396 		if (ddi_copyin(arg, &inresvs,
24397 		    sizeof (mhioc_inresvs_t), flag) != 0) {
24398 			return (EFAULT);
24399 		}
24400 		if ((rval = sd_persistent_reservation_in_read_resv(un,
24401 		    &inresvs, flag)) != 0) {
24402 			return (rval);
24403 		}
24404 		if (ddi_copyout(&inresvs, arg,
24405 		    sizeof (mhioc_inresvs_t), flag) != 0) {
24406 			return (EFAULT);
24407 		}
24408 		break;
24409 	}
24410 
24411 #else /* ! _MULTI_DATAMODEL */
24412 
24413 	if (ddi_copyin(arg, &inresvs, sizeof (mhioc_inresvs_t), flag) != 0) {
24414 		return (EFAULT);
24415 	}
24416 	rval = sd_persistent_reservation_in_read_resv(un, &inresvs, flag);
24417 	if (rval != 0) {
24418 		return (rval);
24419 	}
24420 	if (ddi_copyout(&inresvs, arg, sizeof (mhioc_inresvs_t), flag)) {
24421 		return (EFAULT);
24422 	}
24423 
24424 #endif /* ! _MULTI_DATAMODEL */
24425 
24426 	return (rval);
24427 }
24428 
24429 
24430 /*
24431  * The following routines support the clustering functionality described below
24432  * and implement lost reservation reclaim functionality.
24433  *
24434  * Clustering
24435  * ----------
24436  * The clustering code uses two different, independent forms of SCSI
24437  * reservation. Traditional SCSI-2 Reserve/Release and the newer SCSI-3
24438  * Persistent Group Reservations. For any particular disk, it will use either
24439  * SCSI-2 or SCSI-3 PGR but never both at the same time for the same disk.
24440  *
24441  * SCSI-2
24442  * The cluster software takes ownership of a multi-hosted disk by issuing the
24443  * MHIOCTKOWN ioctl to the disk driver. It releases ownership by issuing the
24444  * MHIOCRELEASE ioctl.  Closely related is the MHIOCENFAILFAST ioctl -- a
24445  * cluster, just after taking ownership of the disk with the MHIOCTKOWN ioctl
24446  * then issues the MHIOCENFAILFAST ioctl.  This ioctl "enables failfast" in the
24447  * driver. The meaning of failfast is that if the driver (on this host) ever
24448  * encounters the scsi error return code RESERVATION_CONFLICT from the device,
24449  * it should immediately panic the host. The motivation for this ioctl is that
24450  * if this host does encounter reservation conflict, the underlying cause is
24451  * that some other host of the cluster has decided that this host is no longer
24452  * in the cluster and has seized control of the disks for itself. Since this
24453  * host is no longer in the cluster, it ought to panic itself. The
24454  * MHIOCENFAILFAST ioctl does two things:
24455  *	(a) it sets a flag that will cause any returned RESERVATION_CONFLICT
24456  *      error to panic the host
24457  *      (b) it sets up a periodic timer to test whether this host still has
24458  *      "access" (in that no other host has reserved the device):  if the
24459  *      periodic timer gets RESERVATION_CONFLICT, the host is panicked. The
24460  *      purpose of that periodic timer is to handle scenarios where the host is
24461  *      otherwise temporarily quiescent, temporarily doing no real i/o.
24462  * The MHIOCTKOWN ioctl will "break" a reservation that is held by another host,
24463  * by issuing a SCSI Bus Device Reset.  It will then issue a SCSI Reserve for
24464  * the device itself.
24465  *
24466  * SCSI-3 PGR
24467  * A direct semantic implementation of the SCSI-3 Persistent Reservation
24468  * facility is supported through the shared multihost disk ioctls
24469  * (MHIOCGRP_INKEYS, MHIOCGRP_INRESV, MHIOCGRP_REGISTER, MHIOCGRP_RESERVE,
24470  * MHIOCGRP_PREEMPTANDABORT)
24471  *
24472  * Reservation Reclaim:
24473  * --------------------
24474  * To support the lost reservation reclaim operations this driver creates a
24475  * single thread to handle reinstating reservations on all devices that have
24476  * lost reservations sd_resv_reclaim_requests are logged for all devices that
24477  * have LOST RESERVATIONS when the scsi watch facility callsback sd_mhd_watch_cb
24478  * and the reservation reclaim thread loops through the requests to regain the
24479  * lost reservations.
24480  */
24481 
24482 /*
24483  *    Function: sd_check_mhd()
24484  *
24485  * Description: This function sets up and submits a scsi watch request or
24486  *		terminates an existing watch request. This routine is used in
24487  *		support of reservation reclaim.
24488  *
24489  *   Arguments: dev    - the device 'dev_t' is used for context to discriminate
24490  *			 among multiple watches that share the callback function
24491  *		interval - the number of microseconds specifying the watch
24492  *			   interval for issuing TEST UNIT READY commands. If
24493  *			   set to 0 the watch should be terminated. If the
24494  *			   interval is set to 0 and if the device is required
24495  *			   to hold reservation while disabling failfast, the
24496  *			   watch is restarted with an interval of
24497  *			   reinstate_resv_delay.
24498  *
24499  * Return Code: 0	   - Successful submit/terminate of scsi watch request
24500  *		ENXIO      - Indicates an invalid device was specified
24501  *		EAGAIN     - Unable to submit the scsi watch request
24502  */
24503 
24504 static int
24505 sd_check_mhd(dev_t dev, int interval)
24506 {
24507 	struct sd_lun	*un;
24508 	opaque_t	token;
24509 
24510 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
24511 		return (ENXIO);
24512 	}
24513 
24514 	/* is this a watch termination request? */
24515 	if (interval == 0) {
24516 		mutex_enter(SD_MUTEX(un));
24517 		/* if there is an existing watch task then terminate it */
24518 		if (un->un_mhd_token) {
24519 			token = un->un_mhd_token;
24520 			un->un_mhd_token = NULL;
24521 			mutex_exit(SD_MUTEX(un));
24522 			(void) scsi_watch_request_terminate(token,
24523 			    SCSI_WATCH_TERMINATE_ALL_WAIT);
24524 			mutex_enter(SD_MUTEX(un));
24525 		} else {
24526 			mutex_exit(SD_MUTEX(un));
24527 			/*
24528 			 * Note: If we return here we don't check for the
24529 			 * failfast case. This is the original legacy
24530 			 * implementation but perhaps we should be checking
24531 			 * the failfast case.
24532 			 */
24533 			return (0);
24534 		}
24535 		/*
24536 		 * If the device is required to hold reservation while
24537 		 * disabling failfast, we need to restart the scsi_watch
24538 		 * routine with an interval of reinstate_resv_delay.
24539 		 */
24540 		if (un->un_resvd_status & SD_RESERVE) {
24541 			interval = sd_reinstate_resv_delay/1000;
24542 		} else {
24543 			/* no failfast so bail */
24544 			mutex_exit(SD_MUTEX(un));
24545 			return (0);
24546 		}
24547 		mutex_exit(SD_MUTEX(un));
24548 	}
24549 
24550 	/*
24551 	 * adjust minimum time interval to 1 second,
24552 	 * and convert from msecs to usecs
24553 	 */
24554 	if (interval > 0 && interval < 1000) {
24555 		interval = 1000;
24556 	}
24557 	interval *= 1000;
24558 
24559 	/*
24560 	 * submit the request to the scsi_watch service
24561 	 */
24562 	token = scsi_watch_request_submit(SD_SCSI_DEVP(un), interval,
24563 	    SENSE_LENGTH, sd_mhd_watch_cb, (caddr_t)dev);
24564 	if (token == NULL) {
24565 		return (EAGAIN);
24566 	}
24567 
24568 	/*
24569 	 * save token for termination later on
24570 	 */
24571 	mutex_enter(SD_MUTEX(un));
24572 	un->un_mhd_token = token;
24573 	mutex_exit(SD_MUTEX(un));
24574 	return (0);
24575 }
24576 
24577 
24578 /*
24579  *    Function: sd_mhd_watch_cb()
24580  *
24581  * Description: This function is the call back function used by the scsi watch
24582  *		facility. The scsi watch facility sends the "Test Unit Ready"
24583  *		and processes the status. If applicable (i.e. a "Unit Attention"
24584  *		status and automatic "Request Sense" not used) the scsi watch
24585  *		facility will send a "Request Sense" and retrieve the sense data
24586  *		to be passed to this callback function. In either case the
24587  *		automatic "Request Sense" or the facility submitting one, this
24588  *		callback is passed the status and sense data.
24589  *
24590  *   Arguments: arg -   the device 'dev_t' is used for context to discriminate
24591  *			among multiple watches that share this callback function
24592  *		resultp - scsi watch facility result packet containing scsi
24593  *			  packet, status byte and sense data
24594  *
24595  * Return Code: 0 - continue the watch task
24596  *		non-zero - terminate the watch task
24597  */
24598 
24599 static int
24600 sd_mhd_watch_cb(caddr_t arg, struct scsi_watch_result *resultp)
24601 {
24602 	struct sd_lun			*un;
24603 	struct scsi_status		*statusp;
24604 	uint8_t				*sensep;
24605 	struct scsi_pkt			*pkt;
24606 	uchar_t				actual_sense_length;
24607 	dev_t  				dev = (dev_t)arg;
24608 
24609 	ASSERT(resultp != NULL);
24610 	statusp			= resultp->statusp;
24611 	sensep			= (uint8_t *)resultp->sensep;
24612 	pkt			= resultp->pkt;
24613 	actual_sense_length	= resultp->actual_sense_length;
24614 
24615 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
24616 		return (ENXIO);
24617 	}
24618 
24619 	SD_TRACE(SD_LOG_IOCTL_MHD, un,
24620 	    "sd_mhd_watch_cb: reason '%s', status '%s'\n",
24621 	    scsi_rname(pkt->pkt_reason), sd_sname(*((unsigned char *)statusp)));
24622 
24623 	/* Begin processing of the status and/or sense data */
24624 	if (pkt->pkt_reason != CMD_CMPLT) {
24625 		/* Handle the incomplete packet */
24626 		sd_mhd_watch_incomplete(un, pkt);
24627 		return (0);
24628 	} else if (*((unsigned char *)statusp) != STATUS_GOOD) {
24629 		if (*((unsigned char *)statusp)
24630 		    == STATUS_RESERVATION_CONFLICT) {
24631 			/*
24632 			 * Handle a reservation conflict by panicking if
24633 			 * configured for failfast or by logging the conflict
24634 			 * and updating the reservation status
24635 			 */
24636 			mutex_enter(SD_MUTEX(un));
24637 			if ((un->un_resvd_status & SD_FAILFAST) &&
24638 			    (sd_failfast_enable)) {
24639 				sd_panic_for_res_conflict(un);
24640 				/*NOTREACHED*/
24641 			}
24642 			SD_INFO(SD_LOG_IOCTL_MHD, un,
24643 			    "sd_mhd_watch_cb: Reservation Conflict\n");
24644 			un->un_resvd_status |= SD_RESERVATION_CONFLICT;
24645 			mutex_exit(SD_MUTEX(un));
24646 		}
24647 	}
24648 
24649 	if (sensep != NULL) {
24650 		if (actual_sense_length >= (SENSE_LENGTH - 2)) {
24651 			mutex_enter(SD_MUTEX(un));
24652 			if ((scsi_sense_asc(sensep) ==
24653 			    SD_SCSI_RESET_SENSE_CODE) &&
24654 			    (un->un_resvd_status & SD_RESERVE)) {
24655 				/*
24656 				 * The additional sense code indicates a power
24657 				 * on or bus device reset has occurred; update
24658 				 * the reservation status.
24659 				 */
24660 				un->un_resvd_status |=
24661 				    (SD_LOST_RESERVE | SD_WANT_RESERVE);
24662 				SD_INFO(SD_LOG_IOCTL_MHD, un,
24663 				    "sd_mhd_watch_cb: Lost Reservation\n");
24664 			}
24665 		} else {
24666 			return (0);
24667 		}
24668 	} else {
24669 		mutex_enter(SD_MUTEX(un));
24670 	}
24671 
24672 	if ((un->un_resvd_status & SD_RESERVE) &&
24673 	    (un->un_resvd_status & SD_LOST_RESERVE)) {
24674 		if (un->un_resvd_status & SD_WANT_RESERVE) {
24675 			/*
24676 			 * A reset occurred in between the last probe and this
24677 			 * one so if a timeout is pending cancel it.
24678 			 */
24679 			if (un->un_resvd_timeid) {
24680 				timeout_id_t temp_id = un->un_resvd_timeid;
24681 				un->un_resvd_timeid = NULL;
24682 				mutex_exit(SD_MUTEX(un));
24683 				(void) untimeout(temp_id);
24684 				mutex_enter(SD_MUTEX(un));
24685 			}
24686 			un->un_resvd_status &= ~SD_WANT_RESERVE;
24687 		}
24688 		if (un->un_resvd_timeid == 0) {
24689 			/* Schedule a timeout to handle the lost reservation */
24690 			un->un_resvd_timeid = timeout(sd_mhd_resvd_recover,
24691 			    (void *)dev,
24692 			    drv_usectohz(sd_reinstate_resv_delay));
24693 		}
24694 	}
24695 	mutex_exit(SD_MUTEX(un));
24696 	return (0);
24697 }
24698 
24699 
24700 /*
24701  *    Function: sd_mhd_watch_incomplete()
24702  *
24703  * Description: This function is used to find out why a scsi pkt sent by the
24704  *		scsi watch facility was not completed. Under some scenarios this
24705  *		routine will return. Otherwise it will send a bus reset to see
24706  *		if the drive is still online.
24707  *
24708  *   Arguments: un  - driver soft state (unit) structure
24709  *		pkt - incomplete scsi pkt
24710  */
24711 
24712 static void
24713 sd_mhd_watch_incomplete(struct sd_lun *un, struct scsi_pkt *pkt)
24714 {
24715 	int	be_chatty;
24716 	int	perr;
24717 
24718 	ASSERT(pkt != NULL);
24719 	ASSERT(un != NULL);
24720 	be_chatty	= (!(pkt->pkt_flags & FLAG_SILENT));
24721 	perr		= (pkt->pkt_statistics & STAT_PERR);
24722 
24723 	mutex_enter(SD_MUTEX(un));
24724 	if (un->un_state == SD_STATE_DUMPING) {
24725 		mutex_exit(SD_MUTEX(un));
24726 		return;
24727 	}
24728 
24729 	switch (pkt->pkt_reason) {
24730 	case CMD_UNX_BUS_FREE:
24731 		/*
24732 		 * If we had a parity error that caused the target to drop BSY*,
24733 		 * don't be chatty about it.
24734 		 */
24735 		if (perr && be_chatty) {
24736 			be_chatty = 0;
24737 		}
24738 		break;
24739 	case CMD_TAG_REJECT:
24740 		/*
24741 		 * The SCSI-2 spec states that a tag reject will be sent by the
24742 		 * target if tagged queuing is not supported. A tag reject may
24743 		 * also be sent during certain initialization periods or to
24744 		 * control internal resources. For the latter case the target
24745 		 * may also return Queue Full.
24746 		 *
24747 		 * If this driver receives a tag reject from a target that is
24748 		 * going through an init period or controlling internal
24749 		 * resources tagged queuing will be disabled. This is a less
24750 		 * than optimal behavior but the driver is unable to determine
24751 		 * the target state and assumes tagged queueing is not supported
24752 		 */
24753 		pkt->pkt_flags = 0;
24754 		un->un_tagflags = 0;
24755 
24756 		if (un->un_f_opt_queueing == TRUE) {
24757 			un->un_throttle = min(un->un_throttle, 3);
24758 		} else {
24759 			un->un_throttle = 1;
24760 		}
24761 		mutex_exit(SD_MUTEX(un));
24762 		(void) scsi_ifsetcap(SD_ADDRESS(un), "tagged-qing", 0, 1);
24763 		mutex_enter(SD_MUTEX(un));
24764 		break;
24765 	case CMD_INCOMPLETE:
24766 		/*
24767 		 * The transport stopped with an abnormal state, fallthrough and
24768 		 * reset the target and/or bus unless selection did not complete
24769 		 * (indicated by STATE_GOT_BUS) in which case we don't want to
24770 		 * go through a target/bus reset
24771 		 */
24772 		if (pkt->pkt_state == STATE_GOT_BUS) {
24773 			break;
24774 		}
24775 		/*FALLTHROUGH*/
24776 
24777 	case CMD_TIMEOUT:
24778 	default:
24779 		/*
24780 		 * The lun may still be running the command, so a lun reset
24781 		 * should be attempted. If the lun reset fails or cannot be
24782 		 * issued, than try a target reset. Lastly try a bus reset.
24783 		 */
24784 		if ((pkt->pkt_statistics &
24785 		    (STAT_BUS_RESET|STAT_DEV_RESET|STAT_ABORTED)) == 0) {
24786 			int reset_retval = 0;
24787 			mutex_exit(SD_MUTEX(un));
24788 			if (un->un_f_allow_bus_device_reset == TRUE) {
24789 				if (un->un_f_lun_reset_enabled == TRUE) {
24790 					reset_retval =
24791 					    scsi_reset(SD_ADDRESS(un),
24792 					    RESET_LUN);
24793 				}
24794 				if (reset_retval == 0) {
24795 					reset_retval =
24796 					    scsi_reset(SD_ADDRESS(un),
24797 					    RESET_TARGET);
24798 				}
24799 			}
24800 			if (reset_retval == 0) {
24801 				(void) scsi_reset(SD_ADDRESS(un), RESET_ALL);
24802 			}
24803 			mutex_enter(SD_MUTEX(un));
24804 		}
24805 		break;
24806 	}
24807 
24808 	/* A device/bus reset has occurred; update the reservation status. */
24809 	if ((pkt->pkt_reason == CMD_RESET) || (pkt->pkt_statistics &
24810 	    (STAT_BUS_RESET | STAT_DEV_RESET))) {
24811 		if ((un->un_resvd_status & SD_RESERVE) == SD_RESERVE) {
24812 			un->un_resvd_status |=
24813 			    (SD_LOST_RESERVE | SD_WANT_RESERVE);
24814 			SD_INFO(SD_LOG_IOCTL_MHD, un,
24815 			    "sd_mhd_watch_incomplete: Lost Reservation\n");
24816 		}
24817 	}
24818 
24819 	/*
24820 	 * The disk has been turned off; Update the device state.
24821 	 *
24822 	 * Note: Should we be offlining the disk here?
24823 	 */
24824 	if (pkt->pkt_state == STATE_GOT_BUS) {
24825 		SD_INFO(SD_LOG_IOCTL_MHD, un, "sd_mhd_watch_incomplete: "
24826 		    "Disk not responding to selection\n");
24827 		if (un->un_state != SD_STATE_OFFLINE) {
24828 			New_state(un, SD_STATE_OFFLINE);
24829 		}
24830 	} else if (be_chatty) {
24831 		/*
24832 		 * suppress messages if they are all the same pkt reason;
24833 		 * with TQ, many (up to 256) are returned with the same
24834 		 * pkt_reason
24835 		 */
24836 		if (pkt->pkt_reason != un->un_last_pkt_reason) {
24837 			SD_ERROR(SD_LOG_IOCTL_MHD, un,
24838 			    "sd_mhd_watch_incomplete: "
24839 			    "SCSI transport failed: reason '%s'\n",
24840 			    scsi_rname(pkt->pkt_reason));
24841 		}
24842 	}
24843 	un->un_last_pkt_reason = pkt->pkt_reason;
24844 	mutex_exit(SD_MUTEX(un));
24845 }
24846 
24847 
24848 /*
24849  *    Function: sd_sname()
24850  *
24851  * Description: This is a simple little routine to return a string containing
24852  *		a printable description of command status byte for use in
24853  *		logging.
24854  *
24855  *   Arguments: status - pointer to a status byte
24856  *
24857  * Return Code: char * - string containing status description.
24858  */
24859 
24860 static char *
24861 sd_sname(uchar_t status)
24862 {
24863 	switch (status & STATUS_MASK) {
24864 	case STATUS_GOOD:
24865 		return ("good status");
24866 	case STATUS_CHECK:
24867 		return ("check condition");
24868 	case STATUS_MET:
24869 		return ("condition met");
24870 	case STATUS_BUSY:
24871 		return ("busy");
24872 	case STATUS_INTERMEDIATE:
24873 		return ("intermediate");
24874 	case STATUS_INTERMEDIATE_MET:
24875 		return ("intermediate - condition met");
24876 	case STATUS_RESERVATION_CONFLICT:
24877 		return ("reservation_conflict");
24878 	case STATUS_TERMINATED:
24879 		return ("command terminated");
24880 	case STATUS_QFULL:
24881 		return ("queue full");
24882 	default:
24883 		return ("<unknown status>");
24884 	}
24885 }
24886 
24887 
24888 /*
24889  *    Function: sd_mhd_resvd_recover()
24890  *
24891  * Description: This function adds a reservation entry to the
24892  *		sd_resv_reclaim_request list and signals the reservation
24893  *		reclaim thread that there is work pending. If the reservation
24894  *		reclaim thread has not been previously created this function
24895  *		will kick it off.
24896  *
24897  *   Arguments: arg -   the device 'dev_t' is used for context to discriminate
24898  *			among multiple watches that share this callback function
24899  *
24900  *     Context: This routine is called by timeout() and is run in interrupt
24901  *		context. It must not sleep or call other functions which may
24902  *		sleep.
24903  */
24904 
24905 static void
24906 sd_mhd_resvd_recover(void *arg)
24907 {
24908 	dev_t			dev = (dev_t)arg;
24909 	struct sd_lun		*un;
24910 	struct sd_thr_request	*sd_treq = NULL;
24911 	struct sd_thr_request	*sd_cur = NULL;
24912 	struct sd_thr_request	*sd_prev = NULL;
24913 	int			already_there = 0;
24914 
24915 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
24916 		return;
24917 	}
24918 
24919 	mutex_enter(SD_MUTEX(un));
24920 	un->un_resvd_timeid = NULL;
24921 	if (un->un_resvd_status & SD_WANT_RESERVE) {
24922 		/*
24923 		 * There was a reset so don't issue the reserve, allow the
24924 		 * sd_mhd_watch_cb callback function to notice this and
24925 		 * reschedule the timeout for reservation.
24926 		 */
24927 		mutex_exit(SD_MUTEX(un));
24928 		return;
24929 	}
24930 	mutex_exit(SD_MUTEX(un));
24931 
24932 	/*
24933 	 * Add this device to the sd_resv_reclaim_request list and the
24934 	 * sd_resv_reclaim_thread should take care of the rest.
24935 	 *
24936 	 * Note: We can't sleep in this context so if the memory allocation
24937 	 * fails allow the sd_mhd_watch_cb callback function to notice this and
24938 	 * reschedule the timeout for reservation.  (4378460)
24939 	 */
24940 	sd_treq = (struct sd_thr_request *)
24941 	    kmem_zalloc(sizeof (struct sd_thr_request), KM_NOSLEEP);
24942 	if (sd_treq == NULL) {
24943 		return;
24944 	}
24945 
24946 	sd_treq->sd_thr_req_next = NULL;
24947 	sd_treq->dev = dev;
24948 	mutex_enter(&sd_tr.srq_resv_reclaim_mutex);
24949 	if (sd_tr.srq_thr_req_head == NULL) {
24950 		sd_tr.srq_thr_req_head = sd_treq;
24951 	} else {
24952 		sd_cur = sd_prev = sd_tr.srq_thr_req_head;
24953 		for (; sd_cur != NULL; sd_cur = sd_cur->sd_thr_req_next) {
24954 			if (sd_cur->dev == dev) {
24955 				/*
24956 				 * already in Queue so don't log
24957 				 * another request for the device
24958 				 */
24959 				already_there = 1;
24960 				break;
24961 			}
24962 			sd_prev = sd_cur;
24963 		}
24964 		if (!already_there) {
24965 			SD_INFO(SD_LOG_IOCTL_MHD, un, "sd_mhd_resvd_recover: "
24966 			    "logging request for %lx\n", dev);
24967 			sd_prev->sd_thr_req_next = sd_treq;
24968 		} else {
24969 			kmem_free(sd_treq, sizeof (struct sd_thr_request));
24970 		}
24971 	}
24972 
24973 	/*
24974 	 * Create a kernel thread to do the reservation reclaim and free up this
24975 	 * thread. We cannot block this thread while we go away to do the
24976 	 * reservation reclaim
24977 	 */
24978 	if (sd_tr.srq_resv_reclaim_thread == NULL)
24979 		sd_tr.srq_resv_reclaim_thread = thread_create(NULL, 0,
24980 		    sd_resv_reclaim_thread, NULL,
24981 		    0, &p0, TS_RUN, v.v_maxsyspri - 2);
24982 
24983 	/* Tell the reservation reclaim thread that it has work to do */
24984 	cv_signal(&sd_tr.srq_resv_reclaim_cv);
24985 	mutex_exit(&sd_tr.srq_resv_reclaim_mutex);
24986 }
24987 
24988 /*
24989  *    Function: sd_resv_reclaim_thread()
24990  *
24991  * Description: This function implements the reservation reclaim operations
24992  *
24993  *   Arguments: arg - the device 'dev_t' is used for context to discriminate
24994  *		      among multiple watches that share this callback function
24995  */
24996 
24997 static void
24998 sd_resv_reclaim_thread()
24999 {
25000 	struct sd_lun		*un;
25001 	struct sd_thr_request	*sd_mhreq;
25002 
25003 	/* Wait for work */
25004 	mutex_enter(&sd_tr.srq_resv_reclaim_mutex);
25005 	if (sd_tr.srq_thr_req_head == NULL) {
25006 		cv_wait(&sd_tr.srq_resv_reclaim_cv,
25007 		    &sd_tr.srq_resv_reclaim_mutex);
25008 	}
25009 
25010 	/* Loop while we have work */
25011 	while ((sd_tr.srq_thr_cur_req = sd_tr.srq_thr_req_head) != NULL) {
25012 		un = ddi_get_soft_state(sd_state,
25013 		    SDUNIT(sd_tr.srq_thr_cur_req->dev));
25014 		if (un == NULL) {
25015 			/*
25016 			 * softstate structure is NULL so just
25017 			 * dequeue the request and continue
25018 			 */
25019 			sd_tr.srq_thr_req_head =
25020 			    sd_tr.srq_thr_cur_req->sd_thr_req_next;
25021 			kmem_free(sd_tr.srq_thr_cur_req,
25022 			    sizeof (struct sd_thr_request));
25023 			continue;
25024 		}
25025 
25026 		/* dequeue the request */
25027 		sd_mhreq = sd_tr.srq_thr_cur_req;
25028 		sd_tr.srq_thr_req_head =
25029 		    sd_tr.srq_thr_cur_req->sd_thr_req_next;
25030 		mutex_exit(&sd_tr.srq_resv_reclaim_mutex);
25031 
25032 		/*
25033 		 * Reclaim reservation only if SD_RESERVE is still set. There
25034 		 * may have been a call to MHIOCRELEASE before we got here.
25035 		 */
25036 		mutex_enter(SD_MUTEX(un));
25037 		if ((un->un_resvd_status & SD_RESERVE) == SD_RESERVE) {
25038 			/*
25039 			 * Note: The SD_LOST_RESERVE flag is cleared before
25040 			 * reclaiming the reservation. If this is done after the
25041 			 * call to sd_reserve_release a reservation loss in the
25042 			 * window between pkt completion of reserve cmd and
25043 			 * mutex_enter below may not be recognized
25044 			 */
25045 			un->un_resvd_status &= ~SD_LOST_RESERVE;
25046 			mutex_exit(SD_MUTEX(un));
25047 
25048 			if (sd_reserve_release(sd_mhreq->dev,
25049 			    SD_RESERVE) == 0) {
25050 				mutex_enter(SD_MUTEX(un));
25051 				un->un_resvd_status |= SD_RESERVE;
25052 				mutex_exit(SD_MUTEX(un));
25053 				SD_INFO(SD_LOG_IOCTL_MHD, un,
25054 				    "sd_resv_reclaim_thread: "
25055 				    "Reservation Recovered\n");
25056 			} else {
25057 				mutex_enter(SD_MUTEX(un));
25058 				un->un_resvd_status |= SD_LOST_RESERVE;
25059 				mutex_exit(SD_MUTEX(un));
25060 				SD_INFO(SD_LOG_IOCTL_MHD, un,
25061 				    "sd_resv_reclaim_thread: Failed "
25062 				    "Reservation Recovery\n");
25063 			}
25064 		} else {
25065 			mutex_exit(SD_MUTEX(un));
25066 		}
25067 		mutex_enter(&sd_tr.srq_resv_reclaim_mutex);
25068 		ASSERT(sd_mhreq == sd_tr.srq_thr_cur_req);
25069 		kmem_free(sd_mhreq, sizeof (struct sd_thr_request));
25070 		sd_mhreq = sd_tr.srq_thr_cur_req = NULL;
25071 		/*
25072 		 * wakeup the destroy thread if anyone is waiting on
25073 		 * us to complete.
25074 		 */
25075 		cv_signal(&sd_tr.srq_inprocess_cv);
25076 		SD_TRACE(SD_LOG_IOCTL_MHD, un,
25077 		    "sd_resv_reclaim_thread: cv_signalling current request \n");
25078 	}
25079 
25080 	/*
25081 	 * cleanup the sd_tr structure now that this thread will not exist
25082 	 */
25083 	ASSERT(sd_tr.srq_thr_req_head == NULL);
25084 	ASSERT(sd_tr.srq_thr_cur_req == NULL);
25085 	sd_tr.srq_resv_reclaim_thread = NULL;
25086 	mutex_exit(&sd_tr.srq_resv_reclaim_mutex);
25087 	thread_exit();
25088 }
25089 
25090 
25091 /*
25092  *    Function: sd_rmv_resv_reclaim_req()
25093  *
25094  * Description: This function removes any pending reservation reclaim requests
25095  *		for the specified device.
25096  *
25097  *   Arguments: dev - the device 'dev_t'
25098  */
25099 
25100 static void
25101 sd_rmv_resv_reclaim_req(dev_t dev)
25102 {
25103 	struct sd_thr_request *sd_mhreq;
25104 	struct sd_thr_request *sd_prev;
25105 
25106 	/* Remove a reservation reclaim request from the list */
25107 	mutex_enter(&sd_tr.srq_resv_reclaim_mutex);
25108 	if (sd_tr.srq_thr_cur_req && sd_tr.srq_thr_cur_req->dev == dev) {
25109 		/*
25110 		 * We are attempting to reinstate reservation for
25111 		 * this device. We wait for sd_reserve_release()
25112 		 * to return before we return.
25113 		 */
25114 		cv_wait(&sd_tr.srq_inprocess_cv,
25115 		    &sd_tr.srq_resv_reclaim_mutex);
25116 	} else {
25117 		sd_prev = sd_mhreq = sd_tr.srq_thr_req_head;
25118 		if (sd_mhreq && sd_mhreq->dev == dev) {
25119 			sd_tr.srq_thr_req_head = sd_mhreq->sd_thr_req_next;
25120 			kmem_free(sd_mhreq, sizeof (struct sd_thr_request));
25121 			mutex_exit(&sd_tr.srq_resv_reclaim_mutex);
25122 			return;
25123 		}
25124 		for (; sd_mhreq != NULL; sd_mhreq = sd_mhreq->sd_thr_req_next) {
25125 			if (sd_mhreq && sd_mhreq->dev == dev) {
25126 				break;
25127 			}
25128 			sd_prev = sd_mhreq;
25129 		}
25130 		if (sd_mhreq != NULL) {
25131 			sd_prev->sd_thr_req_next = sd_mhreq->sd_thr_req_next;
25132 			kmem_free(sd_mhreq, sizeof (struct sd_thr_request));
25133 		}
25134 	}
25135 	mutex_exit(&sd_tr.srq_resv_reclaim_mutex);
25136 }
25137 
25138 
25139 /*
25140  *    Function: sd_mhd_reset_notify_cb()
25141  *
25142  * Description: This is a call back function for scsi_reset_notify. This
25143  *		function updates the softstate reserved status and logs the
25144  *		reset. The driver scsi watch facility callback function
25145  *		(sd_mhd_watch_cb) and reservation reclaim thread functionality
25146  *		will reclaim the reservation.
25147  *
25148  *   Arguments: arg  - driver soft state (unit) structure
25149  */
25150 
25151 static void
25152 sd_mhd_reset_notify_cb(caddr_t arg)
25153 {
25154 	struct sd_lun *un = (struct sd_lun *)arg;
25155 
25156 	mutex_enter(SD_MUTEX(un));
25157 	if ((un->un_resvd_status & SD_RESERVE) == SD_RESERVE) {
25158 		un->un_resvd_status |= (SD_LOST_RESERVE | SD_WANT_RESERVE);
25159 		SD_INFO(SD_LOG_IOCTL_MHD, un,
25160 		    "sd_mhd_reset_notify_cb: Lost Reservation\n");
25161 	}
25162 	mutex_exit(SD_MUTEX(un));
25163 }
25164 
25165 
25166 /*
25167  *    Function: sd_take_ownership()
25168  *
25169  * Description: This routine implements an algorithm to achieve a stable
25170  *		reservation on disks which don't implement priority reserve,
25171  *		and makes sure that other host lose re-reservation attempts.
25172  *		This algorithm contains of a loop that keeps issuing the RESERVE
25173  *		for some period of time (min_ownership_delay, default 6 seconds)
25174  *		During that loop, it looks to see if there has been a bus device
25175  *		reset or bus reset (both of which cause an existing reservation
25176  *		to be lost). If the reservation is lost issue RESERVE until a
25177  *		period of min_ownership_delay with no resets has gone by, or
25178  *		until max_ownership_delay has expired. This loop ensures that
25179  *		the host really did manage to reserve the device, in spite of
25180  *		resets. The looping for min_ownership_delay (default six
25181  *		seconds) is important to early generation clustering products,
25182  *		Solstice HA 1.x and Sun Cluster 2.x. Those products use an
25183  *		MHIOCENFAILFAST periodic timer of two seconds. By having
25184  *		MHIOCTKOWN issue Reserves in a loop for six seconds, and having
25185  *		MHIOCENFAILFAST poll every two seconds, the idea is that by the
25186  *		time the MHIOCTKOWN ioctl returns, the other host (if any) will
25187  *		have already noticed, via the MHIOCENFAILFAST polling, that it
25188  *		no longer "owns" the disk and will have panicked itself.  Thus,
25189  *		the host issuing the MHIOCTKOWN is assured (with timing
25190  *		dependencies) that by the time it actually starts to use the
25191  *		disk for real work, the old owner is no longer accessing it.
25192  *
25193  *		min_ownership_delay is the minimum amount of time for which the
25194  *		disk must be reserved continuously devoid of resets before the
25195  *		MHIOCTKOWN ioctl will return success.
25196  *
25197  *		max_ownership_delay indicates the amount of time by which the
25198  *		take ownership should succeed or timeout with an error.
25199  *
25200  *   Arguments: dev - the device 'dev_t'
25201  *		*p  - struct containing timing info.
25202  *
25203  * Return Code: 0 for success or error code
25204  */
25205 
25206 static int
25207 sd_take_ownership(dev_t dev, struct mhioctkown *p)
25208 {
25209 	struct sd_lun	*un;
25210 	int		rval;
25211 	int		err;
25212 	int		reservation_count   = 0;
25213 	int		min_ownership_delay =  6000000; /* in usec */
25214 	int		max_ownership_delay = 30000000; /* in usec */
25215 	clock_t		start_time;	/* starting time of this algorithm */
25216 	clock_t		end_time;	/* time limit for giving up */
25217 	clock_t		ownership_time;	/* time limit for stable ownership */
25218 	clock_t		current_time;
25219 	clock_t		previous_current_time;
25220 
25221 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
25222 		return (ENXIO);
25223 	}
25224 
25225 	/*
25226 	 * Attempt a device reservation. A priority reservation is requested.
25227 	 */
25228 	if ((rval = sd_reserve_release(dev, SD_PRIORITY_RESERVE))
25229 	    != SD_SUCCESS) {
25230 		SD_ERROR(SD_LOG_IOCTL_MHD, un,
25231 		    "sd_take_ownership: return(1)=%d\n", rval);
25232 		return (rval);
25233 	}
25234 
25235 	/* Update the softstate reserved status to indicate the reservation */
25236 	mutex_enter(SD_MUTEX(un));
25237 	un->un_resvd_status |= SD_RESERVE;
25238 	un->un_resvd_status &=
25239 	    ~(SD_LOST_RESERVE | SD_WANT_RESERVE | SD_RESERVATION_CONFLICT);
25240 	mutex_exit(SD_MUTEX(un));
25241 
25242 	if (p != NULL) {
25243 		if (p->min_ownership_delay != 0) {
25244 			min_ownership_delay = p->min_ownership_delay * 1000;
25245 		}
25246 		if (p->max_ownership_delay != 0) {
25247 			max_ownership_delay = p->max_ownership_delay * 1000;
25248 		}
25249 	}
25250 	SD_INFO(SD_LOG_IOCTL_MHD, un,
25251 	    "sd_take_ownership: min, max delays: %d, %d\n",
25252 	    min_ownership_delay, max_ownership_delay);
25253 
25254 	start_time = ddi_get_lbolt();
25255 	current_time	= start_time;
25256 	ownership_time	= current_time + drv_usectohz(min_ownership_delay);
25257 	end_time	= start_time + drv_usectohz(max_ownership_delay);
25258 
25259 	while (current_time - end_time < 0) {
25260 		delay(drv_usectohz(500000));
25261 
25262 		if ((err = sd_reserve_release(dev, SD_RESERVE)) != 0) {
25263 			if ((sd_reserve_release(dev, SD_RESERVE)) != 0) {
25264 				mutex_enter(SD_MUTEX(un));
25265 				rval = (un->un_resvd_status &
25266 				    SD_RESERVATION_CONFLICT) ? EACCES : EIO;
25267 				mutex_exit(SD_MUTEX(un));
25268 				break;
25269 			}
25270 		}
25271 		previous_current_time = current_time;
25272 		current_time = ddi_get_lbolt();
25273 		mutex_enter(SD_MUTEX(un));
25274 		if (err || (un->un_resvd_status & SD_LOST_RESERVE)) {
25275 			ownership_time = ddi_get_lbolt() +
25276 			    drv_usectohz(min_ownership_delay);
25277 			reservation_count = 0;
25278 		} else {
25279 			reservation_count++;
25280 		}
25281 		un->un_resvd_status |= SD_RESERVE;
25282 		un->un_resvd_status &= ~(SD_LOST_RESERVE | SD_WANT_RESERVE);
25283 		mutex_exit(SD_MUTEX(un));
25284 
25285 		SD_INFO(SD_LOG_IOCTL_MHD, un,
25286 		    "sd_take_ownership: ticks for loop iteration=%ld, "
25287 		    "reservation=%s\n", (current_time - previous_current_time),
25288 		    reservation_count ? "ok" : "reclaimed");
25289 
25290 		if (current_time - ownership_time >= 0 &&
25291 		    reservation_count >= 4) {
25292 			rval = 0; /* Achieved a stable ownership */
25293 			break;
25294 		}
25295 		if (current_time - end_time >= 0) {
25296 			rval = EACCES; /* No ownership in max possible time */
25297 			break;
25298 		}
25299 	}
25300 	SD_TRACE(SD_LOG_IOCTL_MHD, un,
25301 	    "sd_take_ownership: return(2)=%d\n", rval);
25302 	return (rval);
25303 }
25304 
25305 
25306 /*
25307  *    Function: sd_reserve_release()
25308  *
25309  * Description: This function builds and sends scsi RESERVE, RELEASE, and
25310  *		PRIORITY RESERVE commands based on a user specified command type
25311  *
25312  *   Arguments: dev - the device 'dev_t'
25313  *		cmd - user specified command type; one of SD_PRIORITY_RESERVE,
25314  *		      SD_RESERVE, SD_RELEASE
25315  *
25316  * Return Code: 0 or Error Code
25317  */
25318 
25319 static int
25320 sd_reserve_release(dev_t dev, int cmd)
25321 {
25322 	struct uscsi_cmd	*com = NULL;
25323 	struct sd_lun		*un = NULL;
25324 	char			cdb[CDB_GROUP0];
25325 	int			rval;
25326 
25327 	ASSERT((cmd == SD_RELEASE) || (cmd == SD_RESERVE) ||
25328 	    (cmd == SD_PRIORITY_RESERVE));
25329 
25330 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
25331 		return (ENXIO);
25332 	}
25333 
25334 	/* instantiate and initialize the command and cdb */
25335 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
25336 	bzero(cdb, CDB_GROUP0);
25337 	com->uscsi_flags   = USCSI_SILENT;
25338 	com->uscsi_timeout = un->un_reserve_release_time;
25339 	com->uscsi_cdblen  = CDB_GROUP0;
25340 	com->uscsi_cdb	   = cdb;
25341 	if (cmd == SD_RELEASE) {
25342 		cdb[0] = SCMD_RELEASE;
25343 	} else {
25344 		cdb[0] = SCMD_RESERVE;
25345 	}
25346 
25347 	/* Send the command. */
25348 	rval = sd_send_scsi_cmd(dev, com, FKIOCTL, UIO_SYSSPACE,
25349 	    SD_PATH_STANDARD);
25350 
25351 	/*
25352 	 * "break" a reservation that is held by another host, by issuing a
25353 	 * reset if priority reserve is desired, and we could not get the
25354 	 * device.
25355 	 */
25356 	if ((cmd == SD_PRIORITY_RESERVE) &&
25357 	    (rval != 0) && (com->uscsi_status == STATUS_RESERVATION_CONFLICT)) {
25358 		/*
25359 		 * First try to reset the LUN. If we cannot, then try a target
25360 		 * reset, followed by a bus reset if the target reset fails.
25361 		 */
25362 		int reset_retval = 0;
25363 		if (un->un_f_lun_reset_enabled == TRUE) {
25364 			reset_retval = scsi_reset(SD_ADDRESS(un), RESET_LUN);
25365 		}
25366 		if (reset_retval == 0) {
25367 			/* The LUN reset either failed or was not issued */
25368 			reset_retval = scsi_reset(SD_ADDRESS(un), RESET_TARGET);
25369 		}
25370 		if ((reset_retval == 0) &&
25371 		    (scsi_reset(SD_ADDRESS(un), RESET_ALL) == 0)) {
25372 			rval = EIO;
25373 			kmem_free(com, sizeof (*com));
25374 			return (rval);
25375 		}
25376 
25377 		bzero(com, sizeof (struct uscsi_cmd));
25378 		com->uscsi_flags   = USCSI_SILENT;
25379 		com->uscsi_cdb	   = cdb;
25380 		com->uscsi_cdblen  = CDB_GROUP0;
25381 		com->uscsi_timeout = 5;
25382 
25383 		/*
25384 		 * Reissue the last reserve command, this time without request
25385 		 * sense.  Assume that it is just a regular reserve command.
25386 		 */
25387 		rval = sd_send_scsi_cmd(dev, com, FKIOCTL, UIO_SYSSPACE,
25388 		    SD_PATH_STANDARD);
25389 	}
25390 
25391 	/* Return an error if still getting a reservation conflict. */
25392 	if ((rval != 0) && (com->uscsi_status == STATUS_RESERVATION_CONFLICT)) {
25393 		rval = EACCES;
25394 	}
25395 
25396 	kmem_free(com, sizeof (*com));
25397 	return (rval);
25398 }
25399 
25400 
25401 #define	SD_NDUMP_RETRIES	12
25402 /*
25403  *	System Crash Dump routine
25404  */
25405 
25406 static int
25407 sddump(dev_t dev, caddr_t addr, daddr_t blkno, int nblk)
25408 {
25409 	int		instance;
25410 	int		partition;
25411 	int		i;
25412 	int		err;
25413 	struct sd_lun	*un;
25414 	struct scsi_pkt *wr_pktp;
25415 	struct buf	*wr_bp;
25416 	struct buf	wr_buf;
25417 	daddr_t		tgt_byte_offset; /* rmw - byte offset for target */
25418 	daddr_t		tgt_blkno;	/* rmw - blkno for target */
25419 	size_t		tgt_byte_count; /* rmw -  # of bytes to xfer */
25420 	size_t		tgt_nblk; /* rmw -  # of tgt blks to xfer */
25421 	size_t		io_start_offset;
25422 	int		doing_rmw = FALSE;
25423 	int		rval;
25424 	ssize_t		dma_resid;
25425 	daddr_t		oblkno;
25426 	diskaddr_t	nblks = 0;
25427 	diskaddr_t	start_block;
25428 
25429 	instance = SDUNIT(dev);
25430 	if (((un = ddi_get_soft_state(sd_state, instance)) == NULL) ||
25431 	    !SD_IS_VALID_LABEL(un) || ISCD(un)) {
25432 		return (ENXIO);
25433 	}
25434 
25435 	_NOTE(NOW_INVISIBLE_TO_OTHER_THREADS(*un))
25436 
25437 	SD_TRACE(SD_LOG_DUMP, un, "sddump: entry\n");
25438 
25439 	partition = SDPART(dev);
25440 	SD_INFO(SD_LOG_DUMP, un, "sddump: partition = %d\n", partition);
25441 
25442 	if (!(NOT_DEVBSIZE(un))) {
25443 		int secmask = 0;
25444 		int blknomask = 0;
25445 
25446 		blknomask = (un->un_tgt_blocksize / DEV_BSIZE) - 1;
25447 		secmask = un->un_tgt_blocksize - 1;
25448 
25449 		if (blkno & blknomask) {
25450 			SD_TRACE(SD_LOG_DUMP, un,
25451 			    "sddump: dump start block not modulo %d\n",
25452 			    un->un_tgt_blocksize);
25453 			return (EINVAL);
25454 		}
25455 
25456 		if ((nblk * DEV_BSIZE) & secmask) {
25457 			SD_TRACE(SD_LOG_DUMP, un,
25458 			    "sddump: dump length not modulo %d\n",
25459 			    un->un_tgt_blocksize);
25460 			return (EINVAL);
25461 		}
25462 
25463 	}
25464 
25465 	/* Validate blocks to dump at against partition size. */
25466 
25467 	(void) cmlb_partinfo(un->un_cmlbhandle, partition,
25468 	    &nblks, &start_block, NULL, NULL, (void *)SD_PATH_DIRECT);
25469 
25470 	if (NOT_DEVBSIZE(un)) {
25471 		if ((blkno + nblk) > nblks) {
25472 			SD_TRACE(SD_LOG_DUMP, un,
25473 			    "sddump: dump range larger than partition: "
25474 			    "blkno = 0x%x, nblk = 0x%x, dkl_nblk = 0x%x\n",
25475 			    blkno, nblk, nblks);
25476 			return (EINVAL);
25477 		}
25478 	} else {
25479 		if (((blkno / (un->un_tgt_blocksize / DEV_BSIZE)) +
25480 		    (nblk / (un->un_tgt_blocksize / DEV_BSIZE))) > nblks) {
25481 			SD_TRACE(SD_LOG_DUMP, un,
25482 			    "sddump: dump range larger than partition: "
25483 			    "blkno = 0x%x, nblk = 0x%x, dkl_nblk = 0x%x\n",
25484 			    blkno, nblk, nblks);
25485 			return (EINVAL);
25486 		}
25487 	}
25488 
25489 	mutex_enter(&un->un_pm_mutex);
25490 	if (SD_DEVICE_IS_IN_LOW_POWER(un)) {
25491 		struct scsi_pkt *start_pktp;
25492 
25493 		mutex_exit(&un->un_pm_mutex);
25494 
25495 		/*
25496 		 * use pm framework to power on HBA 1st
25497 		 */
25498 		(void) pm_raise_power(SD_DEVINFO(un), 0,
25499 		    SD_PM_STATE_ACTIVE(un));
25500 
25501 		/*
25502 		 * Dump no long uses sdpower to power on a device, it's
25503 		 * in-line here so it can be done in polled mode.
25504 		 */
25505 
25506 		SD_INFO(SD_LOG_DUMP, un, "sddump: starting device\n");
25507 
25508 		start_pktp = scsi_init_pkt(SD_ADDRESS(un), NULL, NULL,
25509 		    CDB_GROUP0, un->un_status_len, 0, 0, NULL_FUNC, NULL);
25510 
25511 		if (start_pktp == NULL) {
25512 			/* We were not given a SCSI packet, fail. */
25513 			return (EIO);
25514 		}
25515 		bzero(start_pktp->pkt_cdbp, CDB_GROUP0);
25516 		start_pktp->pkt_cdbp[0] = SCMD_START_STOP;
25517 		start_pktp->pkt_cdbp[4] = SD_TARGET_START;
25518 		start_pktp->pkt_flags = FLAG_NOINTR;
25519 
25520 		mutex_enter(SD_MUTEX(un));
25521 		SD_FILL_SCSI1_LUN(un, start_pktp);
25522 		mutex_exit(SD_MUTEX(un));
25523 		/*
25524 		 * Scsi_poll returns 0 (success) if the command completes and
25525 		 * the status block is STATUS_GOOD.
25526 		 */
25527 		if (sd_scsi_poll(un, start_pktp) != 0) {
25528 			scsi_destroy_pkt(start_pktp);
25529 			return (EIO);
25530 		}
25531 		scsi_destroy_pkt(start_pktp);
25532 		(void) sd_pm_state_change(un, SD_PM_STATE_ACTIVE(un),
25533 		    SD_PM_STATE_CHANGE);
25534 	} else {
25535 		mutex_exit(&un->un_pm_mutex);
25536 	}
25537 
25538 	mutex_enter(SD_MUTEX(un));
25539 	un->un_throttle = 0;
25540 
25541 	/*
25542 	 * The first time through, reset the specific target device.
25543 	 * However, when cpr calls sddump we know that sd is in a
25544 	 * a good state so no bus reset is required.
25545 	 * Clear sense data via Request Sense cmd.
25546 	 * In sddump we don't care about allow_bus_device_reset anymore
25547 	 */
25548 
25549 	if ((un->un_state != SD_STATE_SUSPENDED) &&
25550 	    (un->un_state != SD_STATE_DUMPING)) {
25551 
25552 		New_state(un, SD_STATE_DUMPING);
25553 
25554 		if (un->un_f_is_fibre == FALSE) {
25555 			mutex_exit(SD_MUTEX(un));
25556 			/*
25557 			 * Attempt a bus reset for parallel scsi.
25558 			 *
25559 			 * Note: A bus reset is required because on some host
25560 			 * systems (i.e. E420R) a bus device reset is
25561 			 * insufficient to reset the state of the target.
25562 			 *
25563 			 * Note: Don't issue the reset for fibre-channel,
25564 			 * because this tends to hang the bus (loop) for
25565 			 * too long while everyone is logging out and in
25566 			 * and the deadman timer for dumping will fire
25567 			 * before the dump is complete.
25568 			 */
25569 			if (scsi_reset(SD_ADDRESS(un), RESET_ALL) == 0) {
25570 				mutex_enter(SD_MUTEX(un));
25571 				Restore_state(un);
25572 				mutex_exit(SD_MUTEX(un));
25573 				return (EIO);
25574 			}
25575 
25576 			/* Delay to give the device some recovery time. */
25577 			drv_usecwait(10000);
25578 
25579 			if (sd_send_polled_RQS(un) == SD_FAILURE) {
25580 				SD_INFO(SD_LOG_DUMP, un,
25581 				    "sddump: sd_send_polled_RQS failed\n");
25582 			}
25583 			mutex_enter(SD_MUTEX(un));
25584 		}
25585 	}
25586 
25587 	/*
25588 	 * Convert the partition-relative block number to a
25589 	 * disk physical block number.
25590 	 */
25591 	if (NOT_DEVBSIZE(un)) {
25592 		blkno += start_block;
25593 	} else {
25594 		blkno = blkno / (un->un_tgt_blocksize / DEV_BSIZE);
25595 		blkno += start_block;
25596 	}
25597 
25598 	SD_INFO(SD_LOG_DUMP, un, "sddump: disk blkno = 0x%x\n", blkno);
25599 
25600 
25601 	/*
25602 	 * Check if the device has a non-512 block size.
25603 	 */
25604 	wr_bp = NULL;
25605 	if (NOT_DEVBSIZE(un)) {
25606 		tgt_byte_offset = blkno * un->un_sys_blocksize;
25607 		tgt_byte_count = nblk * un->un_sys_blocksize;
25608 		if ((tgt_byte_offset % un->un_tgt_blocksize) ||
25609 		    (tgt_byte_count % un->un_tgt_blocksize)) {
25610 			doing_rmw = TRUE;
25611 			/*
25612 			 * Calculate the block number and number of block
25613 			 * in terms of the media block size.
25614 			 */
25615 			tgt_blkno = tgt_byte_offset / un->un_tgt_blocksize;
25616 			tgt_nblk =
25617 			    ((tgt_byte_offset + tgt_byte_count +
25618 			    (un->un_tgt_blocksize - 1)) /
25619 			    un->un_tgt_blocksize) - tgt_blkno;
25620 
25621 			/*
25622 			 * Invoke the routine which is going to do read part
25623 			 * of read-modify-write.
25624 			 * Note that this routine returns a pointer to
25625 			 * a valid bp in wr_bp.
25626 			 */
25627 			err = sddump_do_read_of_rmw(un, tgt_blkno, tgt_nblk,
25628 			    &wr_bp);
25629 			if (err) {
25630 				mutex_exit(SD_MUTEX(un));
25631 				return (err);
25632 			}
25633 			/*
25634 			 * Offset is being calculated as -
25635 			 * (original block # * system block size) -
25636 			 * (new block # * target block size)
25637 			 */
25638 			io_start_offset =
25639 			    ((uint64_t)(blkno * un->un_sys_blocksize)) -
25640 			    ((uint64_t)(tgt_blkno * un->un_tgt_blocksize));
25641 
25642 			ASSERT((io_start_offset >= 0) &&
25643 			    (io_start_offset < un->un_tgt_blocksize));
25644 			/*
25645 			 * Do the modify portion of read modify write.
25646 			 */
25647 			bcopy(addr, &wr_bp->b_un.b_addr[io_start_offset],
25648 			    (size_t)nblk * un->un_sys_blocksize);
25649 		} else {
25650 			doing_rmw = FALSE;
25651 			tgt_blkno = tgt_byte_offset / un->un_tgt_blocksize;
25652 			tgt_nblk = tgt_byte_count / un->un_tgt_blocksize;
25653 		}
25654 
25655 		/* Convert blkno and nblk to target blocks */
25656 		blkno = tgt_blkno;
25657 		nblk = tgt_nblk;
25658 	} else {
25659 		wr_bp = &wr_buf;
25660 		bzero(wr_bp, sizeof (struct buf));
25661 		wr_bp->b_flags		= B_BUSY;
25662 		wr_bp->b_un.b_addr	= addr;
25663 		wr_bp->b_bcount		= nblk << DEV_BSHIFT;
25664 		wr_bp->b_resid		= 0;
25665 	}
25666 
25667 	mutex_exit(SD_MUTEX(un));
25668 
25669 	/*
25670 	 * Obtain a SCSI packet for the write command.
25671 	 * It should be safe to call the allocator here without
25672 	 * worrying about being locked for DVMA mapping because
25673 	 * the address we're passed is already a DVMA mapping
25674 	 *
25675 	 * We are also not going to worry about semaphore ownership
25676 	 * in the dump buffer. Dumping is single threaded at present.
25677 	 */
25678 
25679 	wr_pktp = NULL;
25680 
25681 	dma_resid = wr_bp->b_bcount;
25682 	oblkno = blkno;
25683 
25684 	if (!(NOT_DEVBSIZE(un))) {
25685 		nblk = nblk / (un->un_tgt_blocksize / DEV_BSIZE);
25686 	}
25687 
25688 	while (dma_resid != 0) {
25689 
25690 	for (i = 0; i < SD_NDUMP_RETRIES; i++) {
25691 		wr_bp->b_flags &= ~B_ERROR;
25692 
25693 		if (un->un_partial_dma_supported == 1) {
25694 			blkno = oblkno +
25695 			    ((wr_bp->b_bcount - dma_resid) /
25696 			    un->un_tgt_blocksize);
25697 			nblk = dma_resid / un->un_tgt_blocksize;
25698 
25699 			if (wr_pktp) {
25700 				/*
25701 				 * Partial DMA transfers after initial transfer
25702 				 */
25703 				rval = sd_setup_next_rw_pkt(un, wr_pktp, wr_bp,
25704 				    blkno, nblk);
25705 			} else {
25706 				/* Initial transfer */
25707 				rval = sd_setup_rw_pkt(un, &wr_pktp, wr_bp,
25708 				    un->un_pkt_flags, NULL_FUNC, NULL,
25709 				    blkno, nblk);
25710 			}
25711 		} else {
25712 			rval = sd_setup_rw_pkt(un, &wr_pktp, wr_bp,
25713 			    0, NULL_FUNC, NULL, blkno, nblk);
25714 		}
25715 
25716 		if (rval == 0) {
25717 			/* We were given a SCSI packet, continue. */
25718 			break;
25719 		}
25720 
25721 		if (i == 0) {
25722 			if (wr_bp->b_flags & B_ERROR) {
25723 				scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
25724 				    "no resources for dumping; "
25725 				    "error code: 0x%x, retrying",
25726 				    geterror(wr_bp));
25727 			} else {
25728 				scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
25729 				    "no resources for dumping; retrying");
25730 			}
25731 		} else if (i != (SD_NDUMP_RETRIES - 1)) {
25732 			if (wr_bp->b_flags & B_ERROR) {
25733 				scsi_log(SD_DEVINFO(un), sd_label, CE_CONT,
25734 				    "no resources for dumping; error code: "
25735 				    "0x%x, retrying\n", geterror(wr_bp));
25736 			}
25737 		} else {
25738 			if (wr_bp->b_flags & B_ERROR) {
25739 				scsi_log(SD_DEVINFO(un), sd_label, CE_CONT,
25740 				    "no resources for dumping; "
25741 				    "error code: 0x%x, retries failed, "
25742 				    "giving up.\n", geterror(wr_bp));
25743 			} else {
25744 				scsi_log(SD_DEVINFO(un), sd_label, CE_CONT,
25745 				    "no resources for dumping; "
25746 				    "retries failed, giving up.\n");
25747 			}
25748 			mutex_enter(SD_MUTEX(un));
25749 			Restore_state(un);
25750 			if (NOT_DEVBSIZE(un) && (doing_rmw == TRUE)) {
25751 				mutex_exit(SD_MUTEX(un));
25752 				scsi_free_consistent_buf(wr_bp);
25753 			} else {
25754 				mutex_exit(SD_MUTEX(un));
25755 			}
25756 			return (EIO);
25757 		}
25758 		drv_usecwait(10000);
25759 	}
25760 
25761 	if (un->un_partial_dma_supported == 1) {
25762 		/*
25763 		 * save the resid from PARTIAL_DMA
25764 		 */
25765 		dma_resid = wr_pktp->pkt_resid;
25766 		if (dma_resid != 0)
25767 			nblk -= SD_BYTES2TGTBLOCKS(un, dma_resid);
25768 		wr_pktp->pkt_resid = 0;
25769 	} else {
25770 		dma_resid = 0;
25771 	}
25772 
25773 	/* SunBug 1222170 */
25774 	wr_pktp->pkt_flags = FLAG_NOINTR;
25775 
25776 	err = EIO;
25777 	for (i = 0; i < SD_NDUMP_RETRIES; i++) {
25778 
25779 		/*
25780 		 * Scsi_poll returns 0 (success) if the command completes and
25781 		 * the status block is STATUS_GOOD.  We should only check
25782 		 * errors if this condition is not true.  Even then we should
25783 		 * send our own request sense packet only if we have a check
25784 		 * condition and auto request sense has not been performed by
25785 		 * the hba.
25786 		 */
25787 		SD_TRACE(SD_LOG_DUMP, un, "sddump: sending write\n");
25788 
25789 		if ((sd_scsi_poll(un, wr_pktp) == 0) &&
25790 		    (wr_pktp->pkt_resid == 0)) {
25791 			err = SD_SUCCESS;
25792 			break;
25793 		}
25794 
25795 		/*
25796 		 * Check CMD_DEV_GONE 1st, give up if device is gone.
25797 		 */
25798 		if (wr_pktp->pkt_reason == CMD_DEV_GONE) {
25799 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
25800 			    "Error while dumping state...Device is gone\n");
25801 			break;
25802 		}
25803 
25804 		if (SD_GET_PKT_STATUS(wr_pktp) == STATUS_CHECK) {
25805 			SD_INFO(SD_LOG_DUMP, un,
25806 			    "sddump: write failed with CHECK, try # %d\n", i);
25807 			if (((wr_pktp->pkt_state & STATE_ARQ_DONE) == 0)) {
25808 				(void) sd_send_polled_RQS(un);
25809 			}
25810 
25811 			continue;
25812 		}
25813 
25814 		if (SD_GET_PKT_STATUS(wr_pktp) == STATUS_BUSY) {
25815 			int reset_retval = 0;
25816 
25817 			SD_INFO(SD_LOG_DUMP, un,
25818 			    "sddump: write failed with BUSY, try # %d\n", i);
25819 
25820 			if (un->un_f_lun_reset_enabled == TRUE) {
25821 				reset_retval = scsi_reset(SD_ADDRESS(un),
25822 				    RESET_LUN);
25823 			}
25824 			if (reset_retval == 0) {
25825 				(void) scsi_reset(SD_ADDRESS(un), RESET_TARGET);
25826 			}
25827 			(void) sd_send_polled_RQS(un);
25828 
25829 		} else {
25830 			SD_INFO(SD_LOG_DUMP, un,
25831 			    "sddump: write failed with 0x%x, try # %d\n",
25832 			    SD_GET_PKT_STATUS(wr_pktp), i);
25833 			mutex_enter(SD_MUTEX(un));
25834 			sd_reset_target(un, wr_pktp);
25835 			mutex_exit(SD_MUTEX(un));
25836 		}
25837 
25838 		/*
25839 		 * If we are not getting anywhere with lun/target resets,
25840 		 * let's reset the bus.
25841 		 */
25842 		if (i == SD_NDUMP_RETRIES/2) {
25843 			(void) scsi_reset(SD_ADDRESS(un), RESET_ALL);
25844 			(void) sd_send_polled_RQS(un);
25845 		}
25846 	}
25847 	}
25848 
25849 	scsi_destroy_pkt(wr_pktp);
25850 	mutex_enter(SD_MUTEX(un));
25851 	if ((NOT_DEVBSIZE(un)) && (doing_rmw == TRUE)) {
25852 		mutex_exit(SD_MUTEX(un));
25853 		scsi_free_consistent_buf(wr_bp);
25854 	} else {
25855 		mutex_exit(SD_MUTEX(un));
25856 	}
25857 	SD_TRACE(SD_LOG_DUMP, un, "sddump: exit: err = %d\n", err);
25858 	return (err);
25859 }
25860 
25861 /*
25862  *    Function: sd_scsi_poll()
25863  *
25864  * Description: This is a wrapper for the scsi_poll call.
25865  *
25866  *   Arguments: sd_lun - The unit structure
25867  *              scsi_pkt - The scsi packet being sent to the device.
25868  *
25869  * Return Code: 0 - Command completed successfully with good status
25870  *             -1 - Command failed.  This could indicate a check condition
25871  *                  or other status value requiring recovery action.
25872  *
25873  * NOTE: This code is only called off sddump().
25874  */
25875 
25876 static int
25877 sd_scsi_poll(struct sd_lun *un, struct scsi_pkt *pktp)
25878 {
25879 	int status;
25880 
25881 	ASSERT(un != NULL);
25882 	ASSERT(!mutex_owned(SD_MUTEX(un)));
25883 	ASSERT(pktp != NULL);
25884 
25885 	status = SD_SUCCESS;
25886 
25887 	if (scsi_ifgetcap(&pktp->pkt_address, "tagged-qing", 1) == 1) {
25888 		pktp->pkt_flags |= un->un_tagflags;
25889 		pktp->pkt_flags &= ~FLAG_NODISCON;
25890 	}
25891 
25892 	status = sd_ddi_scsi_poll(pktp);
25893 	/*
25894 	 * Scsi_poll returns 0 (success) if the command completes and the
25895 	 * status block is STATUS_GOOD.  We should only check errors if this
25896 	 * condition is not true.  Even then we should send our own request
25897 	 * sense packet only if we have a check condition and auto
25898 	 * request sense has not been performed by the hba.
25899 	 * Don't get RQS data if pkt_reason is CMD_DEV_GONE.
25900 	 */
25901 	if ((status != SD_SUCCESS) &&
25902 	    (SD_GET_PKT_STATUS(pktp) == STATUS_CHECK) &&
25903 	    (pktp->pkt_state & STATE_ARQ_DONE) == 0 &&
25904 	    (pktp->pkt_reason != CMD_DEV_GONE))
25905 		(void) sd_send_polled_RQS(un);
25906 
25907 	return (status);
25908 }
25909 
25910 /*
25911  *    Function: sd_send_polled_RQS()
25912  *
25913  * Description: This sends the request sense command to a device.
25914  *
25915  *   Arguments: sd_lun - The unit structure
25916  *
25917  * Return Code: 0 - Command completed successfully with good status
25918  *             -1 - Command failed.
25919  *
25920  */
25921 
25922 static int
25923 sd_send_polled_RQS(struct sd_lun *un)
25924 {
25925 	int	ret_val;
25926 	struct	scsi_pkt	*rqs_pktp;
25927 	struct	buf		*rqs_bp;
25928 
25929 	ASSERT(un != NULL);
25930 	ASSERT(!mutex_owned(SD_MUTEX(un)));
25931 
25932 	ret_val = SD_SUCCESS;
25933 
25934 	rqs_pktp = un->un_rqs_pktp;
25935 	rqs_bp	 = un->un_rqs_bp;
25936 
25937 	mutex_enter(SD_MUTEX(un));
25938 
25939 	if (un->un_sense_isbusy) {
25940 		ret_val = SD_FAILURE;
25941 		mutex_exit(SD_MUTEX(un));
25942 		return (ret_val);
25943 	}
25944 
25945 	/*
25946 	 * If the request sense buffer (and packet) is not in use,
25947 	 * let's set the un_sense_isbusy and send our packet
25948 	 */
25949 	un->un_sense_isbusy 	= 1;
25950 	rqs_pktp->pkt_resid  	= 0;
25951 	rqs_pktp->pkt_reason 	= 0;
25952 	rqs_pktp->pkt_flags |= FLAG_NOINTR;
25953 	bzero(rqs_bp->b_un.b_addr, SENSE_LENGTH);
25954 
25955 	mutex_exit(SD_MUTEX(un));
25956 
25957 	SD_INFO(SD_LOG_COMMON, un, "sd_send_polled_RQS: req sense buf at"
25958 	    " 0x%p\n", rqs_bp->b_un.b_addr);
25959 
25960 	/*
25961 	 * Can't send this to sd_scsi_poll, we wrap ourselves around the
25962 	 * axle - it has a call into us!
25963 	 */
25964 	if ((ret_val = sd_ddi_scsi_poll(rqs_pktp)) != 0) {
25965 		SD_INFO(SD_LOG_COMMON, un,
25966 		    "sd_send_polled_RQS: RQS failed\n");
25967 	}
25968 
25969 	SD_DUMP_MEMORY(un, SD_LOG_COMMON, "sd_send_polled_RQS:",
25970 	    (uchar_t *)rqs_bp->b_un.b_addr, SENSE_LENGTH, SD_LOG_HEX);
25971 
25972 	mutex_enter(SD_MUTEX(un));
25973 	un->un_sense_isbusy = 0;
25974 	mutex_exit(SD_MUTEX(un));
25975 
25976 	return (ret_val);
25977 }
25978 
25979 /*
25980  * Defines needed for localized version of the scsi_poll routine.
25981  */
25982 #define	CSEC		10000			/* usecs */
25983 #define	SEC_TO_CSEC	(1000000/CSEC)
25984 
25985 /*
25986  *    Function: sd_ddi_scsi_poll()
25987  *
25988  * Description: Localized version of the scsi_poll routine.  The purpose is to
25989  *		send a scsi_pkt to a device as a polled command.  This version
25990  *		is to ensure more robust handling of transport errors.
25991  *		Specifically this routine cures not ready, coming ready
25992  *		transition for power up and reset of sonoma's.  This can take
25993  *		up to 45 seconds for power-on and 20 seconds for reset of a
25994  * 		sonoma lun.
25995  *
25996  *   Arguments: scsi_pkt - The scsi_pkt being sent to a device
25997  *
25998  * Return Code: 0 - Command completed successfully with good status
25999  *             -1 - Command failed.
26000  *
26001  * NOTE: This code is almost identical to scsi_poll, however before 6668774 can
26002  * be fixed (removing this code), we need to determine how to handle the
26003  * KEY_UNIT_ATTENTION condition below in conditions not as limited as sddump().
26004  *
26005  * NOTE: This code is only called off sddump().
26006  */
26007 static int
26008 sd_ddi_scsi_poll(struct scsi_pkt *pkt)
26009 {
26010 	int			rval = -1;
26011 	int			savef;
26012 	long			savet;
26013 	void			(*savec)();
26014 	int			timeout;
26015 	int			busy_count;
26016 	int			poll_delay;
26017 	int			rc;
26018 	uint8_t			*sensep;
26019 	struct scsi_arq_status	*arqstat;
26020 	extern int		do_polled_io;
26021 
26022 	ASSERT(pkt->pkt_scbp);
26023 
26024 	/*
26025 	 * save old flags..
26026 	 */
26027 	savef = pkt->pkt_flags;
26028 	savec = pkt->pkt_comp;
26029 	savet = pkt->pkt_time;
26030 
26031 	pkt->pkt_flags |= FLAG_NOINTR;
26032 
26033 	/*
26034 	 * XXX there is nothing in the SCSA spec that states that we should not
26035 	 * do a callback for polled cmds; however, removing this will break sd
26036 	 * and probably other target drivers
26037 	 */
26038 	pkt->pkt_comp = NULL;
26039 
26040 	/*
26041 	 * we don't like a polled command without timeout.
26042 	 * 60 seconds seems long enough.
26043 	 */
26044 	if (pkt->pkt_time == 0)
26045 		pkt->pkt_time = SCSI_POLL_TIMEOUT;
26046 
26047 	/*
26048 	 * Send polled cmd.
26049 	 *
26050 	 * We do some error recovery for various errors.  Tran_busy,
26051 	 * queue full, and non-dispatched commands are retried every 10 msec.
26052 	 * as they are typically transient failures.  Busy status and Not
26053 	 * Ready are retried every second as this status takes a while to
26054 	 * change.
26055 	 */
26056 	timeout = pkt->pkt_time * SEC_TO_CSEC;
26057 
26058 	for (busy_count = 0; busy_count < timeout; busy_count++) {
26059 		/*
26060 		 * Initialize pkt status variables.
26061 		 */
26062 		*pkt->pkt_scbp = pkt->pkt_reason = pkt->pkt_state = 0;
26063 
26064 		if ((rc = scsi_transport(pkt)) != TRAN_ACCEPT) {
26065 			if (rc != TRAN_BUSY) {
26066 				/* Transport failed - give up. */
26067 				break;
26068 			} else {
26069 				/* Transport busy - try again. */
26070 				poll_delay = 1 * CSEC;		/* 10 msec. */
26071 			}
26072 		} else {
26073 			/*
26074 			 * Transport accepted - check pkt status.
26075 			 */
26076 			rc = (*pkt->pkt_scbp) & STATUS_MASK;
26077 			if ((pkt->pkt_reason == CMD_CMPLT) &&
26078 			    (rc == STATUS_CHECK) &&
26079 			    (pkt->pkt_state & STATE_ARQ_DONE)) {
26080 				arqstat =
26081 				    (struct scsi_arq_status *)(pkt->pkt_scbp);
26082 				sensep = (uint8_t *)&arqstat->sts_sensedata;
26083 			} else {
26084 				sensep = NULL;
26085 			}
26086 
26087 			if ((pkt->pkt_reason == CMD_CMPLT) &&
26088 			    (rc == STATUS_GOOD)) {
26089 				/* No error - we're done */
26090 				rval = 0;
26091 				break;
26092 
26093 			} else if (pkt->pkt_reason == CMD_DEV_GONE) {
26094 				/* Lost connection - give up */
26095 				break;
26096 
26097 			} else if ((pkt->pkt_reason == CMD_INCOMPLETE) &&
26098 			    (pkt->pkt_state == 0)) {
26099 				/* Pkt not dispatched - try again. */
26100 				poll_delay = 1 * CSEC;		/* 10 msec. */
26101 
26102 			} else if ((pkt->pkt_reason == CMD_CMPLT) &&
26103 			    (rc == STATUS_QFULL)) {
26104 				/* Queue full - try again. */
26105 				poll_delay = 1 * CSEC;		/* 10 msec. */
26106 
26107 			} else if ((pkt->pkt_reason == CMD_CMPLT) &&
26108 			    (rc == STATUS_BUSY)) {
26109 				/* Busy - try again. */
26110 				poll_delay = 100 * CSEC;	/* 1 sec. */
26111 				busy_count += (SEC_TO_CSEC - 1);
26112 
26113 			} else if ((sensep != NULL) &&
26114 			    (scsi_sense_key(sensep) == KEY_UNIT_ATTENTION)) {
26115 				/*
26116 				 * Unit Attention - try again.
26117 				 * Pretend it took 1 sec.
26118 				 * NOTE: 'continue' avoids poll_delay
26119 				 */
26120 				busy_count += (SEC_TO_CSEC - 1);
26121 				continue;
26122 
26123 			} else if ((sensep != NULL) &&
26124 			    (scsi_sense_key(sensep) == KEY_NOT_READY) &&
26125 			    (scsi_sense_asc(sensep) == 0x04) &&
26126 			    (scsi_sense_ascq(sensep) == 0x01)) {
26127 				/*
26128 				 * Not ready -> ready - try again.
26129 				 * 04h/01h: LUN IS IN PROCESS OF BECOMING READY
26130 				 * ...same as STATUS_BUSY
26131 				 */
26132 				poll_delay = 100 * CSEC;	/* 1 sec. */
26133 				busy_count += (SEC_TO_CSEC - 1);
26134 
26135 			} else {
26136 				/* BAD status - give up. */
26137 				break;
26138 			}
26139 		}
26140 
26141 		if (((curthread->t_flag & T_INTR_THREAD) == 0) &&
26142 		    !do_polled_io) {
26143 			delay(drv_usectohz(poll_delay));
26144 		} else {
26145 			/* we busy wait during cpr_dump or interrupt threads */
26146 			drv_usecwait(poll_delay);
26147 		}
26148 	}
26149 
26150 	pkt->pkt_flags = savef;
26151 	pkt->pkt_comp = savec;
26152 	pkt->pkt_time = savet;
26153 
26154 	/* return on error */
26155 	if (rval)
26156 		return (rval);
26157 
26158 	/*
26159 	 * This is not a performance critical code path.
26160 	 *
26161 	 * As an accommodation for scsi_poll callers, to avoid ddi_dma_sync()
26162 	 * issues associated with looking at DMA memory prior to
26163 	 * scsi_pkt_destroy(), we scsi_sync_pkt() prior to return.
26164 	 */
26165 	scsi_sync_pkt(pkt);
26166 	return (0);
26167 }
26168 
26169 
26170 
26171 /*
26172  *    Function: sd_persistent_reservation_in_read_keys
26173  *
26174  * Description: This routine is the driver entry point for handling CD-ROM
26175  *		multi-host persistent reservation requests (MHIOCGRP_INKEYS)
26176  *		by sending the SCSI-3 PRIN commands to the device.
26177  *		Processes the read keys command response by copying the
26178  *		reservation key information into the user provided buffer.
26179  *		Support for the 32/64 bit _MULTI_DATAMODEL is implemented.
26180  *
26181  *   Arguments: un   -  Pointer to soft state struct for the target.
26182  *		usrp -	user provided pointer to multihost Persistent In Read
26183  *			Keys structure (mhioc_inkeys_t)
26184  *		flag -	this argument is a pass through to ddi_copyxxx()
26185  *			directly from the mode argument of ioctl().
26186  *
26187  * Return Code: 0   - Success
26188  *		EACCES
26189  *		ENOTSUP
26190  *		errno return code from sd_send_scsi_cmd()
26191  *
26192  *     Context: Can sleep. Does not return until command is completed.
26193  */
26194 
26195 static int
26196 sd_persistent_reservation_in_read_keys(struct sd_lun *un,
26197     mhioc_inkeys_t *usrp, int flag)
26198 {
26199 #ifdef _MULTI_DATAMODEL
26200 	struct mhioc_key_list32	li32;
26201 #endif
26202 	sd_prin_readkeys_t	*in;
26203 	mhioc_inkeys_t		*ptr;
26204 	mhioc_key_list_t	li;
26205 	uchar_t			*data_bufp;
26206 	int 			data_len;
26207 	int			rval = 0;
26208 	size_t			copysz;
26209 	sd_ssc_t		*ssc;
26210 
26211 	if ((ptr = (mhioc_inkeys_t *)usrp) == NULL) {
26212 		return (EINVAL);
26213 	}
26214 	bzero(&li, sizeof (mhioc_key_list_t));
26215 
26216 	ssc = sd_ssc_init(un);
26217 
26218 	/*
26219 	 * Get the listsize from user
26220 	 */
26221 #ifdef _MULTI_DATAMODEL
26222 
26223 	switch (ddi_model_convert_from(flag & FMODELS)) {
26224 	case DDI_MODEL_ILP32:
26225 		copysz = sizeof (struct mhioc_key_list32);
26226 		if (ddi_copyin(ptr->li, &li32, copysz, flag)) {
26227 			SD_ERROR(SD_LOG_IOCTL_MHD, un,
26228 			    "sd_persistent_reservation_in_read_keys: "
26229 			    "failed ddi_copyin: mhioc_key_list32_t\n");
26230 			rval = EFAULT;
26231 			goto done;
26232 		}
26233 		li.listsize = li32.listsize;
26234 		li.list = (mhioc_resv_key_t *)(uintptr_t)li32.list;
26235 		break;
26236 
26237 	case DDI_MODEL_NONE:
26238 		copysz = sizeof (mhioc_key_list_t);
26239 		if (ddi_copyin(ptr->li, &li, copysz, flag)) {
26240 			SD_ERROR(SD_LOG_IOCTL_MHD, un,
26241 			    "sd_persistent_reservation_in_read_keys: "
26242 			    "failed ddi_copyin: mhioc_key_list_t\n");
26243 			rval = EFAULT;
26244 			goto done;
26245 		}
26246 		break;
26247 	}
26248 
26249 #else /* ! _MULTI_DATAMODEL */
26250 	copysz = sizeof (mhioc_key_list_t);
26251 	if (ddi_copyin(ptr->li, &li, copysz, flag)) {
26252 		SD_ERROR(SD_LOG_IOCTL_MHD, un,
26253 		    "sd_persistent_reservation_in_read_keys: "
26254 		    "failed ddi_copyin: mhioc_key_list_t\n");
26255 		rval = EFAULT;
26256 		goto done;
26257 	}
26258 #endif
26259 
26260 	data_len  = li.listsize * MHIOC_RESV_KEY_SIZE;
26261 	data_len += (sizeof (sd_prin_readkeys_t) - sizeof (caddr_t));
26262 	data_bufp = kmem_zalloc(data_len, KM_SLEEP);
26263 
26264 	rval = sd_send_scsi_PERSISTENT_RESERVE_IN(ssc, SD_READ_KEYS,
26265 	    data_len, data_bufp);
26266 	if (rval != 0) {
26267 		if (rval == EIO)
26268 			sd_ssc_assessment(ssc, SD_FMT_IGNORE_COMPROMISE);
26269 		else
26270 			sd_ssc_assessment(ssc, SD_FMT_IGNORE);
26271 		goto done;
26272 	}
26273 	in = (sd_prin_readkeys_t *)data_bufp;
26274 	ptr->generation = BE_32(in->generation);
26275 	li.listlen = BE_32(in->len) / MHIOC_RESV_KEY_SIZE;
26276 
26277 	/*
26278 	 * Return the min(listsize, listlen) keys
26279 	 */
26280 #ifdef _MULTI_DATAMODEL
26281 
26282 	switch (ddi_model_convert_from(flag & FMODELS)) {
26283 	case DDI_MODEL_ILP32:
26284 		li32.listlen = li.listlen;
26285 		if (ddi_copyout(&li32, ptr->li, copysz, flag)) {
26286 			SD_ERROR(SD_LOG_IOCTL_MHD, un,
26287 			    "sd_persistent_reservation_in_read_keys: "
26288 			    "failed ddi_copyout: mhioc_key_list32_t\n");
26289 			rval = EFAULT;
26290 			goto done;
26291 		}
26292 		break;
26293 
26294 	case DDI_MODEL_NONE:
26295 		if (ddi_copyout(&li, ptr->li, copysz, flag)) {
26296 			SD_ERROR(SD_LOG_IOCTL_MHD, un,
26297 			    "sd_persistent_reservation_in_read_keys: "
26298 			    "failed ddi_copyout: mhioc_key_list_t\n");
26299 			rval = EFAULT;
26300 			goto done;
26301 		}
26302 		break;
26303 	}
26304 
26305 #else /* ! _MULTI_DATAMODEL */
26306 
26307 	if (ddi_copyout(&li, ptr->li, copysz, flag)) {
26308 		SD_ERROR(SD_LOG_IOCTL_MHD, un,
26309 		    "sd_persistent_reservation_in_read_keys: "
26310 		    "failed ddi_copyout: mhioc_key_list_t\n");
26311 		rval = EFAULT;
26312 		goto done;
26313 	}
26314 
26315 #endif /* _MULTI_DATAMODEL */
26316 
26317 	copysz = min(li.listlen * MHIOC_RESV_KEY_SIZE,
26318 	    li.listsize * MHIOC_RESV_KEY_SIZE);
26319 	if (ddi_copyout(&in->keylist, li.list, copysz, flag)) {
26320 		SD_ERROR(SD_LOG_IOCTL_MHD, un,
26321 		    "sd_persistent_reservation_in_read_keys: "
26322 		    "failed ddi_copyout: keylist\n");
26323 		rval = EFAULT;
26324 	}
26325 done:
26326 	sd_ssc_fini(ssc);
26327 	kmem_free(data_bufp, data_len);
26328 	return (rval);
26329 }
26330 
26331 
26332 /*
26333  *    Function: sd_persistent_reservation_in_read_resv
26334  *
26335  * Description: This routine is the driver entry point for handling CD-ROM
26336  *		multi-host persistent reservation requests (MHIOCGRP_INRESV)
26337  *		by sending the SCSI-3 PRIN commands to the device.
26338  *		Process the read persistent reservations command response by
26339  *		copying the reservation information into the user provided
26340  *		buffer. Support for the 32/64 _MULTI_DATAMODEL is implemented.
26341  *
26342  *   Arguments: un   -  Pointer to soft state struct for the target.
26343  *		usrp -	user provided pointer to multihost Persistent In Read
26344  *			Keys structure (mhioc_inkeys_t)
26345  *		flag -	this argument is a pass through to ddi_copyxxx()
26346  *			directly from the mode argument of ioctl().
26347  *
26348  * Return Code: 0   - Success
26349  *		EACCES
26350  *		ENOTSUP
26351  *		errno return code from sd_send_scsi_cmd()
26352  *
26353  *     Context: Can sleep. Does not return until command is completed.
26354  */
26355 
26356 static int
26357 sd_persistent_reservation_in_read_resv(struct sd_lun *un,
26358     mhioc_inresvs_t *usrp, int flag)
26359 {
26360 #ifdef _MULTI_DATAMODEL
26361 	struct mhioc_resv_desc_list32 resvlist32;
26362 #endif
26363 	sd_prin_readresv_t	*in;
26364 	mhioc_inresvs_t		*ptr;
26365 	sd_readresv_desc_t	*readresv_ptr;
26366 	mhioc_resv_desc_list_t	resvlist;
26367 	mhioc_resv_desc_t 	resvdesc;
26368 	uchar_t			*data_bufp = NULL;
26369 	int 			data_len;
26370 	int			rval = 0;
26371 	int			i;
26372 	size_t			copysz;
26373 	mhioc_resv_desc_t	*bufp;
26374 	sd_ssc_t		*ssc;
26375 
26376 	if ((ptr = usrp) == NULL) {
26377 		return (EINVAL);
26378 	}
26379 
26380 	ssc = sd_ssc_init(un);
26381 
26382 	/*
26383 	 * Get the listsize from user
26384 	 */
26385 #ifdef _MULTI_DATAMODEL
26386 	switch (ddi_model_convert_from(flag & FMODELS)) {
26387 	case DDI_MODEL_ILP32:
26388 		copysz = sizeof (struct mhioc_resv_desc_list32);
26389 		if (ddi_copyin(ptr->li, &resvlist32, copysz, flag)) {
26390 			SD_ERROR(SD_LOG_IOCTL_MHD, un,
26391 			    "sd_persistent_reservation_in_read_resv: "
26392 			    "failed ddi_copyin: mhioc_resv_desc_list_t\n");
26393 			rval = EFAULT;
26394 			goto done;
26395 		}
26396 		resvlist.listsize = resvlist32.listsize;
26397 		resvlist.list = (mhioc_resv_desc_t *)(uintptr_t)resvlist32.list;
26398 		break;
26399 
26400 	case DDI_MODEL_NONE:
26401 		copysz = sizeof (mhioc_resv_desc_list_t);
26402 		if (ddi_copyin(ptr->li, &resvlist, copysz, flag)) {
26403 			SD_ERROR(SD_LOG_IOCTL_MHD, un,
26404 			    "sd_persistent_reservation_in_read_resv: "
26405 			    "failed ddi_copyin: mhioc_resv_desc_list_t\n");
26406 			rval = EFAULT;
26407 			goto done;
26408 		}
26409 		break;
26410 	}
26411 #else /* ! _MULTI_DATAMODEL */
26412 	copysz = sizeof (mhioc_resv_desc_list_t);
26413 	if (ddi_copyin(ptr->li, &resvlist, copysz, flag)) {
26414 		SD_ERROR(SD_LOG_IOCTL_MHD, un,
26415 		    "sd_persistent_reservation_in_read_resv: "
26416 		    "failed ddi_copyin: mhioc_resv_desc_list_t\n");
26417 		rval = EFAULT;
26418 		goto done;
26419 	}
26420 #endif /* ! _MULTI_DATAMODEL */
26421 
26422 	data_len  = resvlist.listsize * SCSI3_RESV_DESC_LEN;
26423 	data_len += (sizeof (sd_prin_readresv_t) - sizeof (caddr_t));
26424 	data_bufp = kmem_zalloc(data_len, KM_SLEEP);
26425 
26426 	rval = sd_send_scsi_PERSISTENT_RESERVE_IN(ssc, SD_READ_RESV,
26427 	    data_len, data_bufp);
26428 	if (rval != 0) {
26429 		if (rval == EIO)
26430 			sd_ssc_assessment(ssc, SD_FMT_IGNORE_COMPROMISE);
26431 		else
26432 			sd_ssc_assessment(ssc, SD_FMT_IGNORE);
26433 		goto done;
26434 	}
26435 	in = (sd_prin_readresv_t *)data_bufp;
26436 	ptr->generation = BE_32(in->generation);
26437 	resvlist.listlen = BE_32(in->len) / SCSI3_RESV_DESC_LEN;
26438 
26439 	/*
26440 	 * Return the min(listsize, listlen( keys
26441 	 */
26442 #ifdef _MULTI_DATAMODEL
26443 
26444 	switch (ddi_model_convert_from(flag & FMODELS)) {
26445 	case DDI_MODEL_ILP32:
26446 		resvlist32.listlen = resvlist.listlen;
26447 		if (ddi_copyout(&resvlist32, ptr->li, copysz, flag)) {
26448 			SD_ERROR(SD_LOG_IOCTL_MHD, un,
26449 			    "sd_persistent_reservation_in_read_resv: "
26450 			    "failed ddi_copyout: mhioc_resv_desc_list_t\n");
26451 			rval = EFAULT;
26452 			goto done;
26453 		}
26454 		break;
26455 
26456 	case DDI_MODEL_NONE:
26457 		if (ddi_copyout(&resvlist, ptr->li, copysz, flag)) {
26458 			SD_ERROR(SD_LOG_IOCTL_MHD, un,
26459 			    "sd_persistent_reservation_in_read_resv: "
26460 			    "failed ddi_copyout: mhioc_resv_desc_list_t\n");
26461 			rval = EFAULT;
26462 			goto done;
26463 		}
26464 		break;
26465 	}
26466 
26467 #else /* ! _MULTI_DATAMODEL */
26468 
26469 	if (ddi_copyout(&resvlist, ptr->li, copysz, flag)) {
26470 		SD_ERROR(SD_LOG_IOCTL_MHD, un,
26471 		    "sd_persistent_reservation_in_read_resv: "
26472 		    "failed ddi_copyout: mhioc_resv_desc_list_t\n");
26473 		rval = EFAULT;
26474 		goto done;
26475 	}
26476 
26477 #endif /* ! _MULTI_DATAMODEL */
26478 
26479 	readresv_ptr = (sd_readresv_desc_t *)&in->readresv_desc;
26480 	bufp = resvlist.list;
26481 	copysz = sizeof (mhioc_resv_desc_t);
26482 	for (i = 0; i < min(resvlist.listlen, resvlist.listsize);
26483 	    i++, readresv_ptr++, bufp++) {
26484 
26485 		bcopy(&readresv_ptr->resvkey, &resvdesc.key,
26486 		    MHIOC_RESV_KEY_SIZE);
26487 		resvdesc.type  = readresv_ptr->type;
26488 		resvdesc.scope = readresv_ptr->scope;
26489 		resvdesc.scope_specific_addr =
26490 		    BE_32(readresv_ptr->scope_specific_addr);
26491 
26492 		if (ddi_copyout(&resvdesc, bufp, copysz, flag)) {
26493 			SD_ERROR(SD_LOG_IOCTL_MHD, un,
26494 			    "sd_persistent_reservation_in_read_resv: "
26495 			    "failed ddi_copyout: resvlist\n");
26496 			rval = EFAULT;
26497 			goto done;
26498 		}
26499 	}
26500 done:
26501 	sd_ssc_fini(ssc);
26502 	/* only if data_bufp is allocated, we need to free it */
26503 	if (data_bufp) {
26504 		kmem_free(data_bufp, data_len);
26505 	}
26506 	return (rval);
26507 }
26508 
26509 
26510 /*
26511  *    Function: sr_change_blkmode()
26512  *
26513  * Description: This routine is the driver entry point for handling CD-ROM
26514  *		block mode ioctl requests. Support for returning and changing
26515  *		the current block size in use by the device is implemented. The
26516  *		LBA size is changed via a MODE SELECT Block Descriptor.
26517  *
26518  *		This routine issues a mode sense with an allocation length of
26519  *		12 bytes for the mode page header and a single block descriptor.
26520  *
26521  *   Arguments: dev - the device 'dev_t'
26522  *		cmd - the request type; one of CDROMGBLKMODE (get) or
26523  *		      CDROMSBLKMODE (set)
26524  *		data - current block size or requested block size
26525  *		flag - this argument is a pass through to ddi_copyxxx() directly
26526  *		       from the mode argument of ioctl().
26527  *
26528  * Return Code: the code returned by sd_send_scsi_cmd()
26529  *		EINVAL if invalid arguments are provided
26530  *		EFAULT if ddi_copyxxx() fails
26531  *		ENXIO if fail ddi_get_soft_state
26532  *		EIO if invalid mode sense block descriptor length
26533  *
26534  */
26535 
26536 static int
26537 sr_change_blkmode(dev_t dev, int cmd, intptr_t data, int flag)
26538 {
26539 	struct sd_lun			*un = NULL;
26540 	struct mode_header		*sense_mhp, *select_mhp;
26541 	struct block_descriptor		*sense_desc, *select_desc;
26542 	int				current_bsize;
26543 	int				rval = EINVAL;
26544 	uchar_t				*sense = NULL;
26545 	uchar_t				*select = NULL;
26546 	sd_ssc_t			*ssc;
26547 
26548 	ASSERT((cmd == CDROMGBLKMODE) || (cmd == CDROMSBLKMODE));
26549 
26550 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
26551 		return (ENXIO);
26552 	}
26553 
26554 	/*
26555 	 * The block length is changed via the Mode Select block descriptor, the
26556 	 * "Read/Write Error Recovery" mode page (0x1) contents are not actually
26557 	 * required as part of this routine. Therefore the mode sense allocation
26558 	 * length is specified to be the length of a mode page header and a
26559 	 * block descriptor.
26560 	 */
26561 	sense = kmem_zalloc(BUFLEN_CHG_BLK_MODE, KM_SLEEP);
26562 
26563 	ssc = sd_ssc_init(un);
26564 	rval = sd_send_scsi_MODE_SENSE(ssc, CDB_GROUP0, sense,
26565 	    BUFLEN_CHG_BLK_MODE, MODEPAGE_ERR_RECOV, SD_PATH_STANDARD);
26566 	sd_ssc_fini(ssc);
26567 	if (rval != 0) {
26568 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
26569 		    "sr_change_blkmode: Mode Sense Failed\n");
26570 		kmem_free(sense, BUFLEN_CHG_BLK_MODE);
26571 		return (rval);
26572 	}
26573 
26574 	/* Check the block descriptor len to handle only 1 block descriptor */
26575 	sense_mhp = (struct mode_header *)sense;
26576 	if ((sense_mhp->bdesc_length == 0) ||
26577 	    (sense_mhp->bdesc_length > MODE_BLK_DESC_LENGTH)) {
26578 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
26579 		    "sr_change_blkmode: Mode Sense returned invalid block"
26580 		    " descriptor length\n");
26581 		kmem_free(sense, BUFLEN_CHG_BLK_MODE);
26582 		return (EIO);
26583 	}
26584 	sense_desc = (struct block_descriptor *)(sense + MODE_HEADER_LENGTH);
26585 	current_bsize = ((sense_desc->blksize_hi << 16) |
26586 	    (sense_desc->blksize_mid << 8) | sense_desc->blksize_lo);
26587 
26588 	/* Process command */
26589 	switch (cmd) {
26590 	case CDROMGBLKMODE:
26591 		/* Return the block size obtained during the mode sense */
26592 		if (ddi_copyout(&current_bsize, (void *)data,
26593 		    sizeof (int), flag) != 0)
26594 			rval = EFAULT;
26595 		break;
26596 	case CDROMSBLKMODE:
26597 		/* Validate the requested block size */
26598 		switch (data) {
26599 		case CDROM_BLK_512:
26600 		case CDROM_BLK_1024:
26601 		case CDROM_BLK_2048:
26602 		case CDROM_BLK_2056:
26603 		case CDROM_BLK_2336:
26604 		case CDROM_BLK_2340:
26605 		case CDROM_BLK_2352:
26606 		case CDROM_BLK_2368:
26607 		case CDROM_BLK_2448:
26608 		case CDROM_BLK_2646:
26609 		case CDROM_BLK_2647:
26610 			break;
26611 		default:
26612 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
26613 			    "sr_change_blkmode: "
26614 			    "Block Size '%ld' Not Supported\n", data);
26615 			kmem_free(sense, BUFLEN_CHG_BLK_MODE);
26616 			return (EINVAL);
26617 		}
26618 
26619 		/*
26620 		 * The current block size matches the requested block size so
26621 		 * there is no need to send the mode select to change the size
26622 		 */
26623 		if (current_bsize == data) {
26624 			break;
26625 		}
26626 
26627 		/* Build the select data for the requested block size */
26628 		select = kmem_zalloc(BUFLEN_CHG_BLK_MODE, KM_SLEEP);
26629 		select_mhp = (struct mode_header *)select;
26630 		select_desc =
26631 		    (struct block_descriptor *)(select + MODE_HEADER_LENGTH);
26632 		/*
26633 		 * The LBA size is changed via the block descriptor, so the
26634 		 * descriptor is built according to the user data
26635 		 */
26636 		select_mhp->bdesc_length = MODE_BLK_DESC_LENGTH;
26637 		select_desc->blksize_hi  = (char)(((data) & 0x00ff0000) >> 16);
26638 		select_desc->blksize_mid = (char)(((data) & 0x0000ff00) >> 8);
26639 		select_desc->blksize_lo  = (char)((data) & 0x000000ff);
26640 
26641 		/* Send the mode select for the requested block size */
26642 		ssc = sd_ssc_init(un);
26643 		rval = sd_send_scsi_MODE_SELECT(ssc, CDB_GROUP0,
26644 		    select, BUFLEN_CHG_BLK_MODE, SD_DONTSAVE_PAGE,
26645 		    SD_PATH_STANDARD);
26646 		sd_ssc_fini(ssc);
26647 		if (rval != 0) {
26648 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
26649 			    "sr_change_blkmode: Mode Select Failed\n");
26650 			/*
26651 			 * The mode select failed for the requested block size,
26652 			 * so reset the data for the original block size and
26653 			 * send it to the target. The error is indicated by the
26654 			 * return value for the failed mode select.
26655 			 */
26656 			select_desc->blksize_hi  = sense_desc->blksize_hi;
26657 			select_desc->blksize_mid = sense_desc->blksize_mid;
26658 			select_desc->blksize_lo  = sense_desc->blksize_lo;
26659 			ssc = sd_ssc_init(un);
26660 			(void) sd_send_scsi_MODE_SELECT(ssc, CDB_GROUP0,
26661 			    select, BUFLEN_CHG_BLK_MODE, SD_DONTSAVE_PAGE,
26662 			    SD_PATH_STANDARD);
26663 			sd_ssc_fini(ssc);
26664 		} else {
26665 			ASSERT(!mutex_owned(SD_MUTEX(un)));
26666 			mutex_enter(SD_MUTEX(un));
26667 			sd_update_block_info(un, (uint32_t)data, 0);
26668 			mutex_exit(SD_MUTEX(un));
26669 		}
26670 		break;
26671 	default:
26672 		/* should not reach here, but check anyway */
26673 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
26674 		    "sr_change_blkmode: Command '%x' Not Supported\n", cmd);
26675 		rval = EINVAL;
26676 		break;
26677 	}
26678 
26679 	if (select) {
26680 		kmem_free(select, BUFLEN_CHG_BLK_MODE);
26681 	}
26682 	if (sense) {
26683 		kmem_free(sense, BUFLEN_CHG_BLK_MODE);
26684 	}
26685 	return (rval);
26686 }
26687 
26688 
26689 /*
26690  * Note: The following sr_change_speed() and sr_atapi_change_speed() routines
26691  * implement driver support for getting and setting the CD speed. The command
26692  * set used will be based on the device type. If the device has not been
26693  * identified as MMC the Toshiba vendor specific mode page will be used. If
26694  * the device is MMC but does not support the Real Time Streaming feature
26695  * the SET CD SPEED command will be used to set speed and mode page 0x2A will
26696  * be used to read the speed.
26697  */
26698 
26699 /*
26700  *    Function: sr_change_speed()
26701  *
26702  * Description: This routine is the driver entry point for handling CD-ROM
26703  *		drive speed ioctl requests for devices supporting the Toshiba
26704  *		vendor specific drive speed mode page. Support for returning
26705  *		and changing the current drive speed in use by the device is
26706  *		implemented.
26707  *
26708  *   Arguments: dev - the device 'dev_t'
26709  *		cmd - the request type; one of CDROMGDRVSPEED (get) or
26710  *		      CDROMSDRVSPEED (set)
26711  *		data - current drive speed or requested drive speed
26712  *		flag - this argument is a pass through to ddi_copyxxx() directly
26713  *		       from the mode argument of ioctl().
26714  *
26715  * Return Code: the code returned by sd_send_scsi_cmd()
26716  *		EINVAL if invalid arguments are provided
26717  *		EFAULT if ddi_copyxxx() fails
26718  *		ENXIO if fail ddi_get_soft_state
26719  *		EIO if invalid mode sense block descriptor length
26720  */
26721 
26722 static int
26723 sr_change_speed(dev_t dev, int cmd, intptr_t data, int flag)
26724 {
26725 	struct sd_lun			*un = NULL;
26726 	struct mode_header		*sense_mhp, *select_mhp;
26727 	struct mode_speed		*sense_page, *select_page;
26728 	int				current_speed;
26729 	int				rval = EINVAL;
26730 	int				bd_len;
26731 	uchar_t				*sense = NULL;
26732 	uchar_t				*select = NULL;
26733 	sd_ssc_t			*ssc;
26734 
26735 	ASSERT((cmd == CDROMGDRVSPEED) || (cmd == CDROMSDRVSPEED));
26736 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
26737 		return (ENXIO);
26738 	}
26739 
26740 	/*
26741 	 * Note: The drive speed is being modified here according to a Toshiba
26742 	 * vendor specific mode page (0x31).
26743 	 */
26744 	sense = kmem_zalloc(BUFLEN_MODE_CDROM_SPEED, KM_SLEEP);
26745 
26746 	ssc = sd_ssc_init(un);
26747 	rval = sd_send_scsi_MODE_SENSE(ssc, CDB_GROUP0, sense,
26748 	    BUFLEN_MODE_CDROM_SPEED, CDROM_MODE_SPEED,
26749 	    SD_PATH_STANDARD);
26750 	sd_ssc_fini(ssc);
26751 	if (rval != 0) {
26752 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
26753 		    "sr_change_speed: Mode Sense Failed\n");
26754 		kmem_free(sense, BUFLEN_MODE_CDROM_SPEED);
26755 		return (rval);
26756 	}
26757 	sense_mhp  = (struct mode_header *)sense;
26758 
26759 	/* Check the block descriptor len to handle only 1 block descriptor */
26760 	bd_len = sense_mhp->bdesc_length;
26761 	if (bd_len > MODE_BLK_DESC_LENGTH) {
26762 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
26763 		    "sr_change_speed: Mode Sense returned invalid block "
26764 		    "descriptor length\n");
26765 		kmem_free(sense, BUFLEN_MODE_CDROM_SPEED);
26766 		return (EIO);
26767 	}
26768 
26769 	sense_page = (struct mode_speed *)
26770 	    (sense + MODE_HEADER_LENGTH + sense_mhp->bdesc_length);
26771 	current_speed = sense_page->speed;
26772 
26773 	/* Process command */
26774 	switch (cmd) {
26775 	case CDROMGDRVSPEED:
26776 		/* Return the drive speed obtained during the mode sense */
26777 		if (current_speed == 0x2) {
26778 			current_speed = CDROM_TWELVE_SPEED;
26779 		}
26780 		if (ddi_copyout(&current_speed, (void *)data,
26781 		    sizeof (int), flag) != 0) {
26782 			rval = EFAULT;
26783 		}
26784 		break;
26785 	case CDROMSDRVSPEED:
26786 		/* Validate the requested drive speed */
26787 		switch ((uchar_t)data) {
26788 		case CDROM_TWELVE_SPEED:
26789 			data = 0x2;
26790 			/*FALLTHROUGH*/
26791 		case CDROM_NORMAL_SPEED:
26792 		case CDROM_DOUBLE_SPEED:
26793 		case CDROM_QUAD_SPEED:
26794 		case CDROM_MAXIMUM_SPEED:
26795 			break;
26796 		default:
26797 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
26798 			    "sr_change_speed: "
26799 			    "Drive Speed '%d' Not Supported\n", (uchar_t)data);
26800 			kmem_free(sense, BUFLEN_MODE_CDROM_SPEED);
26801 			return (EINVAL);
26802 		}
26803 
26804 		/*
26805 		 * The current drive speed matches the requested drive speed so
26806 		 * there is no need to send the mode select to change the speed
26807 		 */
26808 		if (current_speed == data) {
26809 			break;
26810 		}
26811 
26812 		/* Build the select data for the requested drive speed */
26813 		select = kmem_zalloc(BUFLEN_MODE_CDROM_SPEED, KM_SLEEP);
26814 		select_mhp = (struct mode_header *)select;
26815 		select_mhp->bdesc_length = 0;
26816 		select_page =
26817 		    (struct mode_speed *)(select + MODE_HEADER_LENGTH);
26818 		select_page =
26819 		    (struct mode_speed *)(select + MODE_HEADER_LENGTH);
26820 		select_page->mode_page.code = CDROM_MODE_SPEED;
26821 		select_page->mode_page.length = 2;
26822 		select_page->speed = (uchar_t)data;
26823 
26824 		/* Send the mode select for the requested block size */
26825 		ssc = sd_ssc_init(un);
26826 		rval = sd_send_scsi_MODE_SELECT(ssc, CDB_GROUP0, select,
26827 		    MODEPAGE_CDROM_SPEED_LEN + MODE_HEADER_LENGTH,
26828 		    SD_DONTSAVE_PAGE, SD_PATH_STANDARD);
26829 		sd_ssc_fini(ssc);
26830 		if (rval != 0) {
26831 			/*
26832 			 * The mode select failed for the requested drive speed,
26833 			 * so reset the data for the original drive speed and
26834 			 * send it to the target. The error is indicated by the
26835 			 * return value for the failed mode select.
26836 			 */
26837 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
26838 			    "sr_drive_speed: Mode Select Failed\n");
26839 			select_page->speed = sense_page->speed;
26840 			ssc = sd_ssc_init(un);
26841 			(void) sd_send_scsi_MODE_SELECT(ssc, CDB_GROUP0, select,
26842 			    MODEPAGE_CDROM_SPEED_LEN + MODE_HEADER_LENGTH,
26843 			    SD_DONTSAVE_PAGE, SD_PATH_STANDARD);
26844 			sd_ssc_fini(ssc);
26845 		}
26846 		break;
26847 	default:
26848 		/* should not reach here, but check anyway */
26849 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
26850 		    "sr_change_speed: Command '%x' Not Supported\n", cmd);
26851 		rval = EINVAL;
26852 		break;
26853 	}
26854 
26855 	if (select) {
26856 		kmem_free(select, BUFLEN_MODE_CDROM_SPEED);
26857 	}
26858 	if (sense) {
26859 		kmem_free(sense, BUFLEN_MODE_CDROM_SPEED);
26860 	}
26861 
26862 	return (rval);
26863 }
26864 
26865 
26866 /*
26867  *    Function: sr_atapi_change_speed()
26868  *
26869  * Description: This routine is the driver entry point for handling CD-ROM
26870  *		drive speed ioctl requests for MMC devices that do not support
26871  *		the Real Time Streaming feature (0x107).
26872  *
26873  *		Note: This routine will use the SET SPEED command which may not
26874  *		be supported by all devices.
26875  *
26876  *   Arguments: dev- the device 'dev_t'
26877  *		cmd- the request type; one of CDROMGDRVSPEED (get) or
26878  *		     CDROMSDRVSPEED (set)
26879  *		data- current drive speed or requested drive speed
26880  *		flag- this argument is a pass through to ddi_copyxxx() directly
26881  *		      from the mode argument of ioctl().
26882  *
26883  * Return Code: the code returned by sd_send_scsi_cmd()
26884  *		EINVAL if invalid arguments are provided
26885  *		EFAULT if ddi_copyxxx() fails
26886  *		ENXIO if fail ddi_get_soft_state
26887  *		EIO if invalid mode sense block descriptor length
26888  */
26889 
26890 static int
26891 sr_atapi_change_speed(dev_t dev, int cmd, intptr_t data, int flag)
26892 {
26893 	struct sd_lun			*un;
26894 	struct uscsi_cmd		*com = NULL;
26895 	struct mode_header_grp2		*sense_mhp;
26896 	uchar_t				*sense_page;
26897 	uchar_t				*sense = NULL;
26898 	char				cdb[CDB_GROUP5];
26899 	int				bd_len;
26900 	int				current_speed = 0;
26901 	int				max_speed = 0;
26902 	int				rval;
26903 	sd_ssc_t			*ssc;
26904 
26905 	ASSERT((cmd == CDROMGDRVSPEED) || (cmd == CDROMSDRVSPEED));
26906 
26907 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
26908 		return (ENXIO);
26909 	}
26910 
26911 	sense = kmem_zalloc(BUFLEN_MODE_CDROM_CAP, KM_SLEEP);
26912 
26913 	ssc = sd_ssc_init(un);
26914 	rval = sd_send_scsi_MODE_SENSE(ssc, CDB_GROUP1, sense,
26915 	    BUFLEN_MODE_CDROM_CAP, MODEPAGE_CDROM_CAP,
26916 	    SD_PATH_STANDARD);
26917 	sd_ssc_fini(ssc);
26918 	if (rval != 0) {
26919 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
26920 		    "sr_atapi_change_speed: Mode Sense Failed\n");
26921 		kmem_free(sense, BUFLEN_MODE_CDROM_CAP);
26922 		return (rval);
26923 	}
26924 
26925 	/* Check the block descriptor len to handle only 1 block descriptor */
26926 	sense_mhp = (struct mode_header_grp2 *)sense;
26927 	bd_len = (sense_mhp->bdesc_length_hi << 8) | sense_mhp->bdesc_length_lo;
26928 	if (bd_len > MODE_BLK_DESC_LENGTH) {
26929 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
26930 		    "sr_atapi_change_speed: Mode Sense returned invalid "
26931 		    "block descriptor length\n");
26932 		kmem_free(sense, BUFLEN_MODE_CDROM_CAP);
26933 		return (EIO);
26934 	}
26935 
26936 	/* Calculate the current and maximum drive speeds */
26937 	sense_page = (uchar_t *)(sense + MODE_HEADER_LENGTH_GRP2 + bd_len);
26938 	current_speed = (sense_page[14] << 8) | sense_page[15];
26939 	max_speed = (sense_page[8] << 8) | sense_page[9];
26940 
26941 	/* Process the command */
26942 	switch (cmd) {
26943 	case CDROMGDRVSPEED:
26944 		current_speed /= SD_SPEED_1X;
26945 		if (ddi_copyout(&current_speed, (void *)data,
26946 		    sizeof (int), flag) != 0)
26947 			rval = EFAULT;
26948 		break;
26949 	case CDROMSDRVSPEED:
26950 		/* Convert the speed code to KB/sec */
26951 		switch ((uchar_t)data) {
26952 		case CDROM_NORMAL_SPEED:
26953 			current_speed = SD_SPEED_1X;
26954 			break;
26955 		case CDROM_DOUBLE_SPEED:
26956 			current_speed = 2 * SD_SPEED_1X;
26957 			break;
26958 		case CDROM_QUAD_SPEED:
26959 			current_speed = 4 * SD_SPEED_1X;
26960 			break;
26961 		case CDROM_TWELVE_SPEED:
26962 			current_speed = 12 * SD_SPEED_1X;
26963 			break;
26964 		case CDROM_MAXIMUM_SPEED:
26965 			current_speed = 0xffff;
26966 			break;
26967 		default:
26968 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
26969 			    "sr_atapi_change_speed: invalid drive speed %d\n",
26970 			    (uchar_t)data);
26971 			kmem_free(sense, BUFLEN_MODE_CDROM_CAP);
26972 			return (EINVAL);
26973 		}
26974 
26975 		/* Check the request against the drive's max speed. */
26976 		if (current_speed != 0xffff) {
26977 			if (current_speed > max_speed) {
26978 				kmem_free(sense, BUFLEN_MODE_CDROM_CAP);
26979 				return (EINVAL);
26980 			}
26981 		}
26982 
26983 		/*
26984 		 * Build and send the SET SPEED command
26985 		 *
26986 		 * Note: The SET SPEED (0xBB) command used in this routine is
26987 		 * obsolete per the SCSI MMC spec but still supported in the
26988 		 * MT FUJI vendor spec. Most equipment is adhereing to MT FUJI
26989 		 * therefore the command is still implemented in this routine.
26990 		 */
26991 		bzero(cdb, sizeof (cdb));
26992 		cdb[0] = (char)SCMD_SET_CDROM_SPEED;
26993 		cdb[2] = (uchar_t)(current_speed >> 8);
26994 		cdb[3] = (uchar_t)current_speed;
26995 		com = kmem_zalloc(sizeof (*com), KM_SLEEP);
26996 		com->uscsi_cdb	   = (caddr_t)cdb;
26997 		com->uscsi_cdblen  = CDB_GROUP5;
26998 		com->uscsi_bufaddr = NULL;
26999 		com->uscsi_buflen  = 0;
27000 		com->uscsi_flags   = USCSI_DIAGNOSE|USCSI_SILENT;
27001 		rval = sd_send_scsi_cmd(dev, com, FKIOCTL, 0, SD_PATH_STANDARD);
27002 		break;
27003 	default:
27004 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
27005 		    "sr_atapi_change_speed: Command '%x' Not Supported\n", cmd);
27006 		rval = EINVAL;
27007 	}
27008 
27009 	if (sense) {
27010 		kmem_free(sense, BUFLEN_MODE_CDROM_CAP);
27011 	}
27012 	if (com) {
27013 		kmem_free(com, sizeof (*com));
27014 	}
27015 	return (rval);
27016 }
27017 
27018 
27019 /*
27020  *    Function: sr_pause_resume()
27021  *
27022  * Description: This routine is the driver entry point for handling CD-ROM
27023  *		pause/resume ioctl requests. This only affects the audio play
27024  *		operation.
27025  *
27026  *   Arguments: dev - the device 'dev_t'
27027  *		cmd - the request type; one of CDROMPAUSE or CDROMRESUME, used
27028  *		      for setting the resume bit of the cdb.
27029  *
27030  * Return Code: the code returned by sd_send_scsi_cmd()
27031  *		EINVAL if invalid mode specified
27032  *
27033  */
27034 
27035 static int
27036 sr_pause_resume(dev_t dev, int cmd)
27037 {
27038 	struct sd_lun		*un;
27039 	struct uscsi_cmd	*com;
27040 	char			cdb[CDB_GROUP1];
27041 	int			rval;
27042 
27043 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
27044 		return (ENXIO);
27045 	}
27046 
27047 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
27048 	bzero(cdb, CDB_GROUP1);
27049 	cdb[0] = SCMD_PAUSE_RESUME;
27050 	switch (cmd) {
27051 	case CDROMRESUME:
27052 		cdb[8] = 1;
27053 		break;
27054 	case CDROMPAUSE:
27055 		cdb[8] = 0;
27056 		break;
27057 	default:
27058 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN, "sr_pause_resume:"
27059 		    " Command '%x' Not Supported\n", cmd);
27060 		rval = EINVAL;
27061 		goto done;
27062 	}
27063 
27064 	com->uscsi_cdb    = cdb;
27065 	com->uscsi_cdblen = CDB_GROUP1;
27066 	com->uscsi_flags  = USCSI_DIAGNOSE|USCSI_SILENT;
27067 
27068 	rval = sd_send_scsi_cmd(dev, com, FKIOCTL, UIO_SYSSPACE,
27069 	    SD_PATH_STANDARD);
27070 
27071 done:
27072 	kmem_free(com, sizeof (*com));
27073 	return (rval);
27074 }
27075 
27076 
27077 /*
27078  *    Function: sr_play_msf()
27079  *
27080  * Description: This routine is the driver entry point for handling CD-ROM
27081  *		ioctl requests to output the audio signals at the specified
27082  *		starting address and continue the audio play until the specified
27083  *		ending address (CDROMPLAYMSF) The address is in Minute Second
27084  *		Frame (MSF) format.
27085  *
27086  *   Arguments: dev	- the device 'dev_t'
27087  *		data	- pointer to user provided audio msf structure,
27088  *		          specifying start/end addresses.
27089  *		flag	- this argument is a pass through to ddi_copyxxx()
27090  *		          directly from the mode argument of ioctl().
27091  *
27092  * Return Code: the code returned by sd_send_scsi_cmd()
27093  *		EFAULT if ddi_copyxxx() fails
27094  *		ENXIO if fail ddi_get_soft_state
27095  *		EINVAL if data pointer is NULL
27096  */
27097 
27098 static int
27099 sr_play_msf(dev_t dev, caddr_t data, int flag)
27100 {
27101 	struct sd_lun		*un;
27102 	struct uscsi_cmd	*com;
27103 	struct cdrom_msf	msf_struct;
27104 	struct cdrom_msf	*msf = &msf_struct;
27105 	char			cdb[CDB_GROUP1];
27106 	int			rval;
27107 
27108 	if (data == NULL) {
27109 		return (EINVAL);
27110 	}
27111 
27112 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
27113 		return (ENXIO);
27114 	}
27115 
27116 	if (ddi_copyin(data, msf, sizeof (struct cdrom_msf), flag)) {
27117 		return (EFAULT);
27118 	}
27119 
27120 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
27121 	bzero(cdb, CDB_GROUP1);
27122 	cdb[0] = SCMD_PLAYAUDIO_MSF;
27123 	if (un->un_f_cfg_playmsf_bcd == TRUE) {
27124 		cdb[3] = BYTE_TO_BCD(msf->cdmsf_min0);
27125 		cdb[4] = BYTE_TO_BCD(msf->cdmsf_sec0);
27126 		cdb[5] = BYTE_TO_BCD(msf->cdmsf_frame0);
27127 		cdb[6] = BYTE_TO_BCD(msf->cdmsf_min1);
27128 		cdb[7] = BYTE_TO_BCD(msf->cdmsf_sec1);
27129 		cdb[8] = BYTE_TO_BCD(msf->cdmsf_frame1);
27130 	} else {
27131 		cdb[3] = msf->cdmsf_min0;
27132 		cdb[4] = msf->cdmsf_sec0;
27133 		cdb[5] = msf->cdmsf_frame0;
27134 		cdb[6] = msf->cdmsf_min1;
27135 		cdb[7] = msf->cdmsf_sec1;
27136 		cdb[8] = msf->cdmsf_frame1;
27137 	}
27138 	com->uscsi_cdb    = cdb;
27139 	com->uscsi_cdblen = CDB_GROUP1;
27140 	com->uscsi_flags  = USCSI_DIAGNOSE|USCSI_SILENT;
27141 	rval = sd_send_scsi_cmd(dev, com, FKIOCTL, UIO_SYSSPACE,
27142 	    SD_PATH_STANDARD);
27143 	kmem_free(com, sizeof (*com));
27144 	return (rval);
27145 }
27146 
27147 
27148 /*
27149  *    Function: sr_play_trkind()
27150  *
27151  * Description: This routine is the driver entry point for handling CD-ROM
27152  *		ioctl requests to output the audio signals at the specified
27153  *		starting address and continue the audio play until the specified
27154  *		ending address (CDROMPLAYTRKIND). The address is in Track Index
27155  *		format.
27156  *
27157  *   Arguments: dev	- the device 'dev_t'
27158  *		data	- pointer to user provided audio track/index structure,
27159  *		          specifying start/end addresses.
27160  *		flag	- this argument is a pass through to ddi_copyxxx()
27161  *		          directly from the mode argument of ioctl().
27162  *
27163  * Return Code: the code returned by sd_send_scsi_cmd()
27164  *		EFAULT if ddi_copyxxx() fails
27165  *		ENXIO if fail ddi_get_soft_state
27166  *		EINVAL if data pointer is NULL
27167  */
27168 
27169 static int
27170 sr_play_trkind(dev_t dev, caddr_t data, int flag)
27171 {
27172 	struct cdrom_ti		ti_struct;
27173 	struct cdrom_ti		*ti = &ti_struct;
27174 	struct uscsi_cmd	*com = NULL;
27175 	char			cdb[CDB_GROUP1];
27176 	int			rval;
27177 
27178 	if (data == NULL) {
27179 		return (EINVAL);
27180 	}
27181 
27182 	if (ddi_copyin(data, ti, sizeof (struct cdrom_ti), flag)) {
27183 		return (EFAULT);
27184 	}
27185 
27186 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
27187 	bzero(cdb, CDB_GROUP1);
27188 	cdb[0] = SCMD_PLAYAUDIO_TI;
27189 	cdb[4] = ti->cdti_trk0;
27190 	cdb[5] = ti->cdti_ind0;
27191 	cdb[7] = ti->cdti_trk1;
27192 	cdb[8] = ti->cdti_ind1;
27193 	com->uscsi_cdb    = cdb;
27194 	com->uscsi_cdblen = CDB_GROUP1;
27195 	com->uscsi_flags  = USCSI_DIAGNOSE|USCSI_SILENT;
27196 	rval = sd_send_scsi_cmd(dev, com, FKIOCTL, UIO_SYSSPACE,
27197 	    SD_PATH_STANDARD);
27198 	kmem_free(com, sizeof (*com));
27199 	return (rval);
27200 }
27201 
27202 
27203 /*
27204  *    Function: sr_read_all_subcodes()
27205  *
27206  * Description: This routine is the driver entry point for handling CD-ROM
27207  *		ioctl requests to return raw subcode data while the target is
27208  *		playing audio (CDROMSUBCODE).
27209  *
27210  *   Arguments: dev	- the device 'dev_t'
27211  *		data	- pointer to user provided cdrom subcode structure,
27212  *		          specifying the transfer length and address.
27213  *		flag	- this argument is a pass through to ddi_copyxxx()
27214  *		          directly from the mode argument of ioctl().
27215  *
27216  * Return Code: the code returned by sd_send_scsi_cmd()
27217  *		EFAULT if ddi_copyxxx() fails
27218  *		ENXIO if fail ddi_get_soft_state
27219  *		EINVAL if data pointer is NULL
27220  */
27221 
27222 static int
27223 sr_read_all_subcodes(dev_t dev, caddr_t data, int flag)
27224 {
27225 	struct sd_lun		*un = NULL;
27226 	struct uscsi_cmd	*com = NULL;
27227 	struct cdrom_subcode	*subcode = NULL;
27228 	int			rval;
27229 	size_t			buflen;
27230 	char			cdb[CDB_GROUP5];
27231 
27232 #ifdef _MULTI_DATAMODEL
27233 	/* To support ILP32 applications in an LP64 world */
27234 	struct cdrom_subcode32		cdrom_subcode32;
27235 	struct cdrom_subcode32		*cdsc32 = &cdrom_subcode32;
27236 #endif
27237 	if (data == NULL) {
27238 		return (EINVAL);
27239 	}
27240 
27241 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
27242 		return (ENXIO);
27243 	}
27244 
27245 	subcode = kmem_zalloc(sizeof (struct cdrom_subcode), KM_SLEEP);
27246 
27247 #ifdef _MULTI_DATAMODEL
27248 	switch (ddi_model_convert_from(flag & FMODELS)) {
27249 	case DDI_MODEL_ILP32:
27250 		if (ddi_copyin(data, cdsc32, sizeof (*cdsc32), flag)) {
27251 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
27252 			    "sr_read_all_subcodes: ddi_copyin Failed\n");
27253 			kmem_free(subcode, sizeof (struct cdrom_subcode));
27254 			return (EFAULT);
27255 		}
27256 		/* Convert the ILP32 uscsi data from the application to LP64 */
27257 		cdrom_subcode32tocdrom_subcode(cdsc32, subcode);
27258 		break;
27259 	case DDI_MODEL_NONE:
27260 		if (ddi_copyin(data, subcode,
27261 		    sizeof (struct cdrom_subcode), flag)) {
27262 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
27263 			    "sr_read_all_subcodes: ddi_copyin Failed\n");
27264 			kmem_free(subcode, sizeof (struct cdrom_subcode));
27265 			return (EFAULT);
27266 		}
27267 		break;
27268 	}
27269 #else /* ! _MULTI_DATAMODEL */
27270 	if (ddi_copyin(data, subcode, sizeof (struct cdrom_subcode), flag)) {
27271 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
27272 		    "sr_read_all_subcodes: ddi_copyin Failed\n");
27273 		kmem_free(subcode, sizeof (struct cdrom_subcode));
27274 		return (EFAULT);
27275 	}
27276 #endif /* _MULTI_DATAMODEL */
27277 
27278 	/*
27279 	 * Since MMC-2 expects max 3 bytes for length, check if the
27280 	 * length input is greater than 3 bytes
27281 	 */
27282 	if ((subcode->cdsc_length & 0xFF000000) != 0) {
27283 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
27284 		    "sr_read_all_subcodes: "
27285 		    "cdrom transfer length too large: %d (limit %d)\n",
27286 		    subcode->cdsc_length, 0xFFFFFF);
27287 		kmem_free(subcode, sizeof (struct cdrom_subcode));
27288 		return (EINVAL);
27289 	}
27290 
27291 	buflen = CDROM_BLK_SUBCODE * subcode->cdsc_length;
27292 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
27293 	bzero(cdb, CDB_GROUP5);
27294 
27295 	if (un->un_f_mmc_cap == TRUE) {
27296 		cdb[0] = (char)SCMD_READ_CD;
27297 		cdb[2] = (char)0xff;
27298 		cdb[3] = (char)0xff;
27299 		cdb[4] = (char)0xff;
27300 		cdb[5] = (char)0xff;
27301 		cdb[6] = (((subcode->cdsc_length) & 0x00ff0000) >> 16);
27302 		cdb[7] = (((subcode->cdsc_length) & 0x0000ff00) >> 8);
27303 		cdb[8] = ((subcode->cdsc_length) & 0x000000ff);
27304 		cdb[10] = 1;
27305 	} else {
27306 		/*
27307 		 * Note: A vendor specific command (0xDF) is being used her to
27308 		 * request a read of all subcodes.
27309 		 */
27310 		cdb[0] = (char)SCMD_READ_ALL_SUBCODES;
27311 		cdb[6] = (((subcode->cdsc_length) & 0xff000000) >> 24);
27312 		cdb[7] = (((subcode->cdsc_length) & 0x00ff0000) >> 16);
27313 		cdb[8] = (((subcode->cdsc_length) & 0x0000ff00) >> 8);
27314 		cdb[9] = ((subcode->cdsc_length) & 0x000000ff);
27315 	}
27316 	com->uscsi_cdb	   = cdb;
27317 	com->uscsi_cdblen  = CDB_GROUP5;
27318 	com->uscsi_bufaddr = (caddr_t)subcode->cdsc_addr;
27319 	com->uscsi_buflen  = buflen;
27320 	com->uscsi_flags   = USCSI_DIAGNOSE|USCSI_SILENT|USCSI_READ;
27321 	rval = sd_send_scsi_cmd(dev, com, FKIOCTL, UIO_USERSPACE,
27322 	    SD_PATH_STANDARD);
27323 	kmem_free(subcode, sizeof (struct cdrom_subcode));
27324 	kmem_free(com, sizeof (*com));
27325 	return (rval);
27326 }
27327 
27328 
27329 /*
27330  *    Function: sr_read_subchannel()
27331  *
27332  * Description: This routine is the driver entry point for handling CD-ROM
27333  *		ioctl requests to return the Q sub-channel data of the CD
27334  *		current position block. (CDROMSUBCHNL) The data includes the
27335  *		track number, index number, absolute CD-ROM address (LBA or MSF
27336  *		format per the user) , track relative CD-ROM address (LBA or MSF
27337  *		format per the user), control data and audio status.
27338  *
27339  *   Arguments: dev	- the device 'dev_t'
27340  *		data	- pointer to user provided cdrom sub-channel structure
27341  *		flag	- this argument is a pass through to ddi_copyxxx()
27342  *		          directly from the mode argument of ioctl().
27343  *
27344  * Return Code: the code returned by sd_send_scsi_cmd()
27345  *		EFAULT if ddi_copyxxx() fails
27346  *		ENXIO if fail ddi_get_soft_state
27347  *		EINVAL if data pointer is NULL
27348  */
27349 
27350 static int
27351 sr_read_subchannel(dev_t dev, caddr_t data, int flag)
27352 {
27353 	struct sd_lun		*un;
27354 	struct uscsi_cmd	*com;
27355 	struct cdrom_subchnl	subchanel;
27356 	struct cdrom_subchnl	*subchnl = &subchanel;
27357 	char			cdb[CDB_GROUP1];
27358 	caddr_t			buffer;
27359 	int			rval;
27360 
27361 	if (data == NULL) {
27362 		return (EINVAL);
27363 	}
27364 
27365 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL ||
27366 	    (un->un_state == SD_STATE_OFFLINE)) {
27367 		return (ENXIO);
27368 	}
27369 
27370 	if (ddi_copyin(data, subchnl, sizeof (struct cdrom_subchnl), flag)) {
27371 		return (EFAULT);
27372 	}
27373 
27374 	buffer = kmem_zalloc((size_t)16, KM_SLEEP);
27375 	bzero(cdb, CDB_GROUP1);
27376 	cdb[0] = SCMD_READ_SUBCHANNEL;
27377 	/* Set the MSF bit based on the user requested address format */
27378 	cdb[1] = (subchnl->cdsc_format & CDROM_LBA) ? 0 : 0x02;
27379 	/*
27380 	 * Set the Q bit in byte 2 to indicate that Q sub-channel data be
27381 	 * returned
27382 	 */
27383 	cdb[2] = 0x40;
27384 	/*
27385 	 * Set byte 3 to specify the return data format. A value of 0x01
27386 	 * indicates that the CD-ROM current position should be returned.
27387 	 */
27388 	cdb[3] = 0x01;
27389 	cdb[8] = 0x10;
27390 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
27391 	com->uscsi_cdb	   = cdb;
27392 	com->uscsi_cdblen  = CDB_GROUP1;
27393 	com->uscsi_bufaddr = buffer;
27394 	com->uscsi_buflen  = 16;
27395 	com->uscsi_flags   = USCSI_DIAGNOSE|USCSI_SILENT|USCSI_READ;
27396 	rval = sd_send_scsi_cmd(dev, com, FKIOCTL, UIO_SYSSPACE,
27397 	    SD_PATH_STANDARD);
27398 	if (rval != 0) {
27399 		kmem_free(buffer, 16);
27400 		kmem_free(com, sizeof (*com));
27401 		return (rval);
27402 	}
27403 
27404 	/* Process the returned Q sub-channel data */
27405 	subchnl->cdsc_audiostatus = buffer[1];
27406 	subchnl->cdsc_adr	= (buffer[5] & 0xF0);
27407 	subchnl->cdsc_ctrl	= (buffer[5] & 0x0F);
27408 	subchnl->cdsc_trk	= buffer[6];
27409 	subchnl->cdsc_ind	= buffer[7];
27410 	if (subchnl->cdsc_format & CDROM_LBA) {
27411 		subchnl->cdsc_absaddr.lba =
27412 		    ((uchar_t)buffer[8] << 24) + ((uchar_t)buffer[9] << 16) +
27413 		    ((uchar_t)buffer[10] << 8) + ((uchar_t)buffer[11]);
27414 		subchnl->cdsc_reladdr.lba =
27415 		    ((uchar_t)buffer[12] << 24) + ((uchar_t)buffer[13] << 16) +
27416 		    ((uchar_t)buffer[14] << 8) + ((uchar_t)buffer[15]);
27417 	} else if (un->un_f_cfg_readsub_bcd == TRUE) {
27418 		subchnl->cdsc_absaddr.msf.minute = BCD_TO_BYTE(buffer[9]);
27419 		subchnl->cdsc_absaddr.msf.second = BCD_TO_BYTE(buffer[10]);
27420 		subchnl->cdsc_absaddr.msf.frame  = BCD_TO_BYTE(buffer[11]);
27421 		subchnl->cdsc_reladdr.msf.minute = BCD_TO_BYTE(buffer[13]);
27422 		subchnl->cdsc_reladdr.msf.second = BCD_TO_BYTE(buffer[14]);
27423 		subchnl->cdsc_reladdr.msf.frame  = BCD_TO_BYTE(buffer[15]);
27424 	} else {
27425 		subchnl->cdsc_absaddr.msf.minute = buffer[9];
27426 		subchnl->cdsc_absaddr.msf.second = buffer[10];
27427 		subchnl->cdsc_absaddr.msf.frame  = buffer[11];
27428 		subchnl->cdsc_reladdr.msf.minute = buffer[13];
27429 		subchnl->cdsc_reladdr.msf.second = buffer[14];
27430 		subchnl->cdsc_reladdr.msf.frame  = buffer[15];
27431 	}
27432 	kmem_free(buffer, 16);
27433 	kmem_free(com, sizeof (*com));
27434 	if (ddi_copyout(subchnl, data, sizeof (struct cdrom_subchnl), flag)
27435 	    != 0) {
27436 		return (EFAULT);
27437 	}
27438 	return (rval);
27439 }
27440 
27441 
27442 /*
27443  *    Function: sr_read_tocentry()
27444  *
27445  * Description: This routine is the driver entry point for handling CD-ROM
27446  *		ioctl requests to read from the Table of Contents (TOC)
27447  *		(CDROMREADTOCENTRY). This routine provides the ADR and CTRL
27448  *		fields, the starting address (LBA or MSF format per the user)
27449  *		and the data mode if the user specified track is a data track.
27450  *
27451  *		Note: The READ HEADER (0x44) command used in this routine is
27452  *		obsolete per the SCSI MMC spec but still supported in the
27453  *		MT FUJI vendor spec. Most equipment is adhereing to MT FUJI
27454  *		therefore the command is still implemented in this routine.
27455  *
27456  *   Arguments: dev	- the device 'dev_t'
27457  *		data	- pointer to user provided toc entry structure,
27458  *			  specifying the track # and the address format
27459  *			  (LBA or MSF).
27460  *		flag	- this argument is a pass through to ddi_copyxxx()
27461  *		          directly from the mode argument of ioctl().
27462  *
27463  * Return Code: the code returned by sd_send_scsi_cmd()
27464  *		EFAULT if ddi_copyxxx() fails
27465  *		ENXIO if fail ddi_get_soft_state
27466  *		EINVAL if data pointer is NULL
27467  */
27468 
27469 static int
27470 sr_read_tocentry(dev_t dev, caddr_t data, int flag)
27471 {
27472 	struct sd_lun		*un = NULL;
27473 	struct uscsi_cmd	*com;
27474 	struct cdrom_tocentry	toc_entry;
27475 	struct cdrom_tocentry	*entry = &toc_entry;
27476 	caddr_t			buffer;
27477 	int			rval;
27478 	char			cdb[CDB_GROUP1];
27479 
27480 	if (data == NULL) {
27481 		return (EINVAL);
27482 	}
27483 
27484 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL ||
27485 	    (un->un_state == SD_STATE_OFFLINE)) {
27486 		return (ENXIO);
27487 	}
27488 
27489 	if (ddi_copyin(data, entry, sizeof (struct cdrom_tocentry), flag)) {
27490 		return (EFAULT);
27491 	}
27492 
27493 	/* Validate the requested track and address format */
27494 	if (!(entry->cdte_format & (CDROM_LBA | CDROM_MSF))) {
27495 		return (EINVAL);
27496 	}
27497 
27498 	if (entry->cdte_track == 0) {
27499 		return (EINVAL);
27500 	}
27501 
27502 	buffer = kmem_zalloc((size_t)12, KM_SLEEP);
27503 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
27504 	bzero(cdb, CDB_GROUP1);
27505 
27506 	cdb[0] = SCMD_READ_TOC;
27507 	/* Set the MSF bit based on the user requested address format  */
27508 	cdb[1] = ((entry->cdte_format & CDROM_LBA) ? 0 : 2);
27509 	if (un->un_f_cfg_read_toc_trk_bcd == TRUE) {
27510 		cdb[6] = BYTE_TO_BCD(entry->cdte_track);
27511 	} else {
27512 		cdb[6] = entry->cdte_track;
27513 	}
27514 
27515 	/*
27516 	 * Bytes 7 & 8 are the 12 byte allocation length for a single entry.
27517 	 * (4 byte TOC response header + 8 byte track descriptor)
27518 	 */
27519 	cdb[8] = 12;
27520 	com->uscsi_cdb	   = cdb;
27521 	com->uscsi_cdblen  = CDB_GROUP1;
27522 	com->uscsi_bufaddr = buffer;
27523 	com->uscsi_buflen  = 0x0C;
27524 	com->uscsi_flags   = (USCSI_DIAGNOSE | USCSI_SILENT | USCSI_READ);
27525 	rval = sd_send_scsi_cmd(dev, com, FKIOCTL, UIO_SYSSPACE,
27526 	    SD_PATH_STANDARD);
27527 	if (rval != 0) {
27528 		kmem_free(buffer, 12);
27529 		kmem_free(com, sizeof (*com));
27530 		return (rval);
27531 	}
27532 
27533 	/* Process the toc entry */
27534 	entry->cdte_adr		= (buffer[5] & 0xF0) >> 4;
27535 	entry->cdte_ctrl	= (buffer[5] & 0x0F);
27536 	if (entry->cdte_format & CDROM_LBA) {
27537 		entry->cdte_addr.lba =
27538 		    ((uchar_t)buffer[8] << 24) + ((uchar_t)buffer[9] << 16) +
27539 		    ((uchar_t)buffer[10] << 8) + ((uchar_t)buffer[11]);
27540 	} else if (un->un_f_cfg_read_toc_addr_bcd == TRUE) {
27541 		entry->cdte_addr.msf.minute	= BCD_TO_BYTE(buffer[9]);
27542 		entry->cdte_addr.msf.second	= BCD_TO_BYTE(buffer[10]);
27543 		entry->cdte_addr.msf.frame	= BCD_TO_BYTE(buffer[11]);
27544 		/*
27545 		 * Send a READ TOC command using the LBA address format to get
27546 		 * the LBA for the track requested so it can be used in the
27547 		 * READ HEADER request
27548 		 *
27549 		 * Note: The MSF bit of the READ HEADER command specifies the
27550 		 * output format. The block address specified in that command
27551 		 * must be in LBA format.
27552 		 */
27553 		cdb[1] = 0;
27554 		rval = sd_send_scsi_cmd(dev, com, FKIOCTL, UIO_SYSSPACE,
27555 		    SD_PATH_STANDARD);
27556 		if (rval != 0) {
27557 			kmem_free(buffer, 12);
27558 			kmem_free(com, sizeof (*com));
27559 			return (rval);
27560 		}
27561 	} else {
27562 		entry->cdte_addr.msf.minute	= buffer[9];
27563 		entry->cdte_addr.msf.second	= buffer[10];
27564 		entry->cdte_addr.msf.frame	= buffer[11];
27565 		/*
27566 		 * Send a READ TOC command using the LBA address format to get
27567 		 * the LBA for the track requested so it can be used in the
27568 		 * READ HEADER request
27569 		 *
27570 		 * Note: The MSF bit of the READ HEADER command specifies the
27571 		 * output format. The block address specified in that command
27572 		 * must be in LBA format.
27573 		 */
27574 		cdb[1] = 0;
27575 		rval = sd_send_scsi_cmd(dev, com, FKIOCTL, UIO_SYSSPACE,
27576 		    SD_PATH_STANDARD);
27577 		if (rval != 0) {
27578 			kmem_free(buffer, 12);
27579 			kmem_free(com, sizeof (*com));
27580 			return (rval);
27581 		}
27582 	}
27583 
27584 	/*
27585 	 * Build and send the READ HEADER command to determine the data mode of
27586 	 * the user specified track.
27587 	 */
27588 	if ((entry->cdte_ctrl & CDROM_DATA_TRACK) &&
27589 	    (entry->cdte_track != CDROM_LEADOUT)) {
27590 		bzero(cdb, CDB_GROUP1);
27591 		cdb[0] = SCMD_READ_HEADER;
27592 		cdb[2] = buffer[8];
27593 		cdb[3] = buffer[9];
27594 		cdb[4] = buffer[10];
27595 		cdb[5] = buffer[11];
27596 		cdb[8] = 0x08;
27597 		com->uscsi_buflen = 0x08;
27598 		rval = sd_send_scsi_cmd(dev, com, FKIOCTL, UIO_SYSSPACE,
27599 		    SD_PATH_STANDARD);
27600 		if (rval == 0) {
27601 			entry->cdte_datamode = buffer[0];
27602 		} else {
27603 			/*
27604 			 * READ HEADER command failed, since this is
27605 			 * obsoleted in one spec, its better to return
27606 			 * -1 for an invlid track so that we can still
27607 			 * receive the rest of the TOC data.
27608 			 */
27609 			entry->cdte_datamode = (uchar_t)-1;
27610 		}
27611 	} else {
27612 		entry->cdte_datamode = (uchar_t)-1;
27613 	}
27614 
27615 	kmem_free(buffer, 12);
27616 	kmem_free(com, sizeof (*com));
27617 	if (ddi_copyout(entry, data, sizeof (struct cdrom_tocentry), flag) != 0)
27618 		return (EFAULT);
27619 
27620 	return (rval);
27621 }
27622 
27623 
27624 /*
27625  *    Function: sr_read_tochdr()
27626  *
27627  * Description: This routine is the driver entry point for handling CD-ROM
27628  * 		ioctl requests to read the Table of Contents (TOC) header
27629  *		(CDROMREADTOHDR). The TOC header consists of the disk starting
27630  *		and ending track numbers
27631  *
27632  *   Arguments: dev	- the device 'dev_t'
27633  *		data	- pointer to user provided toc header structure,
27634  *			  specifying the starting and ending track numbers.
27635  *		flag	- this argument is a pass through to ddi_copyxxx()
27636  *			  directly from the mode argument of ioctl().
27637  *
27638  * Return Code: the code returned by sd_send_scsi_cmd()
27639  *		EFAULT if ddi_copyxxx() fails
27640  *		ENXIO if fail ddi_get_soft_state
27641  *		EINVAL if data pointer is NULL
27642  */
27643 
27644 static int
27645 sr_read_tochdr(dev_t dev, caddr_t data, int flag)
27646 {
27647 	struct sd_lun		*un;
27648 	struct uscsi_cmd	*com;
27649 	struct cdrom_tochdr	toc_header;
27650 	struct cdrom_tochdr	*hdr = &toc_header;
27651 	char			cdb[CDB_GROUP1];
27652 	int			rval;
27653 	caddr_t			buffer;
27654 
27655 	if (data == NULL) {
27656 		return (EINVAL);
27657 	}
27658 
27659 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL ||
27660 	    (un->un_state == SD_STATE_OFFLINE)) {
27661 		return (ENXIO);
27662 	}
27663 
27664 	buffer = kmem_zalloc(4, KM_SLEEP);
27665 	bzero(cdb, CDB_GROUP1);
27666 	cdb[0] = SCMD_READ_TOC;
27667 	/*
27668 	 * Specifying a track number of 0x00 in the READ TOC command indicates
27669 	 * that the TOC header should be returned
27670 	 */
27671 	cdb[6] = 0x00;
27672 	/*
27673 	 * Bytes 7 & 8 are the 4 byte allocation length for TOC header.
27674 	 * (2 byte data len + 1 byte starting track # + 1 byte ending track #)
27675 	 */
27676 	cdb[8] = 0x04;
27677 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
27678 	com->uscsi_cdb	   = cdb;
27679 	com->uscsi_cdblen  = CDB_GROUP1;
27680 	com->uscsi_bufaddr = buffer;
27681 	com->uscsi_buflen  = 0x04;
27682 	com->uscsi_timeout = 300;
27683 	com->uscsi_flags   = USCSI_DIAGNOSE|USCSI_SILENT|USCSI_READ;
27684 
27685 	rval = sd_send_scsi_cmd(dev, com, FKIOCTL, UIO_SYSSPACE,
27686 	    SD_PATH_STANDARD);
27687 	if (un->un_f_cfg_read_toc_trk_bcd == TRUE) {
27688 		hdr->cdth_trk0 = BCD_TO_BYTE(buffer[2]);
27689 		hdr->cdth_trk1 = BCD_TO_BYTE(buffer[3]);
27690 	} else {
27691 		hdr->cdth_trk0 = buffer[2];
27692 		hdr->cdth_trk1 = buffer[3];
27693 	}
27694 	kmem_free(buffer, 4);
27695 	kmem_free(com, sizeof (*com));
27696 	if (ddi_copyout(hdr, data, sizeof (struct cdrom_tochdr), flag) != 0) {
27697 		return (EFAULT);
27698 	}
27699 	return (rval);
27700 }
27701 
27702 
27703 /*
27704  * Note: The following sr_read_mode1(), sr_read_cd_mode2(), sr_read_mode2(),
27705  * sr_read_cdda(), sr_read_cdxa(), routines implement driver support for
27706  * handling CDROMREAD ioctl requests for mode 1 user data, mode 2 user data,
27707  * digital audio and extended architecture digital audio. These modes are
27708  * defined in the IEC908 (Red Book), ISO10149 (Yellow Book), and the SCSI3
27709  * MMC specs.
27710  *
27711  * In addition to support for the various data formats these routines also
27712  * include support for devices that implement only the direct access READ
27713  * commands (0x08, 0x28), devices that implement the READ_CD commands
27714  * (0xBE, 0xD4), and devices that implement the vendor unique READ CDDA and
27715  * READ CDXA commands (0xD8, 0xDB)
27716  */
27717 
27718 /*
27719  *    Function: sr_read_mode1()
27720  *
27721  * Description: This routine is the driver entry point for handling CD-ROM
27722  *		ioctl read mode1 requests (CDROMREADMODE1).
27723  *
27724  *   Arguments: dev	- the device 'dev_t'
27725  *		data	- pointer to user provided cd read structure specifying
27726  *			  the lba buffer address and length.
27727  *		flag	- this argument is a pass through to ddi_copyxxx()
27728  *			  directly from the mode argument of ioctl().
27729  *
27730  * Return Code: the code returned by sd_send_scsi_cmd()
27731  *		EFAULT if ddi_copyxxx() fails
27732  *		ENXIO if fail ddi_get_soft_state
27733  *		EINVAL if data pointer is NULL
27734  */
27735 
27736 static int
27737 sr_read_mode1(dev_t dev, caddr_t data, int flag)
27738 {
27739 	struct sd_lun		*un;
27740 	struct cdrom_read	mode1_struct;
27741 	struct cdrom_read	*mode1 = &mode1_struct;
27742 	int			rval;
27743 	sd_ssc_t		*ssc;
27744 
27745 #ifdef _MULTI_DATAMODEL
27746 	/* To support ILP32 applications in an LP64 world */
27747 	struct cdrom_read32	cdrom_read32;
27748 	struct cdrom_read32	*cdrd32 = &cdrom_read32;
27749 #endif /* _MULTI_DATAMODEL */
27750 
27751 	if (data == NULL) {
27752 		return (EINVAL);
27753 	}
27754 
27755 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL ||
27756 	    (un->un_state == SD_STATE_OFFLINE)) {
27757 		return (ENXIO);
27758 	}
27759 
27760 	SD_TRACE(SD_LOG_ATTACH_DETACH, un,
27761 	    "sd_read_mode1: entry: un:0x%p\n", un);
27762 
27763 #ifdef _MULTI_DATAMODEL
27764 	switch (ddi_model_convert_from(flag & FMODELS)) {
27765 	case DDI_MODEL_ILP32:
27766 		if (ddi_copyin(data, cdrd32, sizeof (*cdrd32), flag) != 0) {
27767 			return (EFAULT);
27768 		}
27769 		/* Convert the ILP32 uscsi data from the application to LP64 */
27770 		cdrom_read32tocdrom_read(cdrd32, mode1);
27771 		break;
27772 	case DDI_MODEL_NONE:
27773 		if (ddi_copyin(data, mode1, sizeof (struct cdrom_read), flag)) {
27774 			return (EFAULT);
27775 		}
27776 	}
27777 #else /* ! _MULTI_DATAMODEL */
27778 	if (ddi_copyin(data, mode1, sizeof (struct cdrom_read), flag)) {
27779 		return (EFAULT);
27780 	}
27781 #endif /* _MULTI_DATAMODEL */
27782 
27783 	ssc = sd_ssc_init(un);
27784 	rval = sd_send_scsi_READ(ssc, mode1->cdread_bufaddr,
27785 	    mode1->cdread_buflen, mode1->cdread_lba, SD_PATH_STANDARD);
27786 	sd_ssc_fini(ssc);
27787 
27788 	SD_TRACE(SD_LOG_ATTACH_DETACH, un,
27789 	    "sd_read_mode1: exit: un:0x%p\n", un);
27790 
27791 	return (rval);
27792 }
27793 
27794 
27795 /*
27796  *    Function: sr_read_cd_mode2()
27797  *
27798  * Description: This routine is the driver entry point for handling CD-ROM
27799  *		ioctl read mode2 requests (CDROMREADMODE2) for devices that
27800  *		support the READ CD (0xBE) command or the 1st generation
27801  *		READ CD (0xD4) command.
27802  *
27803  *   Arguments: dev	- the device 'dev_t'
27804  *		data	- pointer to user provided cd read structure specifying
27805  *			  the lba buffer address and length.
27806  *		flag	- this argument is a pass through to ddi_copyxxx()
27807  *			  directly from the mode argument of ioctl().
27808  *
27809  * Return Code: the code returned by sd_send_scsi_cmd()
27810  *		EFAULT if ddi_copyxxx() fails
27811  *		ENXIO if fail ddi_get_soft_state
27812  *		EINVAL if data pointer is NULL
27813  */
27814 
27815 static int
27816 sr_read_cd_mode2(dev_t dev, caddr_t data, int flag)
27817 {
27818 	struct sd_lun		*un;
27819 	struct uscsi_cmd	*com;
27820 	struct cdrom_read	mode2_struct;
27821 	struct cdrom_read	*mode2 = &mode2_struct;
27822 	uchar_t			cdb[CDB_GROUP5];
27823 	int			nblocks;
27824 	int			rval;
27825 #ifdef _MULTI_DATAMODEL
27826 	/*  To support ILP32 applications in an LP64 world */
27827 	struct cdrom_read32	cdrom_read32;
27828 	struct cdrom_read32	*cdrd32 = &cdrom_read32;
27829 #endif /* _MULTI_DATAMODEL */
27830 
27831 	if (data == NULL) {
27832 		return (EINVAL);
27833 	}
27834 
27835 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL ||
27836 	    (un->un_state == SD_STATE_OFFLINE)) {
27837 		return (ENXIO);
27838 	}
27839 
27840 #ifdef _MULTI_DATAMODEL
27841 	switch (ddi_model_convert_from(flag & FMODELS)) {
27842 	case DDI_MODEL_ILP32:
27843 		if (ddi_copyin(data, cdrd32, sizeof (*cdrd32), flag) != 0) {
27844 			return (EFAULT);
27845 		}
27846 		/* Convert the ILP32 uscsi data from the application to LP64 */
27847 		cdrom_read32tocdrom_read(cdrd32, mode2);
27848 		break;
27849 	case DDI_MODEL_NONE:
27850 		if (ddi_copyin(data, mode2, sizeof (*mode2), flag) != 0) {
27851 			return (EFAULT);
27852 		}
27853 		break;
27854 	}
27855 
27856 #else /* ! _MULTI_DATAMODEL */
27857 	if (ddi_copyin(data, mode2, sizeof (*mode2), flag) != 0) {
27858 		return (EFAULT);
27859 	}
27860 #endif /* _MULTI_DATAMODEL */
27861 
27862 	bzero(cdb, sizeof (cdb));
27863 	if (un->un_f_cfg_read_cd_xd4 == TRUE) {
27864 		/* Read command supported by 1st generation atapi drives */
27865 		cdb[0] = SCMD_READ_CDD4;
27866 	} else {
27867 		/* Universal CD Access Command */
27868 		cdb[0] = SCMD_READ_CD;
27869 	}
27870 
27871 	/*
27872 	 * Set expected sector type to: 2336s byte, Mode 2 Yellow Book
27873 	 */
27874 	cdb[1] = CDROM_SECTOR_TYPE_MODE2;
27875 
27876 	/* set the start address */
27877 	cdb[2] = (uchar_t)((mode2->cdread_lba >> 24) & 0XFF);
27878 	cdb[3] = (uchar_t)((mode2->cdread_lba >> 16) & 0XFF);
27879 	cdb[4] = (uchar_t)((mode2->cdread_lba >> 8) & 0xFF);
27880 	cdb[5] = (uchar_t)(mode2->cdread_lba & 0xFF);
27881 
27882 	/* set the transfer length */
27883 	nblocks = mode2->cdread_buflen / 2336;
27884 	cdb[6] = (uchar_t)(nblocks >> 16);
27885 	cdb[7] = (uchar_t)(nblocks >> 8);
27886 	cdb[8] = (uchar_t)nblocks;
27887 
27888 	/* set the filter bits */
27889 	cdb[9] = CDROM_READ_CD_USERDATA;
27890 
27891 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
27892 	com->uscsi_cdb = (caddr_t)cdb;
27893 	com->uscsi_cdblen = sizeof (cdb);
27894 	com->uscsi_bufaddr = mode2->cdread_bufaddr;
27895 	com->uscsi_buflen = mode2->cdread_buflen;
27896 	com->uscsi_flags = USCSI_DIAGNOSE|USCSI_SILENT|USCSI_READ;
27897 
27898 	rval = sd_send_scsi_cmd(dev, com, FKIOCTL, UIO_USERSPACE,
27899 	    SD_PATH_STANDARD);
27900 	kmem_free(com, sizeof (*com));
27901 	return (rval);
27902 }
27903 
27904 
27905 /*
27906  *    Function: sr_read_mode2()
27907  *
27908  * Description: This routine is the driver entry point for handling CD-ROM
27909  *		ioctl read mode2 requests (CDROMREADMODE2) for devices that
27910  *		do not support the READ CD (0xBE) command.
27911  *
27912  *   Arguments: dev	- the device 'dev_t'
27913  *		data	- pointer to user provided cd read structure specifying
27914  *			  the lba buffer address and length.
27915  *		flag	- this argument is a pass through to ddi_copyxxx()
27916  *			  directly from the mode argument of ioctl().
27917  *
27918  * Return Code: the code returned by sd_send_scsi_cmd()
27919  *		EFAULT if ddi_copyxxx() fails
27920  *		ENXIO if fail ddi_get_soft_state
27921  *		EINVAL if data pointer is NULL
27922  *		EIO if fail to reset block size
27923  *		EAGAIN if commands are in progress in the driver
27924  */
27925 
27926 static int
27927 sr_read_mode2(dev_t dev, caddr_t data, int flag)
27928 {
27929 	struct sd_lun		*un;
27930 	struct cdrom_read	mode2_struct;
27931 	struct cdrom_read	*mode2 = &mode2_struct;
27932 	int			rval;
27933 	uint32_t		restore_blksize;
27934 	struct uscsi_cmd	*com;
27935 	uchar_t			cdb[CDB_GROUP0];
27936 	int			nblocks;
27937 
27938 #ifdef _MULTI_DATAMODEL
27939 	/* To support ILP32 applications in an LP64 world */
27940 	struct cdrom_read32	cdrom_read32;
27941 	struct cdrom_read32	*cdrd32 = &cdrom_read32;
27942 #endif /* _MULTI_DATAMODEL */
27943 
27944 	if (data == NULL) {
27945 		return (EINVAL);
27946 	}
27947 
27948 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL ||
27949 	    (un->un_state == SD_STATE_OFFLINE)) {
27950 		return (ENXIO);
27951 	}
27952 
27953 	/*
27954 	 * Because this routine will update the device and driver block size
27955 	 * being used we want to make sure there are no commands in progress.
27956 	 * If commands are in progress the user will have to try again.
27957 	 *
27958 	 * We check for 1 instead of 0 because we increment un_ncmds_in_driver
27959 	 * in sdioctl to protect commands from sdioctl through to the top of
27960 	 * sd_uscsi_strategy. See sdioctl for details.
27961 	 */
27962 	mutex_enter(SD_MUTEX(un));
27963 	if (un->un_ncmds_in_driver != 1) {
27964 		mutex_exit(SD_MUTEX(un));
27965 		return (EAGAIN);
27966 	}
27967 	mutex_exit(SD_MUTEX(un));
27968 
27969 	SD_TRACE(SD_LOG_ATTACH_DETACH, un,
27970 	    "sd_read_mode2: entry: un:0x%p\n", un);
27971 
27972 #ifdef _MULTI_DATAMODEL
27973 	switch (ddi_model_convert_from(flag & FMODELS)) {
27974 	case DDI_MODEL_ILP32:
27975 		if (ddi_copyin(data, cdrd32, sizeof (*cdrd32), flag) != 0) {
27976 			return (EFAULT);
27977 		}
27978 		/* Convert the ILP32 uscsi data from the application to LP64 */
27979 		cdrom_read32tocdrom_read(cdrd32, mode2);
27980 		break;
27981 	case DDI_MODEL_NONE:
27982 		if (ddi_copyin(data, mode2, sizeof (*mode2), flag) != 0) {
27983 			return (EFAULT);
27984 		}
27985 		break;
27986 	}
27987 #else /* ! _MULTI_DATAMODEL */
27988 	if (ddi_copyin(data, mode2, sizeof (*mode2), flag)) {
27989 		return (EFAULT);
27990 	}
27991 #endif /* _MULTI_DATAMODEL */
27992 
27993 	/* Store the current target block size for restoration later */
27994 	restore_blksize = un->un_tgt_blocksize;
27995 
27996 	/* Change the device and soft state target block size to 2336 */
27997 	if (sr_sector_mode(dev, SD_MODE2_BLKSIZE) != 0) {
27998 		rval = EIO;
27999 		goto done;
28000 	}
28001 
28002 
28003 	bzero(cdb, sizeof (cdb));
28004 
28005 	/* set READ operation */
28006 	cdb[0] = SCMD_READ;
28007 
28008 	/* adjust lba for 2kbyte blocks from 512 byte blocks */
28009 	mode2->cdread_lba >>= 2;
28010 
28011 	/* set the start address */
28012 	cdb[1] = (uchar_t)((mode2->cdread_lba >> 16) & 0X1F);
28013 	cdb[2] = (uchar_t)((mode2->cdread_lba >> 8) & 0xFF);
28014 	cdb[3] = (uchar_t)(mode2->cdread_lba & 0xFF);
28015 
28016 	/* set the transfer length */
28017 	nblocks = mode2->cdread_buflen / 2336;
28018 	cdb[4] = (uchar_t)nblocks & 0xFF;
28019 
28020 	/* build command */
28021 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
28022 	com->uscsi_cdb = (caddr_t)cdb;
28023 	com->uscsi_cdblen = sizeof (cdb);
28024 	com->uscsi_bufaddr = mode2->cdread_bufaddr;
28025 	com->uscsi_buflen = mode2->cdread_buflen;
28026 	com->uscsi_flags = USCSI_DIAGNOSE|USCSI_SILENT|USCSI_READ;
28027 
28028 	/*
28029 	 * Issue SCSI command with user space address for read buffer.
28030 	 *
28031 	 * This sends the command through main channel in the driver.
28032 	 *
28033 	 * Since this is accessed via an IOCTL call, we go through the
28034 	 * standard path, so that if the device was powered down, then
28035 	 * it would be 'awakened' to handle the command.
28036 	 */
28037 	rval = sd_send_scsi_cmd(dev, com, FKIOCTL, UIO_USERSPACE,
28038 	    SD_PATH_STANDARD);
28039 
28040 	kmem_free(com, sizeof (*com));
28041 
28042 	/* Restore the device and soft state target block size */
28043 	if (sr_sector_mode(dev, restore_blksize) != 0) {
28044 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
28045 		    "can't do switch back to mode 1\n");
28046 		/*
28047 		 * If sd_send_scsi_READ succeeded we still need to report
28048 		 * an error because we failed to reset the block size
28049 		 */
28050 		if (rval == 0) {
28051 			rval = EIO;
28052 		}
28053 	}
28054 
28055 done:
28056 	SD_TRACE(SD_LOG_ATTACH_DETACH, un,
28057 	    "sd_read_mode2: exit: un:0x%p\n", un);
28058 
28059 	return (rval);
28060 }
28061 
28062 
28063 /*
28064  *    Function: sr_sector_mode()
28065  *
28066  * Description: This utility function is used by sr_read_mode2 to set the target
28067  *		block size based on the user specified size. This is a legacy
28068  *		implementation based upon a vendor specific mode page
28069  *
28070  *   Arguments: dev	- the device 'dev_t'
28071  *		data	- flag indicating if block size is being set to 2336 or
28072  *			  512.
28073  *
28074  * Return Code: the code returned by sd_send_scsi_cmd()
28075  *		EFAULT if ddi_copyxxx() fails
28076  *		ENXIO if fail ddi_get_soft_state
28077  *		EINVAL if data pointer is NULL
28078  */
28079 
28080 static int
28081 sr_sector_mode(dev_t dev, uint32_t blksize)
28082 {
28083 	struct sd_lun	*un;
28084 	uchar_t		*sense;
28085 	uchar_t		*select;
28086 	int		rval;
28087 	sd_ssc_t	*ssc;
28088 
28089 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL ||
28090 	    (un->un_state == SD_STATE_OFFLINE)) {
28091 		return (ENXIO);
28092 	}
28093 
28094 	sense = kmem_zalloc(20, KM_SLEEP);
28095 
28096 	/* Note: This is a vendor specific mode page (0x81) */
28097 	ssc = sd_ssc_init(un);
28098 	rval = sd_send_scsi_MODE_SENSE(ssc, CDB_GROUP0, sense, 20, 0x81,
28099 	    SD_PATH_STANDARD);
28100 	sd_ssc_fini(ssc);
28101 	if (rval != 0) {
28102 		SD_ERROR(SD_LOG_IOCTL_RMMEDIA, un,
28103 		    "sr_sector_mode: Mode Sense failed\n");
28104 		kmem_free(sense, 20);
28105 		return (rval);
28106 	}
28107 	select = kmem_zalloc(20, KM_SLEEP);
28108 	select[3] = 0x08;
28109 	select[10] = ((blksize >> 8) & 0xff);
28110 	select[11] = (blksize & 0xff);
28111 	select[12] = 0x01;
28112 	select[13] = 0x06;
28113 	select[14] = sense[14];
28114 	select[15] = sense[15];
28115 	if (blksize == SD_MODE2_BLKSIZE) {
28116 		select[14] |= 0x01;
28117 	}
28118 
28119 	ssc = sd_ssc_init(un);
28120 	rval = sd_send_scsi_MODE_SELECT(ssc, CDB_GROUP0, select, 20,
28121 	    SD_DONTSAVE_PAGE, SD_PATH_STANDARD);
28122 	sd_ssc_fini(ssc);
28123 	if (rval != 0) {
28124 		SD_ERROR(SD_LOG_IOCTL_RMMEDIA, un,
28125 		    "sr_sector_mode: Mode Select failed\n");
28126 	} else {
28127 		/*
28128 		 * Only update the softstate block size if we successfully
28129 		 * changed the device block mode.
28130 		 */
28131 		mutex_enter(SD_MUTEX(un));
28132 		sd_update_block_info(un, blksize, 0);
28133 		mutex_exit(SD_MUTEX(un));
28134 	}
28135 	kmem_free(sense, 20);
28136 	kmem_free(select, 20);
28137 	return (rval);
28138 }
28139 
28140 
28141 /*
28142  *    Function: sr_read_cdda()
28143  *
28144  * Description: This routine is the driver entry point for handling CD-ROM
28145  *		ioctl requests to return CD-DA or subcode data. (CDROMCDDA) If
28146  *		the target supports CDDA these requests are handled via a vendor
28147  *		specific command (0xD8) If the target does not support CDDA
28148  *		these requests are handled via the READ CD command (0xBE).
28149  *
28150  *   Arguments: dev	- the device 'dev_t'
28151  *		data	- pointer to user provided CD-DA structure specifying
28152  *			  the track starting address, transfer length, and
28153  *			  subcode options.
28154  *		flag	- this argument is a pass through to ddi_copyxxx()
28155  *			  directly from the mode argument of ioctl().
28156  *
28157  * Return Code: the code returned by sd_send_scsi_cmd()
28158  *		EFAULT if ddi_copyxxx() fails
28159  *		ENXIO if fail ddi_get_soft_state
28160  *		EINVAL if invalid arguments are provided
28161  *		ENOTTY
28162  */
28163 
28164 static int
28165 sr_read_cdda(dev_t dev, caddr_t data, int flag)
28166 {
28167 	struct sd_lun			*un;
28168 	struct uscsi_cmd		*com;
28169 	struct cdrom_cdda		*cdda;
28170 	int				rval;
28171 	size_t				buflen;
28172 	char				cdb[CDB_GROUP5];
28173 
28174 #ifdef _MULTI_DATAMODEL
28175 	/* To support ILP32 applications in an LP64 world */
28176 	struct cdrom_cdda32	cdrom_cdda32;
28177 	struct cdrom_cdda32	*cdda32 = &cdrom_cdda32;
28178 #endif /* _MULTI_DATAMODEL */
28179 
28180 	if (data == NULL) {
28181 		return (EINVAL);
28182 	}
28183 
28184 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
28185 		return (ENXIO);
28186 	}
28187 
28188 	cdda = kmem_zalloc(sizeof (struct cdrom_cdda), KM_SLEEP);
28189 
28190 #ifdef _MULTI_DATAMODEL
28191 	switch (ddi_model_convert_from(flag & FMODELS)) {
28192 	case DDI_MODEL_ILP32:
28193 		if (ddi_copyin(data, cdda32, sizeof (*cdda32), flag)) {
28194 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
28195 			    "sr_read_cdda: ddi_copyin Failed\n");
28196 			kmem_free(cdda, sizeof (struct cdrom_cdda));
28197 			return (EFAULT);
28198 		}
28199 		/* Convert the ILP32 uscsi data from the application to LP64 */
28200 		cdrom_cdda32tocdrom_cdda(cdda32, cdda);
28201 		break;
28202 	case DDI_MODEL_NONE:
28203 		if (ddi_copyin(data, cdda, sizeof (struct cdrom_cdda), flag)) {
28204 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
28205 			    "sr_read_cdda: ddi_copyin Failed\n");
28206 			kmem_free(cdda, sizeof (struct cdrom_cdda));
28207 			return (EFAULT);
28208 		}
28209 		break;
28210 	}
28211 #else /* ! _MULTI_DATAMODEL */
28212 	if (ddi_copyin(data, cdda, sizeof (struct cdrom_cdda), flag)) {
28213 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
28214 		    "sr_read_cdda: ddi_copyin Failed\n");
28215 		kmem_free(cdda, sizeof (struct cdrom_cdda));
28216 		return (EFAULT);
28217 	}
28218 #endif /* _MULTI_DATAMODEL */
28219 
28220 	/*
28221 	 * Since MMC-2 expects max 3 bytes for length, check if the
28222 	 * length input is greater than 3 bytes
28223 	 */
28224 	if ((cdda->cdda_length & 0xFF000000) != 0) {
28225 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN, "sr_read_cdda: "
28226 		    "cdrom transfer length too large: %d (limit %d)\n",
28227 		    cdda->cdda_length, 0xFFFFFF);
28228 		kmem_free(cdda, sizeof (struct cdrom_cdda));
28229 		return (EINVAL);
28230 	}
28231 
28232 	switch (cdda->cdda_subcode) {
28233 	case CDROM_DA_NO_SUBCODE:
28234 		buflen = CDROM_BLK_2352 * cdda->cdda_length;
28235 		break;
28236 	case CDROM_DA_SUBQ:
28237 		buflen = CDROM_BLK_2368 * cdda->cdda_length;
28238 		break;
28239 	case CDROM_DA_ALL_SUBCODE:
28240 		buflen = CDROM_BLK_2448 * cdda->cdda_length;
28241 		break;
28242 	case CDROM_DA_SUBCODE_ONLY:
28243 		buflen = CDROM_BLK_SUBCODE * cdda->cdda_length;
28244 		break;
28245 	default:
28246 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
28247 		    "sr_read_cdda: Subcode '0x%x' Not Supported\n",
28248 		    cdda->cdda_subcode);
28249 		kmem_free(cdda, sizeof (struct cdrom_cdda));
28250 		return (EINVAL);
28251 	}
28252 
28253 	/* Build and send the command */
28254 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
28255 	bzero(cdb, CDB_GROUP5);
28256 
28257 	if (un->un_f_cfg_cdda == TRUE) {
28258 		cdb[0] = (char)SCMD_READ_CD;
28259 		cdb[1] = 0x04;
28260 		cdb[2] = (((cdda->cdda_addr) & 0xff000000) >> 24);
28261 		cdb[3] = (((cdda->cdda_addr) & 0x00ff0000) >> 16);
28262 		cdb[4] = (((cdda->cdda_addr) & 0x0000ff00) >> 8);
28263 		cdb[5] = ((cdda->cdda_addr) & 0x000000ff);
28264 		cdb[6] = (((cdda->cdda_length) & 0x00ff0000) >> 16);
28265 		cdb[7] = (((cdda->cdda_length) & 0x0000ff00) >> 8);
28266 		cdb[8] = ((cdda->cdda_length) & 0x000000ff);
28267 		cdb[9] = 0x10;
28268 		switch (cdda->cdda_subcode) {
28269 		case CDROM_DA_NO_SUBCODE :
28270 			cdb[10] = 0x0;
28271 			break;
28272 		case CDROM_DA_SUBQ :
28273 			cdb[10] = 0x2;
28274 			break;
28275 		case CDROM_DA_ALL_SUBCODE :
28276 			cdb[10] = 0x1;
28277 			break;
28278 		case CDROM_DA_SUBCODE_ONLY :
28279 			/* FALLTHROUGH */
28280 		default :
28281 			kmem_free(cdda, sizeof (struct cdrom_cdda));
28282 			kmem_free(com, sizeof (*com));
28283 			return (ENOTTY);
28284 		}
28285 	} else {
28286 		cdb[0] = (char)SCMD_READ_CDDA;
28287 		cdb[2] = (((cdda->cdda_addr) & 0xff000000) >> 24);
28288 		cdb[3] = (((cdda->cdda_addr) & 0x00ff0000) >> 16);
28289 		cdb[4] = (((cdda->cdda_addr) & 0x0000ff00) >> 8);
28290 		cdb[5] = ((cdda->cdda_addr) & 0x000000ff);
28291 		cdb[6] = (((cdda->cdda_length) & 0xff000000) >> 24);
28292 		cdb[7] = (((cdda->cdda_length) & 0x00ff0000) >> 16);
28293 		cdb[8] = (((cdda->cdda_length) & 0x0000ff00) >> 8);
28294 		cdb[9] = ((cdda->cdda_length) & 0x000000ff);
28295 		cdb[10] = cdda->cdda_subcode;
28296 	}
28297 
28298 	com->uscsi_cdb = cdb;
28299 	com->uscsi_cdblen = CDB_GROUP5;
28300 	com->uscsi_bufaddr = (caddr_t)cdda->cdda_data;
28301 	com->uscsi_buflen = buflen;
28302 	com->uscsi_flags = USCSI_DIAGNOSE|USCSI_SILENT|USCSI_READ;
28303 
28304 	rval = sd_send_scsi_cmd(dev, com, FKIOCTL, UIO_USERSPACE,
28305 	    SD_PATH_STANDARD);
28306 
28307 	kmem_free(cdda, sizeof (struct cdrom_cdda));
28308 	kmem_free(com, sizeof (*com));
28309 	return (rval);
28310 }
28311 
28312 
28313 /*
28314  *    Function: sr_read_cdxa()
28315  *
28316  * Description: This routine is the driver entry point for handling CD-ROM
28317  *		ioctl requests to return CD-XA (Extended Architecture) data.
28318  *		(CDROMCDXA).
28319  *
28320  *   Arguments: dev	- the device 'dev_t'
28321  *		data	- pointer to user provided CD-XA structure specifying
28322  *			  the data starting address, transfer length, and format
28323  *		flag	- this argument is a pass through to ddi_copyxxx()
28324  *			  directly from the mode argument of ioctl().
28325  *
28326  * Return Code: the code returned by sd_send_scsi_cmd()
28327  *		EFAULT if ddi_copyxxx() fails
28328  *		ENXIO if fail ddi_get_soft_state
28329  *		EINVAL if data pointer is NULL
28330  */
28331 
28332 static int
28333 sr_read_cdxa(dev_t dev, caddr_t data, int flag)
28334 {
28335 	struct sd_lun		*un;
28336 	struct uscsi_cmd	*com;
28337 	struct cdrom_cdxa	*cdxa;
28338 	int			rval;
28339 	size_t			buflen;
28340 	char			cdb[CDB_GROUP5];
28341 	uchar_t			read_flags;
28342 
28343 #ifdef _MULTI_DATAMODEL
28344 	/* To support ILP32 applications in an LP64 world */
28345 	struct cdrom_cdxa32		cdrom_cdxa32;
28346 	struct cdrom_cdxa32		*cdxa32 = &cdrom_cdxa32;
28347 #endif /* _MULTI_DATAMODEL */
28348 
28349 	if (data == NULL) {
28350 		return (EINVAL);
28351 	}
28352 
28353 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
28354 		return (ENXIO);
28355 	}
28356 
28357 	cdxa = kmem_zalloc(sizeof (struct cdrom_cdxa), KM_SLEEP);
28358 
28359 #ifdef _MULTI_DATAMODEL
28360 	switch (ddi_model_convert_from(flag & FMODELS)) {
28361 	case DDI_MODEL_ILP32:
28362 		if (ddi_copyin(data, cdxa32, sizeof (*cdxa32), flag)) {
28363 			kmem_free(cdxa, sizeof (struct cdrom_cdxa));
28364 			return (EFAULT);
28365 		}
28366 		/*
28367 		 * Convert the ILP32 uscsi data from the
28368 		 * application to LP64 for internal use.
28369 		 */
28370 		cdrom_cdxa32tocdrom_cdxa(cdxa32, cdxa);
28371 		break;
28372 	case DDI_MODEL_NONE:
28373 		if (ddi_copyin(data, cdxa, sizeof (struct cdrom_cdxa), flag)) {
28374 			kmem_free(cdxa, sizeof (struct cdrom_cdxa));
28375 			return (EFAULT);
28376 		}
28377 		break;
28378 	}
28379 #else /* ! _MULTI_DATAMODEL */
28380 	if (ddi_copyin(data, cdxa, sizeof (struct cdrom_cdxa), flag)) {
28381 		kmem_free(cdxa, sizeof (struct cdrom_cdxa));
28382 		return (EFAULT);
28383 	}
28384 #endif /* _MULTI_DATAMODEL */
28385 
28386 	/*
28387 	 * Since MMC-2 expects max 3 bytes for length, check if the
28388 	 * length input is greater than 3 bytes
28389 	 */
28390 	if ((cdxa->cdxa_length & 0xFF000000) != 0) {
28391 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN, "sr_read_cdxa: "
28392 		    "cdrom transfer length too large: %d (limit %d)\n",
28393 		    cdxa->cdxa_length, 0xFFFFFF);
28394 		kmem_free(cdxa, sizeof (struct cdrom_cdxa));
28395 		return (EINVAL);
28396 	}
28397 
28398 	switch (cdxa->cdxa_format) {
28399 	case CDROM_XA_DATA:
28400 		buflen = CDROM_BLK_2048 * cdxa->cdxa_length;
28401 		read_flags = 0x10;
28402 		break;
28403 	case CDROM_XA_SECTOR_DATA:
28404 		buflen = CDROM_BLK_2352 * cdxa->cdxa_length;
28405 		read_flags = 0xf8;
28406 		break;
28407 	case CDROM_XA_DATA_W_ERROR:
28408 		buflen = CDROM_BLK_2646 * cdxa->cdxa_length;
28409 		read_flags = 0xfc;
28410 		break;
28411 	default:
28412 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
28413 		    "sr_read_cdxa: Format '0x%x' Not Supported\n",
28414 		    cdxa->cdxa_format);
28415 		kmem_free(cdxa, sizeof (struct cdrom_cdxa));
28416 		return (EINVAL);
28417 	}
28418 
28419 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
28420 	bzero(cdb, CDB_GROUP5);
28421 	if (un->un_f_mmc_cap == TRUE) {
28422 		cdb[0] = (char)SCMD_READ_CD;
28423 		cdb[2] = (((cdxa->cdxa_addr) & 0xff000000) >> 24);
28424 		cdb[3] = (((cdxa->cdxa_addr) & 0x00ff0000) >> 16);
28425 		cdb[4] = (((cdxa->cdxa_addr) & 0x0000ff00) >> 8);
28426 		cdb[5] = ((cdxa->cdxa_addr) & 0x000000ff);
28427 		cdb[6] = (((cdxa->cdxa_length) & 0x00ff0000) >> 16);
28428 		cdb[7] = (((cdxa->cdxa_length) & 0x0000ff00) >> 8);
28429 		cdb[8] = ((cdxa->cdxa_length) & 0x000000ff);
28430 		cdb[9] = (char)read_flags;
28431 	} else {
28432 		/*
28433 		 * Note: A vendor specific command (0xDB) is being used her to
28434 		 * request a read of all subcodes.
28435 		 */
28436 		cdb[0] = (char)SCMD_READ_CDXA;
28437 		cdb[2] = (((cdxa->cdxa_addr) & 0xff000000) >> 24);
28438 		cdb[3] = (((cdxa->cdxa_addr) & 0x00ff0000) >> 16);
28439 		cdb[4] = (((cdxa->cdxa_addr) & 0x0000ff00) >> 8);
28440 		cdb[5] = ((cdxa->cdxa_addr) & 0x000000ff);
28441 		cdb[6] = (((cdxa->cdxa_length) & 0xff000000) >> 24);
28442 		cdb[7] = (((cdxa->cdxa_length) & 0x00ff0000) >> 16);
28443 		cdb[8] = (((cdxa->cdxa_length) & 0x0000ff00) >> 8);
28444 		cdb[9] = ((cdxa->cdxa_length) & 0x000000ff);
28445 		cdb[10] = cdxa->cdxa_format;
28446 	}
28447 	com->uscsi_cdb	   = cdb;
28448 	com->uscsi_cdblen  = CDB_GROUP5;
28449 	com->uscsi_bufaddr = (caddr_t)cdxa->cdxa_data;
28450 	com->uscsi_buflen  = buflen;
28451 	com->uscsi_flags   = USCSI_DIAGNOSE|USCSI_SILENT|USCSI_READ;
28452 	rval = sd_send_scsi_cmd(dev, com, FKIOCTL, UIO_USERSPACE,
28453 	    SD_PATH_STANDARD);
28454 	kmem_free(cdxa, sizeof (struct cdrom_cdxa));
28455 	kmem_free(com, sizeof (*com));
28456 	return (rval);
28457 }
28458 
28459 
28460 /*
28461  *    Function: sr_eject()
28462  *
28463  * Description: This routine is the driver entry point for handling CD-ROM
28464  *		eject ioctl requests (FDEJECT, DKIOCEJECT, CDROMEJECT)
28465  *
28466  *   Arguments: dev	- the device 'dev_t'
28467  *
28468  * Return Code: the code returned by sd_send_scsi_cmd()
28469  */
28470 
28471 static int
28472 sr_eject(dev_t dev)
28473 {
28474 	struct sd_lun	*un;
28475 	int		rval;
28476 	sd_ssc_t	*ssc;
28477 
28478 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL ||
28479 	    (un->un_state == SD_STATE_OFFLINE)) {
28480 		return (ENXIO);
28481 	}
28482 
28483 	/*
28484 	 * To prevent race conditions with the eject
28485 	 * command, keep track of an eject command as
28486 	 * it progresses. If we are already handling
28487 	 * an eject command in the driver for the given
28488 	 * unit and another request to eject is received
28489 	 * immediately return EAGAIN so we don't lose
28490 	 * the command if the current eject command fails.
28491 	 */
28492 	mutex_enter(SD_MUTEX(un));
28493 	if (un->un_f_ejecting == TRUE) {
28494 		mutex_exit(SD_MUTEX(un));
28495 		return (EAGAIN);
28496 	}
28497 	un->un_f_ejecting = TRUE;
28498 	mutex_exit(SD_MUTEX(un));
28499 
28500 	ssc = sd_ssc_init(un);
28501 	rval = sd_send_scsi_DOORLOCK(ssc, SD_REMOVAL_ALLOW,
28502 	    SD_PATH_STANDARD);
28503 	sd_ssc_fini(ssc);
28504 
28505 	if (rval != 0) {
28506 		mutex_enter(SD_MUTEX(un));
28507 		un->un_f_ejecting = FALSE;
28508 		mutex_exit(SD_MUTEX(un));
28509 		return (rval);
28510 	}
28511 
28512 	ssc = sd_ssc_init(un);
28513 	rval = sd_send_scsi_START_STOP_UNIT(ssc, SD_START_STOP,
28514 	    SD_TARGET_EJECT, SD_PATH_STANDARD);
28515 	sd_ssc_fini(ssc);
28516 
28517 	if (rval == 0) {
28518 		mutex_enter(SD_MUTEX(un));
28519 		sr_ejected(un);
28520 		un->un_mediastate = DKIO_EJECTED;
28521 		un->un_f_ejecting = FALSE;
28522 		cv_broadcast(&un->un_state_cv);
28523 		mutex_exit(SD_MUTEX(un));
28524 	} else {
28525 		mutex_enter(SD_MUTEX(un));
28526 		un->un_f_ejecting = FALSE;
28527 		mutex_exit(SD_MUTEX(un));
28528 	}
28529 	return (rval);
28530 }
28531 
28532 
28533 /*
28534  *    Function: sr_ejected()
28535  *
28536  * Description: This routine updates the soft state structure to invalidate the
28537  *		geometry information after the media has been ejected or a
28538  *		media eject has been detected.
28539  *
28540  *   Arguments: un - driver soft state (unit) structure
28541  */
28542 
28543 static void
28544 sr_ejected(struct sd_lun *un)
28545 {
28546 	struct sd_errstats *stp;
28547 
28548 	ASSERT(un != NULL);
28549 	ASSERT(mutex_owned(SD_MUTEX(un)));
28550 
28551 	un->un_f_blockcount_is_valid	= FALSE;
28552 	un->un_f_tgt_blocksize_is_valid	= FALSE;
28553 	mutex_exit(SD_MUTEX(un));
28554 	cmlb_invalidate(un->un_cmlbhandle, (void *)SD_PATH_DIRECT_PRIORITY);
28555 	mutex_enter(SD_MUTEX(un));
28556 
28557 	if (un->un_errstats != NULL) {
28558 		stp = (struct sd_errstats *)un->un_errstats->ks_data;
28559 		stp->sd_capacity.value.ui64 = 0;
28560 	}
28561 }
28562 
28563 
28564 /*
28565  *    Function: sr_check_wp()
28566  *
28567  * Description: This routine checks the write protection of a removable
28568  *      media disk and hotpluggable devices via the write protect bit of
28569  *      the Mode Page Header device specific field. Some devices choke
28570  *      on unsupported mode page. In order to workaround this issue,
28571  *      this routine has been implemented to use 0x3f mode page(request
28572  *      for all pages) for all device types.
28573  *
28574  *   Arguments: dev             - the device 'dev_t'
28575  *
28576  * Return Code: int indicating if the device is write protected (1) or not (0)
28577  *
28578  *     Context: Kernel thread.
28579  *
28580  */
28581 
28582 static int
28583 sr_check_wp(dev_t dev)
28584 {
28585 	struct sd_lun	*un;
28586 	uchar_t		device_specific;
28587 	uchar_t		*sense;
28588 	int		hdrlen;
28589 	int		rval = FALSE;
28590 	int		status;
28591 	sd_ssc_t	*ssc;
28592 
28593 	/*
28594 	 * Note: The return codes for this routine should be reworked to
28595 	 * properly handle the case of a NULL softstate.
28596 	 */
28597 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
28598 		return (FALSE);
28599 	}
28600 
28601 	if (un->un_f_cfg_is_atapi == TRUE) {
28602 		/*
28603 		 * The mode page contents are not required; set the allocation
28604 		 * length for the mode page header only
28605 		 */
28606 		hdrlen = MODE_HEADER_LENGTH_GRP2;
28607 		sense = kmem_zalloc(hdrlen, KM_SLEEP);
28608 		ssc = sd_ssc_init(un);
28609 		status = sd_send_scsi_MODE_SENSE(ssc, CDB_GROUP1, sense, hdrlen,
28610 		    MODEPAGE_ALLPAGES, SD_PATH_STANDARD);
28611 		sd_ssc_fini(ssc);
28612 		if (status != 0)
28613 			goto err_exit;
28614 		device_specific =
28615 		    ((struct mode_header_grp2 *)sense)->device_specific;
28616 	} else {
28617 		hdrlen = MODE_HEADER_LENGTH;
28618 		sense = kmem_zalloc(hdrlen, KM_SLEEP);
28619 		ssc = sd_ssc_init(un);
28620 		status = sd_send_scsi_MODE_SENSE(ssc, CDB_GROUP0, sense, hdrlen,
28621 		    MODEPAGE_ALLPAGES, SD_PATH_STANDARD);
28622 		sd_ssc_fini(ssc);
28623 		if (status != 0)
28624 			goto err_exit;
28625 		device_specific =
28626 		    ((struct mode_header *)sense)->device_specific;
28627 	}
28628 
28629 
28630 	/*
28631 	 * Write protect mode sense failed; not all disks
28632 	 * understand this query. Return FALSE assuming that
28633 	 * these devices are not writable.
28634 	 */
28635 	if (device_specific & WRITE_PROTECT) {
28636 		rval = TRUE;
28637 	}
28638 
28639 err_exit:
28640 	kmem_free(sense, hdrlen);
28641 	return (rval);
28642 }
28643 
28644 /*
28645  *    Function: sr_volume_ctrl()
28646  *
28647  * Description: This routine is the driver entry point for handling CD-ROM
28648  *		audio output volume ioctl requests. (CDROMVOLCTRL)
28649  *
28650  *   Arguments: dev	- the device 'dev_t'
28651  *		data	- pointer to user audio volume control structure
28652  *		flag	- this argument is a pass through to ddi_copyxxx()
28653  *			  directly from the mode argument of ioctl().
28654  *
28655  * Return Code: the code returned by sd_send_scsi_cmd()
28656  *		EFAULT if ddi_copyxxx() fails
28657  *		ENXIO if fail ddi_get_soft_state
28658  *		EINVAL if data pointer is NULL
28659  *
28660  */
28661 
28662 static int
28663 sr_volume_ctrl(dev_t dev, caddr_t data, int flag)
28664 {
28665 	struct sd_lun		*un;
28666 	struct cdrom_volctrl    volume;
28667 	struct cdrom_volctrl    *vol = &volume;
28668 	uchar_t			*sense_page;
28669 	uchar_t			*select_page;
28670 	uchar_t			*sense;
28671 	uchar_t			*select;
28672 	int			sense_buflen;
28673 	int			select_buflen;
28674 	int			rval;
28675 	sd_ssc_t		*ssc;
28676 
28677 	if (data == NULL) {
28678 		return (EINVAL);
28679 	}
28680 
28681 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL ||
28682 	    (un->un_state == SD_STATE_OFFLINE)) {
28683 		return (ENXIO);
28684 	}
28685 
28686 	if (ddi_copyin(data, vol, sizeof (struct cdrom_volctrl), flag)) {
28687 		return (EFAULT);
28688 	}
28689 
28690 	if ((un->un_f_cfg_is_atapi == TRUE) || (un->un_f_mmc_cap == TRUE)) {
28691 		struct mode_header_grp2		*sense_mhp;
28692 		struct mode_header_grp2		*select_mhp;
28693 		int				bd_len;
28694 
28695 		sense_buflen = MODE_PARAM_LENGTH_GRP2 + MODEPAGE_AUDIO_CTRL_LEN;
28696 		select_buflen = MODE_HEADER_LENGTH_GRP2 +
28697 		    MODEPAGE_AUDIO_CTRL_LEN;
28698 		sense  = kmem_zalloc(sense_buflen, KM_SLEEP);
28699 		select = kmem_zalloc(select_buflen, KM_SLEEP);
28700 		ssc = sd_ssc_init(un);
28701 		rval = sd_send_scsi_MODE_SENSE(ssc, CDB_GROUP1, sense,
28702 		    sense_buflen, MODEPAGE_AUDIO_CTRL,
28703 		    SD_PATH_STANDARD);
28704 		sd_ssc_fini(ssc);
28705 
28706 		if (rval != 0) {
28707 			SD_ERROR(SD_LOG_IOCTL_RMMEDIA, un,
28708 			    "sr_volume_ctrl: Mode Sense Failed\n");
28709 			kmem_free(sense, sense_buflen);
28710 			kmem_free(select, select_buflen);
28711 			return (rval);
28712 		}
28713 		sense_mhp = (struct mode_header_grp2 *)sense;
28714 		select_mhp = (struct mode_header_grp2 *)select;
28715 		bd_len = (sense_mhp->bdesc_length_hi << 8) |
28716 		    sense_mhp->bdesc_length_lo;
28717 		if (bd_len > MODE_BLK_DESC_LENGTH) {
28718 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
28719 			    "sr_volume_ctrl: Mode Sense returned invalid "
28720 			    "block descriptor length\n");
28721 			kmem_free(sense, sense_buflen);
28722 			kmem_free(select, select_buflen);
28723 			return (EIO);
28724 		}
28725 		sense_page = (uchar_t *)
28726 		    (sense + MODE_HEADER_LENGTH_GRP2 + bd_len);
28727 		select_page = (uchar_t *)(select + MODE_HEADER_LENGTH_GRP2);
28728 		select_mhp->length_msb = 0;
28729 		select_mhp->length_lsb = 0;
28730 		select_mhp->bdesc_length_hi = 0;
28731 		select_mhp->bdesc_length_lo = 0;
28732 	} else {
28733 		struct mode_header		*sense_mhp, *select_mhp;
28734 
28735 		sense_buflen = MODE_PARAM_LENGTH + MODEPAGE_AUDIO_CTRL_LEN;
28736 		select_buflen = MODE_HEADER_LENGTH + MODEPAGE_AUDIO_CTRL_LEN;
28737 		sense  = kmem_zalloc(sense_buflen, KM_SLEEP);
28738 		select = kmem_zalloc(select_buflen, KM_SLEEP);
28739 		ssc = sd_ssc_init(un);
28740 		rval = sd_send_scsi_MODE_SENSE(ssc, CDB_GROUP0, sense,
28741 		    sense_buflen, MODEPAGE_AUDIO_CTRL,
28742 		    SD_PATH_STANDARD);
28743 		sd_ssc_fini(ssc);
28744 
28745 		if (rval != 0) {
28746 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
28747 			    "sr_volume_ctrl: Mode Sense Failed\n");
28748 			kmem_free(sense, sense_buflen);
28749 			kmem_free(select, select_buflen);
28750 			return (rval);
28751 		}
28752 		sense_mhp  = (struct mode_header *)sense;
28753 		select_mhp = (struct mode_header *)select;
28754 		if (sense_mhp->bdesc_length > MODE_BLK_DESC_LENGTH) {
28755 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
28756 			    "sr_volume_ctrl: Mode Sense returned invalid "
28757 			    "block descriptor length\n");
28758 			kmem_free(sense, sense_buflen);
28759 			kmem_free(select, select_buflen);
28760 			return (EIO);
28761 		}
28762 		sense_page = (uchar_t *)
28763 		    (sense + MODE_HEADER_LENGTH + sense_mhp->bdesc_length);
28764 		select_page = (uchar_t *)(select + MODE_HEADER_LENGTH);
28765 		select_mhp->length = 0;
28766 		select_mhp->bdesc_length = 0;
28767 	}
28768 	/*
28769 	 * Note: An audio control data structure could be created and overlayed
28770 	 * on the following in place of the array indexing method implemented.
28771 	 */
28772 
28773 	/* Build the select data for the user volume data */
28774 	select_page[0] = MODEPAGE_AUDIO_CTRL;
28775 	select_page[1] = 0xE;
28776 	/* Set the immediate bit */
28777 	select_page[2] = 0x04;
28778 	/* Zero out reserved fields */
28779 	select_page[3] = 0x00;
28780 	select_page[4] = 0x00;
28781 	/* Return sense data for fields not to be modified */
28782 	select_page[5] = sense_page[5];
28783 	select_page[6] = sense_page[6];
28784 	select_page[7] = sense_page[7];
28785 	/* Set the user specified volume levels for channel 0 and 1 */
28786 	select_page[8] = 0x01;
28787 	select_page[9] = vol->channel0;
28788 	select_page[10] = 0x02;
28789 	select_page[11] = vol->channel1;
28790 	/* Channel 2 and 3 are currently unsupported so return the sense data */
28791 	select_page[12] = sense_page[12];
28792 	select_page[13] = sense_page[13];
28793 	select_page[14] = sense_page[14];
28794 	select_page[15] = sense_page[15];
28795 
28796 	ssc = sd_ssc_init(un);
28797 	if ((un->un_f_cfg_is_atapi == TRUE) || (un->un_f_mmc_cap == TRUE)) {
28798 		rval = sd_send_scsi_MODE_SELECT(ssc, CDB_GROUP1, select,
28799 		    select_buflen, SD_DONTSAVE_PAGE, SD_PATH_STANDARD);
28800 	} else {
28801 		rval = sd_send_scsi_MODE_SELECT(ssc, CDB_GROUP0, select,
28802 		    select_buflen, SD_DONTSAVE_PAGE, SD_PATH_STANDARD);
28803 	}
28804 	sd_ssc_fini(ssc);
28805 
28806 	kmem_free(sense, sense_buflen);
28807 	kmem_free(select, select_buflen);
28808 	return (rval);
28809 }
28810 
28811 
28812 /*
28813  *    Function: sr_read_sony_session_offset()
28814  *
28815  * Description: This routine is the driver entry point for handling CD-ROM
28816  *		ioctl requests for session offset information. (CDROMREADOFFSET)
28817  *		The address of the first track in the last session of a
28818  *		multi-session CD-ROM is returned
28819  *
28820  *		Note: This routine uses a vendor specific key value in the
28821  *		command control field without implementing any vendor check here
28822  *		or in the ioctl routine.
28823  *
28824  *   Arguments: dev	- the device 'dev_t'
28825  *		data	- pointer to an int to hold the requested address
28826  *		flag	- this argument is a pass through to ddi_copyxxx()
28827  *			  directly from the mode argument of ioctl().
28828  *
28829  * Return Code: the code returned by sd_send_scsi_cmd()
28830  *		EFAULT if ddi_copyxxx() fails
28831  *		ENXIO if fail ddi_get_soft_state
28832  *		EINVAL if data pointer is NULL
28833  */
28834 
28835 static int
28836 sr_read_sony_session_offset(dev_t dev, caddr_t data, int flag)
28837 {
28838 	struct sd_lun		*un;
28839 	struct uscsi_cmd	*com;
28840 	caddr_t			buffer;
28841 	char			cdb[CDB_GROUP1];
28842 	int			session_offset = 0;
28843 	int			rval;
28844 
28845 	if (data == NULL) {
28846 		return (EINVAL);
28847 	}
28848 
28849 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL ||
28850 	    (un->un_state == SD_STATE_OFFLINE)) {
28851 		return (ENXIO);
28852 	}
28853 
28854 	buffer = kmem_zalloc((size_t)SONY_SESSION_OFFSET_LEN, KM_SLEEP);
28855 	bzero(cdb, CDB_GROUP1);
28856 	cdb[0] = SCMD_READ_TOC;
28857 	/*
28858 	 * Bytes 7 & 8 are the 12 byte allocation length for a single entry.
28859 	 * (4 byte TOC response header + 8 byte response data)
28860 	 */
28861 	cdb[8] = SONY_SESSION_OFFSET_LEN;
28862 	/* Byte 9 is the control byte. A vendor specific value is used */
28863 	cdb[9] = SONY_SESSION_OFFSET_KEY;
28864 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
28865 	com->uscsi_cdb = cdb;
28866 	com->uscsi_cdblen = CDB_GROUP1;
28867 	com->uscsi_bufaddr = buffer;
28868 	com->uscsi_buflen = SONY_SESSION_OFFSET_LEN;
28869 	com->uscsi_flags = USCSI_DIAGNOSE|USCSI_SILENT|USCSI_READ;
28870 
28871 	rval = sd_send_scsi_cmd(dev, com, FKIOCTL, UIO_SYSSPACE,
28872 	    SD_PATH_STANDARD);
28873 	if (rval != 0) {
28874 		kmem_free(buffer, SONY_SESSION_OFFSET_LEN);
28875 		kmem_free(com, sizeof (*com));
28876 		return (rval);
28877 	}
28878 	if (buffer[1] == SONY_SESSION_OFFSET_VALID) {
28879 		session_offset =
28880 		    ((uchar_t)buffer[8] << 24) + ((uchar_t)buffer[9] << 16) +
28881 		    ((uchar_t)buffer[10] << 8) + ((uchar_t)buffer[11]);
28882 		/*
28883 		 * Offset returned offset in current lbasize block's. Convert to
28884 		 * 2k block's to return to the user
28885 		 */
28886 		if (un->un_tgt_blocksize == CDROM_BLK_512) {
28887 			session_offset >>= 2;
28888 		} else if (un->un_tgt_blocksize == CDROM_BLK_1024) {
28889 			session_offset >>= 1;
28890 		}
28891 	}
28892 
28893 	if (ddi_copyout(&session_offset, data, sizeof (int), flag) != 0) {
28894 		rval = EFAULT;
28895 	}
28896 
28897 	kmem_free(buffer, SONY_SESSION_OFFSET_LEN);
28898 	kmem_free(com, sizeof (*com));
28899 	return (rval);
28900 }
28901 
28902 
28903 /*
28904  *    Function: sd_wm_cache_constructor()
28905  *
28906  * Description: Cache Constructor for the wmap cache for the read/modify/write
28907  * 		devices.
28908  *
28909  *   Arguments: wm      - A pointer to the sd_w_map to be initialized.
28910  *		un	- sd_lun structure for the device.
28911  *		flag	- the km flags passed to constructor
28912  *
28913  * Return Code: 0 on success.
28914  *		-1 on failure.
28915  */
28916 
28917 /*ARGSUSED*/
28918 static int
28919 sd_wm_cache_constructor(void *wm, void *un, int flags)
28920 {
28921 	bzero(wm, sizeof (struct sd_w_map));
28922 	cv_init(&((struct sd_w_map *)wm)->wm_avail, NULL, CV_DRIVER, NULL);
28923 	return (0);
28924 }
28925 
28926 
28927 /*
28928  *    Function: sd_wm_cache_destructor()
28929  *
28930  * Description: Cache destructor for the wmap cache for the read/modify/write
28931  * 		devices.
28932  *
28933  *   Arguments: wm      - A pointer to the sd_w_map to be initialized.
28934  *		un	- sd_lun structure for the device.
28935  */
28936 /*ARGSUSED*/
28937 static void
28938 sd_wm_cache_destructor(void *wm, void *un)
28939 {
28940 	cv_destroy(&((struct sd_w_map *)wm)->wm_avail);
28941 }
28942 
28943 
28944 /*
28945  *    Function: sd_range_lock()
28946  *
28947  * Description: Lock the range of blocks specified as parameter to ensure
28948  *		that read, modify write is atomic and no other i/o writes
28949  *		to the same location. The range is specified in terms
28950  *		of start and end blocks. Block numbers are the actual
28951  *		media block numbers and not system.
28952  *
28953  *   Arguments: un	- sd_lun structure for the device.
28954  *		startb - The starting block number
28955  *		endb - The end block number
28956  *		typ - type of i/o - simple/read_modify_write
28957  *
28958  * Return Code: wm  - pointer to the wmap structure.
28959  *
28960  *     Context: This routine can sleep.
28961  */
28962 
28963 static struct sd_w_map *
28964 sd_range_lock(struct sd_lun *un, daddr_t startb, daddr_t endb, ushort_t typ)
28965 {
28966 	struct sd_w_map *wmp = NULL;
28967 	struct sd_w_map *sl_wmp = NULL;
28968 	struct sd_w_map *tmp_wmp;
28969 	wm_state state = SD_WM_CHK_LIST;
28970 
28971 
28972 	ASSERT(un != NULL);
28973 	ASSERT(!mutex_owned(SD_MUTEX(un)));
28974 
28975 	mutex_enter(SD_MUTEX(un));
28976 
28977 	while (state != SD_WM_DONE) {
28978 
28979 		switch (state) {
28980 		case SD_WM_CHK_LIST:
28981 			/*
28982 			 * This is the starting state. Check the wmap list
28983 			 * to see if the range is currently available.
28984 			 */
28985 			if (!(typ & SD_WTYPE_RMW) && !(un->un_rmw_count)) {
28986 				/*
28987 				 * If this is a simple write and no rmw
28988 				 * i/o is pending then try to lock the
28989 				 * range as the range should be available.
28990 				 */
28991 				state = SD_WM_LOCK_RANGE;
28992 			} else {
28993 				tmp_wmp = sd_get_range(un, startb, endb);
28994 				if (tmp_wmp != NULL) {
28995 					if ((wmp != NULL) && ONLIST(un, wmp)) {
28996 						/*
28997 						 * Should not keep onlist wmps
28998 						 * while waiting this macro
28999 						 * will also do wmp = NULL;
29000 						 */
29001 						FREE_ONLIST_WMAP(un, wmp);
29002 					}
29003 					/*
29004 					 * sl_wmp is the wmap on which wait
29005 					 * is done, since the tmp_wmp points
29006 					 * to the inuse wmap, set sl_wmp to
29007 					 * tmp_wmp and change the state to sleep
29008 					 */
29009 					sl_wmp = tmp_wmp;
29010 					state = SD_WM_WAIT_MAP;
29011 				} else {
29012 					state = SD_WM_LOCK_RANGE;
29013 				}
29014 
29015 			}
29016 			break;
29017 
29018 		case SD_WM_LOCK_RANGE:
29019 			ASSERT(un->un_wm_cache);
29020 			/*
29021 			 * The range need to be locked, try to get a wmap.
29022 			 * First attempt it with NO_SLEEP, want to avoid a sleep
29023 			 * if possible as we will have to release the sd mutex
29024 			 * if we have to sleep.
29025 			 */
29026 			if (wmp == NULL)
29027 				wmp = kmem_cache_alloc(un->un_wm_cache,
29028 				    KM_NOSLEEP);
29029 			if (wmp == NULL) {
29030 				mutex_exit(SD_MUTEX(un));
29031 				_NOTE(DATA_READABLE_WITHOUT_LOCK
29032 				    (sd_lun::un_wm_cache))
29033 				wmp = kmem_cache_alloc(un->un_wm_cache,
29034 				    KM_SLEEP);
29035 				mutex_enter(SD_MUTEX(un));
29036 				/*
29037 				 * we released the mutex so recheck and go to
29038 				 * check list state.
29039 				 */
29040 				state = SD_WM_CHK_LIST;
29041 			} else {
29042 				/*
29043 				 * We exit out of state machine since we
29044 				 * have the wmap. Do the housekeeping first.
29045 				 * place the wmap on the wmap list if it is not
29046 				 * on it already and then set the state to done.
29047 				 */
29048 				wmp->wm_start = startb;
29049 				wmp->wm_end = endb;
29050 				wmp->wm_flags = typ | SD_WM_BUSY;
29051 				if (typ & SD_WTYPE_RMW) {
29052 					un->un_rmw_count++;
29053 				}
29054 				/*
29055 				 * If not already on the list then link
29056 				 */
29057 				if (!ONLIST(un, wmp)) {
29058 					wmp->wm_next = un->un_wm;
29059 					wmp->wm_prev = NULL;
29060 					if (wmp->wm_next)
29061 						wmp->wm_next->wm_prev = wmp;
29062 					un->un_wm = wmp;
29063 				}
29064 				state = SD_WM_DONE;
29065 			}
29066 			break;
29067 
29068 		case SD_WM_WAIT_MAP:
29069 			ASSERT(sl_wmp->wm_flags & SD_WM_BUSY);
29070 			/*
29071 			 * Wait is done on sl_wmp, which is set in the
29072 			 * check_list state.
29073 			 */
29074 			sl_wmp->wm_wanted_count++;
29075 			cv_wait(&sl_wmp->wm_avail, SD_MUTEX(un));
29076 			sl_wmp->wm_wanted_count--;
29077 			/*
29078 			 * We can reuse the memory from the completed sl_wmp
29079 			 * lock range for our new lock, but only if noone is
29080 			 * waiting for it.
29081 			 */
29082 			ASSERT(!(sl_wmp->wm_flags & SD_WM_BUSY));
29083 			if (sl_wmp->wm_wanted_count == 0) {
29084 				if (wmp != NULL)
29085 					CHK_N_FREEWMP(un, wmp);
29086 				wmp = sl_wmp;
29087 			}
29088 			sl_wmp = NULL;
29089 			/*
29090 			 * After waking up, need to recheck for availability of
29091 			 * range.
29092 			 */
29093 			state = SD_WM_CHK_LIST;
29094 			break;
29095 
29096 		default:
29097 			panic("sd_range_lock: "
29098 			    "Unknown state %d in sd_range_lock", state);
29099 			/*NOTREACHED*/
29100 		} /* switch(state) */
29101 
29102 	} /* while(state != SD_WM_DONE) */
29103 
29104 	mutex_exit(SD_MUTEX(un));
29105 
29106 	ASSERT(wmp != NULL);
29107 
29108 	return (wmp);
29109 }
29110 
29111 
29112 /*
29113  *    Function: sd_get_range()
29114  *
29115  * Description: Find if there any overlapping I/O to this one
29116  *		Returns the write-map of 1st such I/O, NULL otherwise.
29117  *
29118  *   Arguments: un	- sd_lun structure for the device.
29119  *		startb - The starting block number
29120  *		endb - The end block number
29121  *
29122  * Return Code: wm  - pointer to the wmap structure.
29123  */
29124 
29125 static struct sd_w_map *
29126 sd_get_range(struct sd_lun *un, daddr_t startb, daddr_t endb)
29127 {
29128 	struct sd_w_map *wmp;
29129 
29130 	ASSERT(un != NULL);
29131 
29132 	for (wmp = un->un_wm; wmp != NULL; wmp = wmp->wm_next) {
29133 		if (!(wmp->wm_flags & SD_WM_BUSY)) {
29134 			continue;
29135 		}
29136 		if ((startb >= wmp->wm_start) && (startb <= wmp->wm_end)) {
29137 			break;
29138 		}
29139 		if ((endb >= wmp->wm_start) && (endb <= wmp->wm_end)) {
29140 			break;
29141 		}
29142 	}
29143 
29144 	return (wmp);
29145 }
29146 
29147 
29148 /*
29149  *    Function: sd_free_inlist_wmap()
29150  *
29151  * Description: Unlink and free a write map struct.
29152  *
29153  *   Arguments: un      - sd_lun structure for the device.
29154  *		wmp	- sd_w_map which needs to be unlinked.
29155  */
29156 
29157 static void
29158 sd_free_inlist_wmap(struct sd_lun *un, struct sd_w_map *wmp)
29159 {
29160 	ASSERT(un != NULL);
29161 
29162 	if (un->un_wm == wmp) {
29163 		un->un_wm = wmp->wm_next;
29164 	} else {
29165 		wmp->wm_prev->wm_next = wmp->wm_next;
29166 	}
29167 
29168 	if (wmp->wm_next) {
29169 		wmp->wm_next->wm_prev = wmp->wm_prev;
29170 	}
29171 
29172 	wmp->wm_next = wmp->wm_prev = NULL;
29173 
29174 	kmem_cache_free(un->un_wm_cache, wmp);
29175 }
29176 
29177 
29178 /*
29179  *    Function: sd_range_unlock()
29180  *
29181  * Description: Unlock the range locked by wm.
29182  *		Free write map if nobody else is waiting on it.
29183  *
29184  *   Arguments: un      - sd_lun structure for the device.
29185  *              wmp     - sd_w_map which needs to be unlinked.
29186  */
29187 
29188 static void
29189 sd_range_unlock(struct sd_lun *un, struct sd_w_map *wm)
29190 {
29191 	ASSERT(un != NULL);
29192 	ASSERT(wm != NULL);
29193 	ASSERT(!mutex_owned(SD_MUTEX(un)));
29194 
29195 	mutex_enter(SD_MUTEX(un));
29196 
29197 	if (wm->wm_flags & SD_WTYPE_RMW) {
29198 		un->un_rmw_count--;
29199 	}
29200 
29201 	if (wm->wm_wanted_count) {
29202 		wm->wm_flags = 0;
29203 		/*
29204 		 * Broadcast that the wmap is available now.
29205 		 */
29206 		cv_broadcast(&wm->wm_avail);
29207 	} else {
29208 		/*
29209 		 * If no one is waiting on the map, it should be free'ed.
29210 		 */
29211 		sd_free_inlist_wmap(un, wm);
29212 	}
29213 
29214 	mutex_exit(SD_MUTEX(un));
29215 }
29216 
29217 
29218 /*
29219  *    Function: sd_read_modify_write_task
29220  *
29221  * Description: Called from a taskq thread to initiate the write phase of
29222  *		a read-modify-write request.  This is used for targets where
29223  *		un->un_sys_blocksize != un->un_tgt_blocksize.
29224  *
29225  *   Arguments: arg - a pointer to the buf(9S) struct for the write command.
29226  *
29227  *     Context: Called under taskq thread context.
29228  */
29229 
29230 static void
29231 sd_read_modify_write_task(void *arg)
29232 {
29233 	struct sd_mapblocksize_info	*bsp;
29234 	struct buf	*bp;
29235 	struct sd_xbuf	*xp;
29236 	struct sd_lun	*un;
29237 
29238 	bp = arg;	/* The bp is given in arg */
29239 	ASSERT(bp != NULL);
29240 
29241 	/* Get the pointer to the layer-private data struct */
29242 	xp = SD_GET_XBUF(bp);
29243 	ASSERT(xp != NULL);
29244 	bsp = xp->xb_private;
29245 	ASSERT(bsp != NULL);
29246 
29247 	un = SD_GET_UN(bp);
29248 	ASSERT(un != NULL);
29249 	ASSERT(!mutex_owned(SD_MUTEX(un)));
29250 
29251 	SD_TRACE(SD_LOG_IO_RMMEDIA, un,
29252 	    "sd_read_modify_write_task: entry: buf:0x%p\n", bp);
29253 
29254 	/*
29255 	 * This is the write phase of a read-modify-write request, called
29256 	 * under the context of a taskq thread in response to the completion
29257 	 * of the read portion of the rmw request completing under interrupt
29258 	 * context. The write request must be sent from here down the iostart
29259 	 * chain as if it were being sent from sd_mapblocksize_iostart(), so
29260 	 * we use the layer index saved in the layer-private data area.
29261 	 */
29262 	SD_NEXT_IOSTART(bsp->mbs_layer_index, un, bp);
29263 
29264 	SD_TRACE(SD_LOG_IO_RMMEDIA, un,
29265 	    "sd_read_modify_write_task: exit: buf:0x%p\n", bp);
29266 }
29267 
29268 
29269 /*
29270  *    Function: sddump_do_read_of_rmw()
29271  *
29272  * Description: This routine will be called from sddump, If sddump is called
29273  *		with an I/O which not aligned on device blocksize boundary
29274  *		then the write has to be converted to read-modify-write.
29275  *		Do the read part here in order to keep sddump simple.
29276  *		Note - That the sd_mutex is held across the call to this
29277  *		routine.
29278  *
29279  *   Arguments: un	- sd_lun
29280  *		blkno	- block number in terms of media block size.
29281  *		nblk	- number of blocks.
29282  *		bpp	- pointer to pointer to the buf structure. On return
29283  *			from this function, *bpp points to the valid buffer
29284  *			to which the write has to be done.
29285  *
29286  * Return Code: 0 for success or errno-type return code
29287  */
29288 
29289 static int
29290 sddump_do_read_of_rmw(struct sd_lun *un, uint64_t blkno, uint64_t nblk,
29291 	struct buf **bpp)
29292 {
29293 	int err;
29294 	int i;
29295 	int rval;
29296 	struct buf *bp;
29297 	struct scsi_pkt *pkt = NULL;
29298 	uint32_t target_blocksize;
29299 
29300 	ASSERT(un != NULL);
29301 	ASSERT(mutex_owned(SD_MUTEX(un)));
29302 
29303 	target_blocksize = un->un_tgt_blocksize;
29304 
29305 	mutex_exit(SD_MUTEX(un));
29306 
29307 	bp = scsi_alloc_consistent_buf(SD_ADDRESS(un), (struct buf *)NULL,
29308 	    (size_t)(nblk * target_blocksize), B_READ, NULL_FUNC, NULL);
29309 	if (bp == NULL) {
29310 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
29311 		    "no resources for dumping; giving up");
29312 		err = ENOMEM;
29313 		goto done;
29314 	}
29315 
29316 	rval = sd_setup_rw_pkt(un, &pkt, bp, 0, NULL_FUNC, NULL,
29317 	    blkno, nblk);
29318 	if (rval != 0) {
29319 		scsi_free_consistent_buf(bp);
29320 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
29321 		    "no resources for dumping; giving up");
29322 		err = ENOMEM;
29323 		goto done;
29324 	}
29325 
29326 	pkt->pkt_flags |= FLAG_NOINTR;
29327 
29328 	err = EIO;
29329 	for (i = 0; i < SD_NDUMP_RETRIES; i++) {
29330 
29331 		/*
29332 		 * Scsi_poll returns 0 (success) if the command completes and
29333 		 * the status block is STATUS_GOOD.  We should only check
29334 		 * errors if this condition is not true.  Even then we should
29335 		 * send our own request sense packet only if we have a check
29336 		 * condition and auto request sense has not been performed by
29337 		 * the hba.
29338 		 */
29339 		SD_TRACE(SD_LOG_DUMP, un, "sddump: sending read\n");
29340 
29341 		if ((sd_scsi_poll(un, pkt) == 0) && (pkt->pkt_resid == 0)) {
29342 			err = 0;
29343 			break;
29344 		}
29345 
29346 		/*
29347 		 * Check CMD_DEV_GONE 1st, give up if device is gone,
29348 		 * no need to read RQS data.
29349 		 */
29350 		if (pkt->pkt_reason == CMD_DEV_GONE) {
29351 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
29352 			    "Error while dumping state with rmw..."
29353 			    "Device is gone\n");
29354 			break;
29355 		}
29356 
29357 		if (SD_GET_PKT_STATUS(pkt) == STATUS_CHECK) {
29358 			SD_INFO(SD_LOG_DUMP, un,
29359 			    "sddump: read failed with CHECK, try # %d\n", i);
29360 			if (((pkt->pkt_state & STATE_ARQ_DONE) == 0)) {
29361 				(void) sd_send_polled_RQS(un);
29362 			}
29363 
29364 			continue;
29365 		}
29366 
29367 		if (SD_GET_PKT_STATUS(pkt) == STATUS_BUSY) {
29368 			int reset_retval = 0;
29369 
29370 			SD_INFO(SD_LOG_DUMP, un,
29371 			    "sddump: read failed with BUSY, try # %d\n", i);
29372 
29373 			if (un->un_f_lun_reset_enabled == TRUE) {
29374 				reset_retval = scsi_reset(SD_ADDRESS(un),
29375 				    RESET_LUN);
29376 			}
29377 			if (reset_retval == 0) {
29378 				(void) scsi_reset(SD_ADDRESS(un), RESET_TARGET);
29379 			}
29380 			(void) sd_send_polled_RQS(un);
29381 
29382 		} else {
29383 			SD_INFO(SD_LOG_DUMP, un,
29384 			    "sddump: read failed with 0x%x, try # %d\n",
29385 			    SD_GET_PKT_STATUS(pkt), i);
29386 			mutex_enter(SD_MUTEX(un));
29387 			sd_reset_target(un, pkt);
29388 			mutex_exit(SD_MUTEX(un));
29389 		}
29390 
29391 		/*
29392 		 * If we are not getting anywhere with lun/target resets,
29393 		 * let's reset the bus.
29394 		 */
29395 		if (i > SD_NDUMP_RETRIES/2) {
29396 			(void) scsi_reset(SD_ADDRESS(un), RESET_ALL);
29397 			(void) sd_send_polled_RQS(un);
29398 		}
29399 
29400 	}
29401 	scsi_destroy_pkt(pkt);
29402 
29403 	if (err != 0) {
29404 		scsi_free_consistent_buf(bp);
29405 		*bpp = NULL;
29406 	} else {
29407 		*bpp = bp;
29408 	}
29409 
29410 done:
29411 	mutex_enter(SD_MUTEX(un));
29412 	return (err);
29413 }
29414 
29415 
29416 /*
29417  *    Function: sd_failfast_flushq
29418  *
29419  * Description: Take all bp's on the wait queue that have B_FAILFAST set
29420  *		in b_flags and move them onto the failfast queue, then kick
29421  *		off a thread to return all bp's on the failfast queue to
29422  *		their owners with an error set.
29423  *
29424  *   Arguments: un - pointer to the soft state struct for the instance.
29425  *
29426  *     Context: may execute in interrupt context.
29427  */
29428 
29429 static void
29430 sd_failfast_flushq(struct sd_lun *un)
29431 {
29432 	struct buf *bp;
29433 	struct buf *next_waitq_bp;
29434 	struct buf *prev_waitq_bp = NULL;
29435 
29436 	ASSERT(un != NULL);
29437 	ASSERT(mutex_owned(SD_MUTEX(un)));
29438 	ASSERT(un->un_failfast_state == SD_FAILFAST_ACTIVE);
29439 	ASSERT(un->un_failfast_bp == NULL);
29440 
29441 	SD_TRACE(SD_LOG_IO_FAILFAST, un,
29442 	    "sd_failfast_flushq: entry: un:0x%p\n", un);
29443 
29444 	/*
29445 	 * Check if we should flush all bufs when entering failfast state, or
29446 	 * just those with B_FAILFAST set.
29447 	 */
29448 	if (sd_failfast_flushctl & SD_FAILFAST_FLUSH_ALL_BUFS) {
29449 		/*
29450 		 * Move *all* bp's on the wait queue to the failfast flush
29451 		 * queue, including those that do NOT have B_FAILFAST set.
29452 		 */
29453 		if (un->un_failfast_headp == NULL) {
29454 			ASSERT(un->un_failfast_tailp == NULL);
29455 			un->un_failfast_headp = un->un_waitq_headp;
29456 		} else {
29457 			ASSERT(un->un_failfast_tailp != NULL);
29458 			un->un_failfast_tailp->av_forw = un->un_waitq_headp;
29459 		}
29460 
29461 		un->un_failfast_tailp = un->un_waitq_tailp;
29462 
29463 		/* update kstat for each bp moved out of the waitq */
29464 		for (bp = un->un_waitq_headp; bp != NULL; bp = bp->av_forw) {
29465 			SD_UPDATE_KSTATS(un, kstat_waitq_exit, bp);
29466 		}
29467 
29468 		/* empty the waitq */
29469 		un->un_waitq_headp = un->un_waitq_tailp = NULL;
29470 
29471 	} else {
29472 		/*
29473 		 * Go thru the wait queue, pick off all entries with
29474 		 * B_FAILFAST set, and move these onto the failfast queue.
29475 		 */
29476 		for (bp = un->un_waitq_headp; bp != NULL; bp = next_waitq_bp) {
29477 			/*
29478 			 * Save the pointer to the next bp on the wait queue,
29479 			 * so we get to it on the next iteration of this loop.
29480 			 */
29481 			next_waitq_bp = bp->av_forw;
29482 
29483 			/*
29484 			 * If this bp from the wait queue does NOT have
29485 			 * B_FAILFAST set, just move on to the next element
29486 			 * in the wait queue. Note, this is the only place
29487 			 * where it is correct to set prev_waitq_bp.
29488 			 */
29489 			if ((bp->b_flags & B_FAILFAST) == 0) {
29490 				prev_waitq_bp = bp;
29491 				continue;
29492 			}
29493 
29494 			/*
29495 			 * Remove the bp from the wait queue.
29496 			 */
29497 			if (bp == un->un_waitq_headp) {
29498 				/* The bp is the first element of the waitq. */
29499 				un->un_waitq_headp = next_waitq_bp;
29500 				if (un->un_waitq_headp == NULL) {
29501 					/* The wait queue is now empty */
29502 					un->un_waitq_tailp = NULL;
29503 				}
29504 			} else {
29505 				/*
29506 				 * The bp is either somewhere in the middle
29507 				 * or at the end of the wait queue.
29508 				 */
29509 				ASSERT(un->un_waitq_headp != NULL);
29510 				ASSERT(prev_waitq_bp != NULL);
29511 				ASSERT((prev_waitq_bp->b_flags & B_FAILFAST)
29512 				    == 0);
29513 				if (bp == un->un_waitq_tailp) {
29514 					/* bp is the last entry on the waitq. */
29515 					ASSERT(next_waitq_bp == NULL);
29516 					un->un_waitq_tailp = prev_waitq_bp;
29517 				}
29518 				prev_waitq_bp->av_forw = next_waitq_bp;
29519 			}
29520 			bp->av_forw = NULL;
29521 
29522 			/*
29523 			 * update kstat since the bp is moved out of
29524 			 * the waitq
29525 			 */
29526 			SD_UPDATE_KSTATS(un, kstat_waitq_exit, bp);
29527 
29528 			/*
29529 			 * Now put the bp onto the failfast queue.
29530 			 */
29531 			if (un->un_failfast_headp == NULL) {
29532 				/* failfast queue is currently empty */
29533 				ASSERT(un->un_failfast_tailp == NULL);
29534 				un->un_failfast_headp =
29535 				    un->un_failfast_tailp = bp;
29536 			} else {
29537 				/* Add the bp to the end of the failfast q */
29538 				ASSERT(un->un_failfast_tailp != NULL);
29539 				ASSERT(un->un_failfast_tailp->b_flags &
29540 				    B_FAILFAST);
29541 				un->un_failfast_tailp->av_forw = bp;
29542 				un->un_failfast_tailp = bp;
29543 			}
29544 		}
29545 	}
29546 
29547 	/*
29548 	 * Now return all bp's on the failfast queue to their owners.
29549 	 */
29550 	while ((bp = un->un_failfast_headp) != NULL) {
29551 
29552 		un->un_failfast_headp = bp->av_forw;
29553 		if (un->un_failfast_headp == NULL) {
29554 			un->un_failfast_tailp = NULL;
29555 		}
29556 
29557 		/*
29558 		 * We want to return the bp with a failure error code, but
29559 		 * we do not want a call to sd_start_cmds() to occur here,
29560 		 * so use sd_return_failed_command_no_restart() instead of
29561 		 * sd_return_failed_command().
29562 		 */
29563 		sd_return_failed_command_no_restart(un, bp, EIO);
29564 	}
29565 
29566 	/* Flush the xbuf queues if required. */
29567 	if (sd_failfast_flushctl & SD_FAILFAST_FLUSH_ALL_QUEUES) {
29568 		ddi_xbuf_flushq(un->un_xbuf_attr, sd_failfast_flushq_callback);
29569 	}
29570 
29571 	SD_TRACE(SD_LOG_IO_FAILFAST, un,
29572 	    "sd_failfast_flushq: exit: un:0x%p\n", un);
29573 }
29574 
29575 
29576 /*
29577  *    Function: sd_failfast_flushq_callback
29578  *
29579  * Description: Return TRUE if the given bp meets the criteria for failfast
29580  *		flushing. Used with ddi_xbuf_flushq(9F).
29581  *
29582  *   Arguments: bp - ptr to buf struct to be examined.
29583  *
29584  *     Context: Any
29585  */
29586 
29587 static int
29588 sd_failfast_flushq_callback(struct buf *bp)
29589 {
29590 	/*
29591 	 * Return TRUE if (1) we want to flush ALL bufs when the failfast
29592 	 * state is entered; OR (2) the given bp has B_FAILFAST set.
29593 	 */
29594 	return (((sd_failfast_flushctl & SD_FAILFAST_FLUSH_ALL_BUFS) ||
29595 	    (bp->b_flags & B_FAILFAST)) ? TRUE : FALSE);
29596 }
29597 
29598 
29599 
29600 /*
29601  * Function: sd_setup_next_xfer
29602  *
29603  * Description: Prepare next I/O operation using DMA_PARTIAL
29604  *
29605  */
29606 
29607 static int
29608 sd_setup_next_xfer(struct sd_lun *un, struct buf *bp,
29609     struct scsi_pkt *pkt, struct sd_xbuf *xp)
29610 {
29611 	ssize_t	num_blks_not_xfered;
29612 	daddr_t	strt_blk_num;
29613 	ssize_t	bytes_not_xfered;
29614 	int	rval;
29615 
29616 	ASSERT(pkt->pkt_resid == 0);
29617 
29618 	/*
29619 	 * Calculate next block number and amount to be transferred.
29620 	 *
29621 	 * How much data NOT transfered to the HBA yet.
29622 	 */
29623 	bytes_not_xfered = xp->xb_dma_resid;
29624 
29625 	/*
29626 	 * figure how many blocks NOT transfered to the HBA yet.
29627 	 */
29628 	num_blks_not_xfered = SD_BYTES2TGTBLOCKS(un, bytes_not_xfered);
29629 
29630 	/*
29631 	 * set starting block number to the end of what WAS transfered.
29632 	 */
29633 	strt_blk_num = xp->xb_blkno +
29634 	    SD_BYTES2TGTBLOCKS(un, bp->b_bcount - bytes_not_xfered);
29635 
29636 	/*
29637 	 * Move pkt to the next portion of the xfer.  sd_setup_next_rw_pkt
29638 	 * will call scsi_initpkt with NULL_FUNC so we do not have to release
29639 	 * the disk mutex here.
29640 	 */
29641 	rval = sd_setup_next_rw_pkt(un, pkt, bp,
29642 	    strt_blk_num, num_blks_not_xfered);
29643 
29644 	if (rval == 0) {
29645 
29646 		/*
29647 		 * Success.
29648 		 *
29649 		 * Adjust things if there are still more blocks to be
29650 		 * transfered.
29651 		 */
29652 		xp->xb_dma_resid = pkt->pkt_resid;
29653 		pkt->pkt_resid = 0;
29654 
29655 		return (1);
29656 	}
29657 
29658 	/*
29659 	 * There's really only one possible return value from
29660 	 * sd_setup_next_rw_pkt which occurs when scsi_init_pkt
29661 	 * returns NULL.
29662 	 */
29663 	ASSERT(rval == SD_PKT_ALLOC_FAILURE);
29664 
29665 	bp->b_resid = bp->b_bcount;
29666 	bp->b_flags |= B_ERROR;
29667 
29668 	scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
29669 	    "Error setting up next portion of DMA transfer\n");
29670 
29671 	return (0);
29672 }
29673 
29674 /*
29675  *    Function: sd_panic_for_res_conflict
29676  *
29677  * Description: Call panic with a string formatted with "Reservation Conflict"
29678  *		and a human readable identifier indicating the SD instance
29679  *		that experienced the reservation conflict.
29680  *
29681  *   Arguments: un - pointer to the soft state struct for the instance.
29682  *
29683  *     Context: may execute in interrupt context.
29684  */
29685 
29686 #define	SD_RESV_CONFLICT_FMT_LEN 40
29687 void
29688 sd_panic_for_res_conflict(struct sd_lun *un)
29689 {
29690 	char panic_str[SD_RESV_CONFLICT_FMT_LEN+MAXPATHLEN];
29691 	char path_str[MAXPATHLEN];
29692 
29693 	(void) snprintf(panic_str, sizeof (panic_str),
29694 	    "Reservation Conflict\nDisk: %s",
29695 	    ddi_pathname(SD_DEVINFO(un), path_str));
29696 
29697 	panic(panic_str);
29698 }
29699 
29700 /*
29701  * Note: The following sd_faultinjection_ioctl( ) routines implement
29702  * driver support for handling fault injection for error analysis
29703  * causing faults in multiple layers of the driver.
29704  *
29705  */
29706 
29707 #ifdef SD_FAULT_INJECTION
29708 static uint_t   sd_fault_injection_on = 0;
29709 
29710 /*
29711  *    Function: sd_faultinjection_ioctl()
29712  *
29713  * Description: This routine is the driver entry point for handling
29714  *              faultinjection ioctls to inject errors into the
29715  *              layer model
29716  *
29717  *   Arguments: cmd	- the ioctl cmd received
29718  *		arg	- the arguments from user and returns
29719  */
29720 
29721 static void
29722 sd_faultinjection_ioctl(int cmd, intptr_t arg,  struct sd_lun *un) {
29723 
29724 	uint_t i = 0;
29725 	uint_t rval;
29726 
29727 	SD_TRACE(SD_LOG_IOERR, un, "sd_faultinjection_ioctl: entry\n");
29728 
29729 	mutex_enter(SD_MUTEX(un));
29730 
29731 	switch (cmd) {
29732 	case SDIOCRUN:
29733 		/* Allow pushed faults to be injected */
29734 		SD_INFO(SD_LOG_SDTEST, un,
29735 		    "sd_faultinjection_ioctl: Injecting Fault Run\n");
29736 
29737 		sd_fault_injection_on = 1;
29738 
29739 		SD_INFO(SD_LOG_IOERR, un,
29740 		    "sd_faultinjection_ioctl: run finished\n");
29741 		break;
29742 
29743 	case SDIOCSTART:
29744 		/* Start Injection Session */
29745 		SD_INFO(SD_LOG_SDTEST, un,
29746 		    "sd_faultinjection_ioctl: Injecting Fault Start\n");
29747 
29748 		sd_fault_injection_on = 0;
29749 		un->sd_injection_mask = 0xFFFFFFFF;
29750 		for (i = 0; i < SD_FI_MAX_ERROR; i++) {
29751 			un->sd_fi_fifo_pkt[i] = NULL;
29752 			un->sd_fi_fifo_xb[i] = NULL;
29753 			un->sd_fi_fifo_un[i] = NULL;
29754 			un->sd_fi_fifo_arq[i] = NULL;
29755 		}
29756 		un->sd_fi_fifo_start = 0;
29757 		un->sd_fi_fifo_end = 0;
29758 
29759 		mutex_enter(&(un->un_fi_mutex));
29760 		un->sd_fi_log[0] = '\0';
29761 		un->sd_fi_buf_len = 0;
29762 		mutex_exit(&(un->un_fi_mutex));
29763 
29764 		SD_INFO(SD_LOG_IOERR, un,
29765 		    "sd_faultinjection_ioctl: start finished\n");
29766 		break;
29767 
29768 	case SDIOCSTOP:
29769 		/* Stop Injection Session */
29770 		SD_INFO(SD_LOG_SDTEST, un,
29771 		    "sd_faultinjection_ioctl: Injecting Fault Stop\n");
29772 		sd_fault_injection_on = 0;
29773 		un->sd_injection_mask = 0x0;
29774 
29775 		/* Empty stray or unuseds structs from fifo */
29776 		for (i = 0; i < SD_FI_MAX_ERROR; i++) {
29777 			if (un->sd_fi_fifo_pkt[i] != NULL) {
29778 				kmem_free(un->sd_fi_fifo_pkt[i],
29779 				    sizeof (struct sd_fi_pkt));
29780 			}
29781 			if (un->sd_fi_fifo_xb[i] != NULL) {
29782 				kmem_free(un->sd_fi_fifo_xb[i],
29783 				    sizeof (struct sd_fi_xb));
29784 			}
29785 			if (un->sd_fi_fifo_un[i] != NULL) {
29786 				kmem_free(un->sd_fi_fifo_un[i],
29787 				    sizeof (struct sd_fi_un));
29788 			}
29789 			if (un->sd_fi_fifo_arq[i] != NULL) {
29790 				kmem_free(un->sd_fi_fifo_arq[i],
29791 				    sizeof (struct sd_fi_arq));
29792 			}
29793 			un->sd_fi_fifo_pkt[i] = NULL;
29794 			un->sd_fi_fifo_un[i] = NULL;
29795 			un->sd_fi_fifo_xb[i] = NULL;
29796 			un->sd_fi_fifo_arq[i] = NULL;
29797 		}
29798 		un->sd_fi_fifo_start = 0;
29799 		un->sd_fi_fifo_end = 0;
29800 
29801 		SD_INFO(SD_LOG_IOERR, un,
29802 		    "sd_faultinjection_ioctl: stop finished\n");
29803 		break;
29804 
29805 	case SDIOCINSERTPKT:
29806 		/* Store a packet struct to be pushed onto fifo */
29807 		SD_INFO(SD_LOG_SDTEST, un,
29808 		    "sd_faultinjection_ioctl: Injecting Fault Insert Pkt\n");
29809 
29810 		i = un->sd_fi_fifo_end % SD_FI_MAX_ERROR;
29811 
29812 		sd_fault_injection_on = 0;
29813 
29814 		/* No more that SD_FI_MAX_ERROR allowed in Queue */
29815 		if (un->sd_fi_fifo_pkt[i] != NULL) {
29816 			kmem_free(un->sd_fi_fifo_pkt[i],
29817 			    sizeof (struct sd_fi_pkt));
29818 		}
29819 		if (arg != NULL) {
29820 			un->sd_fi_fifo_pkt[i] =
29821 			    kmem_alloc(sizeof (struct sd_fi_pkt), KM_NOSLEEP);
29822 			if (un->sd_fi_fifo_pkt[i] == NULL) {
29823 				/* Alloc failed don't store anything */
29824 				break;
29825 			}
29826 			rval = ddi_copyin((void *)arg, un->sd_fi_fifo_pkt[i],
29827 			    sizeof (struct sd_fi_pkt), 0);
29828 			if (rval == -1) {
29829 				kmem_free(un->sd_fi_fifo_pkt[i],
29830 				    sizeof (struct sd_fi_pkt));
29831 				un->sd_fi_fifo_pkt[i] = NULL;
29832 			}
29833 		} else {
29834 			SD_INFO(SD_LOG_IOERR, un,
29835 			    "sd_faultinjection_ioctl: pkt null\n");
29836 		}
29837 		break;
29838 
29839 	case SDIOCINSERTXB:
29840 		/* Store a xb struct to be pushed onto fifo */
29841 		SD_INFO(SD_LOG_SDTEST, un,
29842 		    "sd_faultinjection_ioctl: Injecting Fault Insert XB\n");
29843 
29844 		i = un->sd_fi_fifo_end % SD_FI_MAX_ERROR;
29845 
29846 		sd_fault_injection_on = 0;
29847 
29848 		if (un->sd_fi_fifo_xb[i] != NULL) {
29849 			kmem_free(un->sd_fi_fifo_xb[i],
29850 			    sizeof (struct sd_fi_xb));
29851 			un->sd_fi_fifo_xb[i] = NULL;
29852 		}
29853 		if (arg != NULL) {
29854 			un->sd_fi_fifo_xb[i] =
29855 			    kmem_alloc(sizeof (struct sd_fi_xb), KM_NOSLEEP);
29856 			if (un->sd_fi_fifo_xb[i] == NULL) {
29857 				/* Alloc failed don't store anything */
29858 				break;
29859 			}
29860 			rval = ddi_copyin((void *)arg, un->sd_fi_fifo_xb[i],
29861 			    sizeof (struct sd_fi_xb), 0);
29862 
29863 			if (rval == -1) {
29864 				kmem_free(un->sd_fi_fifo_xb[i],
29865 				    sizeof (struct sd_fi_xb));
29866 				un->sd_fi_fifo_xb[i] = NULL;
29867 			}
29868 		} else {
29869 			SD_INFO(SD_LOG_IOERR, un,
29870 			    "sd_faultinjection_ioctl: xb null\n");
29871 		}
29872 		break;
29873 
29874 	case SDIOCINSERTUN:
29875 		/* Store a un struct to be pushed onto fifo */
29876 		SD_INFO(SD_LOG_SDTEST, un,
29877 		    "sd_faultinjection_ioctl: Injecting Fault Insert UN\n");
29878 
29879 		i = un->sd_fi_fifo_end % SD_FI_MAX_ERROR;
29880 
29881 		sd_fault_injection_on = 0;
29882 
29883 		if (un->sd_fi_fifo_un[i] != NULL) {
29884 			kmem_free(un->sd_fi_fifo_un[i],
29885 			    sizeof (struct sd_fi_un));
29886 			un->sd_fi_fifo_un[i] = NULL;
29887 		}
29888 		if (arg != NULL) {
29889 			un->sd_fi_fifo_un[i] =
29890 			    kmem_alloc(sizeof (struct sd_fi_un), KM_NOSLEEP);
29891 			if (un->sd_fi_fifo_un[i] == NULL) {
29892 				/* Alloc failed don't store anything */
29893 				break;
29894 			}
29895 			rval = ddi_copyin((void *)arg, un->sd_fi_fifo_un[i],
29896 			    sizeof (struct sd_fi_un), 0);
29897 			if (rval == -1) {
29898 				kmem_free(un->sd_fi_fifo_un[i],
29899 				    sizeof (struct sd_fi_un));
29900 				un->sd_fi_fifo_un[i] = NULL;
29901 			}
29902 
29903 		} else {
29904 			SD_INFO(SD_LOG_IOERR, un,
29905 			    "sd_faultinjection_ioctl: un null\n");
29906 		}
29907 
29908 		break;
29909 
29910 	case SDIOCINSERTARQ:
29911 		/* Store a arq struct to be pushed onto fifo */
29912 		SD_INFO(SD_LOG_SDTEST, un,
29913 		    "sd_faultinjection_ioctl: Injecting Fault Insert ARQ\n");
29914 		i = un->sd_fi_fifo_end % SD_FI_MAX_ERROR;
29915 
29916 		sd_fault_injection_on = 0;
29917 
29918 		if (un->sd_fi_fifo_arq[i] != NULL) {
29919 			kmem_free(un->sd_fi_fifo_arq[i],
29920 			    sizeof (struct sd_fi_arq));
29921 			un->sd_fi_fifo_arq[i] = NULL;
29922 		}
29923 		if (arg != NULL) {
29924 			un->sd_fi_fifo_arq[i] =
29925 			    kmem_alloc(sizeof (struct sd_fi_arq), KM_NOSLEEP);
29926 			if (un->sd_fi_fifo_arq[i] == NULL) {
29927 				/* Alloc failed don't store anything */
29928 				break;
29929 			}
29930 			rval = ddi_copyin((void *)arg, un->sd_fi_fifo_arq[i],
29931 			    sizeof (struct sd_fi_arq), 0);
29932 			if (rval == -1) {
29933 				kmem_free(un->sd_fi_fifo_arq[i],
29934 				    sizeof (struct sd_fi_arq));
29935 				un->sd_fi_fifo_arq[i] = NULL;
29936 			}
29937 
29938 		} else {
29939 			SD_INFO(SD_LOG_IOERR, un,
29940 			    "sd_faultinjection_ioctl: arq null\n");
29941 		}
29942 
29943 		break;
29944 
29945 	case SDIOCPUSH:
29946 		/* Push stored xb, pkt, un, and arq onto fifo */
29947 		sd_fault_injection_on = 0;
29948 
29949 		if (arg != NULL) {
29950 			rval = ddi_copyin((void *)arg, &i, sizeof (uint_t), 0);
29951 			if (rval != -1 &&
29952 			    un->sd_fi_fifo_end + i < SD_FI_MAX_ERROR) {
29953 				un->sd_fi_fifo_end += i;
29954 			}
29955 		} else {
29956 			SD_INFO(SD_LOG_IOERR, un,
29957 			    "sd_faultinjection_ioctl: push arg null\n");
29958 			if (un->sd_fi_fifo_end + i < SD_FI_MAX_ERROR) {
29959 				un->sd_fi_fifo_end++;
29960 			}
29961 		}
29962 		SD_INFO(SD_LOG_IOERR, un,
29963 		    "sd_faultinjection_ioctl: push to end=%d\n",
29964 		    un->sd_fi_fifo_end);
29965 		break;
29966 
29967 	case SDIOCRETRIEVE:
29968 		/* Return buffer of log from Injection session */
29969 		SD_INFO(SD_LOG_SDTEST, un,
29970 		    "sd_faultinjection_ioctl: Injecting Fault Retreive");
29971 
29972 		sd_fault_injection_on = 0;
29973 
29974 		mutex_enter(&(un->un_fi_mutex));
29975 		rval = ddi_copyout(un->sd_fi_log, (void *)arg,
29976 		    un->sd_fi_buf_len+1, 0);
29977 		mutex_exit(&(un->un_fi_mutex));
29978 
29979 		if (rval == -1) {
29980 			/*
29981 			 * arg is possibly invalid setting
29982 			 * it to NULL for return
29983 			 */
29984 			arg = NULL;
29985 		}
29986 		break;
29987 	}
29988 
29989 	mutex_exit(SD_MUTEX(un));
29990 	SD_TRACE(SD_LOG_IOERR, un, "sd_faultinjection_ioctl:"
29991 			    " exit\n");
29992 }
29993 
29994 
29995 /*
29996  *    Function: sd_injection_log()
29997  *
29998  * Description: This routine adds buff to the already existing injection log
29999  *              for retrieval via faultinjection_ioctl for use in fault
30000  *              detection and recovery
30001  *
30002  *   Arguments: buf - the string to add to the log
30003  */
30004 
30005 static void
30006 sd_injection_log(char *buf, struct sd_lun *un)
30007 {
30008 	uint_t len;
30009 
30010 	ASSERT(un != NULL);
30011 	ASSERT(buf != NULL);
30012 
30013 	mutex_enter(&(un->un_fi_mutex));
30014 
30015 	len = min(strlen(buf), 255);
30016 	/* Add logged value to Injection log to be returned later */
30017 	if (len + un->sd_fi_buf_len < SD_FI_MAX_BUF) {
30018 		uint_t	offset = strlen((char *)un->sd_fi_log);
30019 		char *destp = (char *)un->sd_fi_log + offset;
30020 		int i;
30021 		for (i = 0; i < len; i++) {
30022 			*destp++ = *buf++;
30023 		}
30024 		un->sd_fi_buf_len += len;
30025 		un->sd_fi_log[un->sd_fi_buf_len] = '\0';
30026 	}
30027 
30028 	mutex_exit(&(un->un_fi_mutex));
30029 }
30030 
30031 
30032 /*
30033  *    Function: sd_faultinjection()
30034  *
30035  * Description: This routine takes the pkt and changes its
30036  *		content based on error injection scenerio.
30037  *
30038  *   Arguments: pktp	- packet to be changed
30039  */
30040 
30041 static void
30042 sd_faultinjection(struct scsi_pkt *pktp)
30043 {
30044 	uint_t i;
30045 	struct sd_fi_pkt *fi_pkt;
30046 	struct sd_fi_xb *fi_xb;
30047 	struct sd_fi_un *fi_un;
30048 	struct sd_fi_arq *fi_arq;
30049 	struct buf *bp;
30050 	struct sd_xbuf *xb;
30051 	struct sd_lun *un;
30052 
30053 	ASSERT(pktp != NULL);
30054 
30055 	/* pull bp xb and un from pktp */
30056 	bp = (struct buf *)pktp->pkt_private;
30057 	xb = SD_GET_XBUF(bp);
30058 	un = SD_GET_UN(bp);
30059 
30060 	ASSERT(un != NULL);
30061 
30062 	mutex_enter(SD_MUTEX(un));
30063 
30064 	SD_TRACE(SD_LOG_SDTEST, un,
30065 	    "sd_faultinjection: entry Injection from sdintr\n");
30066 
30067 	/* if injection is off return */
30068 	if (sd_fault_injection_on == 0 ||
30069 	    un->sd_fi_fifo_start == un->sd_fi_fifo_end) {
30070 		mutex_exit(SD_MUTEX(un));
30071 		return;
30072 	}
30073 
30074 	SD_INFO(SD_LOG_SDTEST, un,
30075 	    "sd_faultinjection: is working for copying\n");
30076 
30077 	/* take next set off fifo */
30078 	i = un->sd_fi_fifo_start % SD_FI_MAX_ERROR;
30079 
30080 	fi_pkt = un->sd_fi_fifo_pkt[i];
30081 	fi_xb = un->sd_fi_fifo_xb[i];
30082 	fi_un = un->sd_fi_fifo_un[i];
30083 	fi_arq = un->sd_fi_fifo_arq[i];
30084 
30085 
30086 	/* set variables accordingly */
30087 	/* set pkt if it was on fifo */
30088 	if (fi_pkt != NULL) {
30089 		SD_CONDSET(pktp, pkt, pkt_flags, "pkt_flags");
30090 		SD_CONDSET(*pktp, pkt, pkt_scbp, "pkt_scbp");
30091 		if (fi_pkt->pkt_cdbp != 0xff)
30092 			SD_CONDSET(*pktp, pkt, pkt_cdbp, "pkt_cdbp");
30093 		SD_CONDSET(pktp, pkt, pkt_state, "pkt_state");
30094 		SD_CONDSET(pktp, pkt, pkt_statistics, "pkt_statistics");
30095 		SD_CONDSET(pktp, pkt, pkt_reason, "pkt_reason");
30096 
30097 	}
30098 	/* set xb if it was on fifo */
30099 	if (fi_xb != NULL) {
30100 		SD_CONDSET(xb, xb, xb_blkno, "xb_blkno");
30101 		SD_CONDSET(xb, xb, xb_dma_resid, "xb_dma_resid");
30102 		if (fi_xb->xb_retry_count != 0)
30103 			SD_CONDSET(xb, xb, xb_retry_count, "xb_retry_count");
30104 		SD_CONDSET(xb, xb, xb_victim_retry_count,
30105 		    "xb_victim_retry_count");
30106 		SD_CONDSET(xb, xb, xb_sense_status, "xb_sense_status");
30107 		SD_CONDSET(xb, xb, xb_sense_state, "xb_sense_state");
30108 		SD_CONDSET(xb, xb, xb_sense_resid, "xb_sense_resid");
30109 
30110 		/* copy in block data from sense */
30111 		/*
30112 		 * if (fi_xb->xb_sense_data[0] != -1) {
30113 		 *	bcopy(fi_xb->xb_sense_data, xb->xb_sense_data,
30114 		 *	SENSE_LENGTH);
30115 		 * }
30116 		 */
30117 		bcopy(fi_xb->xb_sense_data, xb->xb_sense_data, SENSE_LENGTH);
30118 
30119 		/* copy in extended sense codes */
30120 		SD_CONDSET(((struct scsi_extended_sense *)xb->xb_sense_data),
30121 		    xb, es_code, "es_code");
30122 		SD_CONDSET(((struct scsi_extended_sense *)xb->xb_sense_data),
30123 		    xb, es_key, "es_key");
30124 		SD_CONDSET(((struct scsi_extended_sense *)xb->xb_sense_data),
30125 		    xb, es_add_code, "es_add_code");
30126 		SD_CONDSET(((struct scsi_extended_sense *)xb->xb_sense_data),
30127 		    xb, es_qual_code, "es_qual_code");
30128 		struct scsi_extended_sense *esp;
30129 		esp = (struct scsi_extended_sense *)xb->xb_sense_data;
30130 		esp->es_class = CLASS_EXTENDED_SENSE;
30131 	}
30132 
30133 	/* set un if it was on fifo */
30134 	if (fi_un != NULL) {
30135 		SD_CONDSET(un->un_sd->sd_inq, un, inq_rmb, "inq_rmb");
30136 		SD_CONDSET(un, un, un_ctype, "un_ctype");
30137 		SD_CONDSET(un, un, un_reset_retry_count,
30138 		    "un_reset_retry_count");
30139 		SD_CONDSET(un, un, un_reservation_type, "un_reservation_type");
30140 		SD_CONDSET(un, un, un_resvd_status, "un_resvd_status");
30141 		SD_CONDSET(un, un, un_f_arq_enabled, "un_f_arq_enabled");
30142 		SD_CONDSET(un, un, un_f_allow_bus_device_reset,
30143 		    "un_f_allow_bus_device_reset");
30144 		SD_CONDSET(un, un, un_f_opt_queueing, "un_f_opt_queueing");
30145 
30146 	}
30147 
30148 	/* copy in auto request sense if it was on fifo */
30149 	if (fi_arq != NULL) {
30150 		bcopy(fi_arq, pktp->pkt_scbp, sizeof (struct sd_fi_arq));
30151 	}
30152 
30153 	/* free structs */
30154 	if (un->sd_fi_fifo_pkt[i] != NULL) {
30155 		kmem_free(un->sd_fi_fifo_pkt[i], sizeof (struct sd_fi_pkt));
30156 	}
30157 	if (un->sd_fi_fifo_xb[i] != NULL) {
30158 		kmem_free(un->sd_fi_fifo_xb[i], sizeof (struct sd_fi_xb));
30159 	}
30160 	if (un->sd_fi_fifo_un[i] != NULL) {
30161 		kmem_free(un->sd_fi_fifo_un[i], sizeof (struct sd_fi_un));
30162 	}
30163 	if (un->sd_fi_fifo_arq[i] != NULL) {
30164 		kmem_free(un->sd_fi_fifo_arq[i], sizeof (struct sd_fi_arq));
30165 	}
30166 
30167 	/*
30168 	 * kmem_free does not gurantee to set to NULL
30169 	 * since we uses these to determine if we set
30170 	 * values or not lets confirm they are always
30171 	 * NULL after free
30172 	 */
30173 	un->sd_fi_fifo_pkt[i] = NULL;
30174 	un->sd_fi_fifo_un[i] = NULL;
30175 	un->sd_fi_fifo_xb[i] = NULL;
30176 	un->sd_fi_fifo_arq[i] = NULL;
30177 
30178 	un->sd_fi_fifo_start++;
30179 
30180 	mutex_exit(SD_MUTEX(un));
30181 
30182 	SD_INFO(SD_LOG_SDTEST, un, "sd_faultinjection: exit\n");
30183 }
30184 
30185 #endif /* SD_FAULT_INJECTION */
30186 
30187 /*
30188  * This routine is invoked in sd_unit_attach(). Before calling it, the
30189  * properties in conf file should be processed already, and "hotpluggable"
30190  * property was processed also.
30191  *
30192  * The sd driver distinguishes 3 different type of devices: removable media,
30193  * non-removable media, and hotpluggable. Below the differences are defined:
30194  *
30195  * 1. Device ID
30196  *
30197  *     The device ID of a device is used to identify this device. Refer to
30198  *     ddi_devid_register(9F).
30199  *
30200  *     For a non-removable media disk device which can provide 0x80 or 0x83
30201  *     VPD page (refer to INQUIRY command of SCSI SPC specification), a unique
30202  *     device ID is created to identify this device. For other non-removable
30203  *     media devices, a default device ID is created only if this device has
30204  *     at least 2 alter cylinders. Otherwise, this device has no devid.
30205  *
30206  *     -------------------------------------------------------
30207  *     removable media   hotpluggable  | Can Have Device ID
30208  *     -------------------------------------------------------
30209  *         false             false     |     Yes
30210  *         false             true      |     Yes
30211  *         true                x       |     No
30212  *     ------------------------------------------------------
30213  *
30214  *
30215  * 2. SCSI group 4 commands
30216  *
30217  *     In SCSI specs, only some commands in group 4 command set can use
30218  *     8-byte addresses that can be used to access >2TB storage spaces.
30219  *     Other commands have no such capability. Without supporting group4,
30220  *     it is impossible to make full use of storage spaces of a disk with
30221  *     capacity larger than 2TB.
30222  *
30223  *     -----------------------------------------------
30224  *     removable media   hotpluggable   LP64  |  Group
30225  *     -----------------------------------------------
30226  *           false          false       false |   1
30227  *           false          false       true  |   4
30228  *           false          true        false |   1
30229  *           false          true        true  |   4
30230  *           true             x           x   |   5
30231  *     -----------------------------------------------
30232  *
30233  *
30234  * 3. Check for VTOC Label
30235  *
30236  *     If a direct-access disk has no EFI label, sd will check if it has a
30237  *     valid VTOC label. Now, sd also does that check for removable media
30238  *     and hotpluggable devices.
30239  *
30240  *     --------------------------------------------------------------
30241  *     Direct-Access   removable media    hotpluggable |  Check Label
30242  *     -------------------------------------------------------------
30243  *         false          false           false        |   No
30244  *         false          false           true         |   No
30245  *         false          true            false        |   Yes
30246  *         false          true            true         |   Yes
30247  *         true            x                x          |   Yes
30248  *     --------------------------------------------------------------
30249  *
30250  *
30251  * 4. Building default VTOC label
30252  *
30253  *     As section 3 says, sd checks if some kinds of devices have VTOC label.
30254  *     If those devices have no valid VTOC label, sd(7d) will attempt to
30255  *     create default VTOC for them. Currently sd creates default VTOC label
30256  *     for all devices on x86 platform (VTOC_16), but only for removable
30257  *     media devices on SPARC (VTOC_8).
30258  *
30259  *     -----------------------------------------------------------
30260  *       removable media hotpluggable platform   |   Default Label
30261  *     -----------------------------------------------------------
30262  *             false          false    sparc     |     No
30263  *             false          true      x86      |     Yes
30264  *             false          true     sparc     |     Yes
30265  *             true             x        x       |     Yes
30266  *     ----------------------------------------------------------
30267  *
30268  *
30269  * 5. Supported blocksizes of target devices
30270  *
30271  *     Sd supports non-512-byte blocksize for removable media devices only.
30272  *     For other devices, only 512-byte blocksize is supported. This may be
30273  *     changed in near future because some RAID devices require non-512-byte
30274  *     blocksize
30275  *
30276  *     -----------------------------------------------------------
30277  *     removable media    hotpluggable    | non-512-byte blocksize
30278  *     -----------------------------------------------------------
30279  *           false          false         |   No
30280  *           false          true          |   No
30281  *           true             x           |   Yes
30282  *     -----------------------------------------------------------
30283  *
30284  *
30285  * 6. Automatic mount & unmount
30286  *
30287  *     Sd(7d) driver provides DKIOCREMOVABLE ioctl. This ioctl is used to query
30288  *     if a device is removable media device. It return 1 for removable media
30289  *     devices, and 0 for others.
30290  *
30291  *     The automatic mounting subsystem should distinguish between the types
30292  *     of devices and apply automounting policies to each.
30293  *
30294  *
30295  * 7. fdisk partition management
30296  *
30297  *     Fdisk is traditional partition method on x86 platform. Sd(7d) driver
30298  *     just supports fdisk partitions on x86 platform. On sparc platform, sd
30299  *     doesn't support fdisk partitions at all. Note: pcfs(7fs) can recognize
30300  *     fdisk partitions on both x86 and SPARC platform.
30301  *
30302  *     -----------------------------------------------------------
30303  *       platform   removable media  USB/1394  |  fdisk supported
30304  *     -----------------------------------------------------------
30305  *        x86         X               X        |       true
30306  *     ------------------------------------------------------------
30307  *        sparc       X               X        |       false
30308  *     ------------------------------------------------------------
30309  *
30310  *
30311  * 8. MBOOT/MBR
30312  *
30313  *     Although sd(7d) doesn't support fdisk on SPARC platform, it does support
30314  *     read/write mboot for removable media devices on sparc platform.
30315  *
30316  *     -----------------------------------------------------------
30317  *       platform   removable media  USB/1394  |  mboot supported
30318  *     -----------------------------------------------------------
30319  *        x86         X               X        |       true
30320  *     ------------------------------------------------------------
30321  *        sparc      false           false     |       false
30322  *        sparc      false           true      |       true
30323  *        sparc      true            false     |       true
30324  *        sparc      true            true      |       true
30325  *     ------------------------------------------------------------
30326  *
30327  *
30328  * 9.  error handling during opening device
30329  *
30330  *     If failed to open a disk device, an errno is returned. For some kinds
30331  *     of errors, different errno is returned depending on if this device is
30332  *     a removable media device. This brings USB/1394 hard disks in line with
30333  *     expected hard disk behavior. It is not expected that this breaks any
30334  *     application.
30335  *
30336  *     ------------------------------------------------------
30337  *       removable media    hotpluggable   |  errno
30338  *     ------------------------------------------------------
30339  *             false          false        |   EIO
30340  *             false          true         |   EIO
30341  *             true             x          |   ENXIO
30342  *     ------------------------------------------------------
30343  *
30344  *
30345  * 11. ioctls: DKIOCEJECT, CDROMEJECT
30346  *
30347  *     These IOCTLs are applicable only to removable media devices.
30348  *
30349  *     -----------------------------------------------------------
30350  *       removable media    hotpluggable   |DKIOCEJECT, CDROMEJECT
30351  *     -----------------------------------------------------------
30352  *             false          false        |     No
30353  *             false          true         |     No
30354  *             true            x           |     Yes
30355  *     -----------------------------------------------------------
30356  *
30357  *
30358  * 12. Kstats for partitions
30359  *
30360  *     sd creates partition kstat for non-removable media devices. USB and
30361  *     Firewire hard disks now have partition kstats
30362  *
30363  *      ------------------------------------------------------
30364  *       removable media    hotpluggable   |   kstat
30365  *      ------------------------------------------------------
30366  *             false          false        |    Yes
30367  *             false          true         |    Yes
30368  *             true             x          |    No
30369  *       ------------------------------------------------------
30370  *
30371  *
30372  * 13. Removable media & hotpluggable properties
30373  *
30374  *     Sd driver creates a "removable-media" property for removable media
30375  *     devices. Parent nexus drivers create a "hotpluggable" property if
30376  *     it supports hotplugging.
30377  *
30378  *     ---------------------------------------------------------------------
30379  *     removable media   hotpluggable |  "removable-media"   " hotpluggable"
30380  *     ---------------------------------------------------------------------
30381  *       false            false       |    No                   No
30382  *       false            true        |    No                   Yes
30383  *       true             false       |    Yes                  No
30384  *       true             true        |    Yes                  Yes
30385  *     ---------------------------------------------------------------------
30386  *
30387  *
30388  * 14. Power Management
30389  *
30390  *     sd only power manages removable media devices or devices that support
30391  *     LOG_SENSE or have a "pm-capable" property  (PSARC/2002/250)
30392  *
30393  *     A parent nexus that supports hotplugging can also set "pm-capable"
30394  *     if the disk can be power managed.
30395  *
30396  *     ------------------------------------------------------------
30397  *       removable media hotpluggable pm-capable  |   power manage
30398  *     ------------------------------------------------------------
30399  *             false          false     false     |     No
30400  *             false          false     true      |     Yes
30401  *             false          true      false     |     No
30402  *             false          true      true      |     Yes
30403  *             true             x        x        |     Yes
30404  *     ------------------------------------------------------------
30405  *
30406  *      USB and firewire hard disks can now be power managed independently
30407  *      of the framebuffer
30408  *
30409  *
30410  * 15. Support for USB disks with capacity larger than 1TB
30411  *
30412  *     Currently, sd doesn't permit a fixed disk device with capacity
30413  *     larger than 1TB to be used in a 32-bit operating system environment.
30414  *     However, sd doesn't do that for removable media devices. Instead, it
30415  *     assumes that removable media devices cannot have a capacity larger
30416  *     than 1TB. Therefore, using those devices on 32-bit system is partially
30417  *     supported, which can cause some unexpected results.
30418  *
30419  *     ---------------------------------------------------------------------
30420  *       removable media    USB/1394 | Capacity > 1TB |   Used in 32-bit env
30421  *     ---------------------------------------------------------------------
30422  *             false          false  |   true         |     no
30423  *             false          true   |   true         |     no
30424  *             true           false  |   true         |     Yes
30425  *             true           true   |   true         |     Yes
30426  *     ---------------------------------------------------------------------
30427  *
30428  *
30429  * 16. Check write-protection at open time
30430  *
30431  *     When a removable media device is being opened for writing without NDELAY
30432  *     flag, sd will check if this device is writable. If attempting to open
30433  *     without NDELAY flag a write-protected device, this operation will abort.
30434  *
30435  *     ------------------------------------------------------------
30436  *       removable media    USB/1394   |   WP Check
30437  *     ------------------------------------------------------------
30438  *             false          false    |     No
30439  *             false          true     |     No
30440  *             true           false    |     Yes
30441  *             true           true     |     Yes
30442  *     ------------------------------------------------------------
30443  *
30444  *
30445  * 17. syslog when corrupted VTOC is encountered
30446  *
30447  *      Currently, if an invalid VTOC is encountered, sd only print syslog
30448  *      for fixed SCSI disks.
30449  *     ------------------------------------------------------------
30450  *       removable media    USB/1394   |   print syslog
30451  *     ------------------------------------------------------------
30452  *             false          false    |     Yes
30453  *             false          true     |     No
30454  *             true           false    |     No
30455  *             true           true     |     No
30456  *     ------------------------------------------------------------
30457  */
30458 static void
30459 sd_set_unit_attributes(struct sd_lun *un, dev_info_t *devi)
30460 {
30461 	int	pm_cap;
30462 
30463 	ASSERT(un->un_sd);
30464 	ASSERT(un->un_sd->sd_inq);
30465 
30466 	/*
30467 	 * Enable SYNC CACHE support for all devices.
30468 	 */
30469 	un->un_f_sync_cache_supported = TRUE;
30470 
30471 	/*
30472 	 * Set the sync cache required flag to false.
30473 	 * This would ensure that there is no SYNC CACHE
30474 	 * sent when there are no writes
30475 	 */
30476 	un->un_f_sync_cache_required = FALSE;
30477 
30478 	if (un->un_sd->sd_inq->inq_rmb) {
30479 		/*
30480 		 * The media of this device is removable. And for this kind
30481 		 * of devices, it is possible to change medium after opening
30482 		 * devices. Thus we should support this operation.
30483 		 */
30484 		un->un_f_has_removable_media = TRUE;
30485 
30486 		/*
30487 		 * support non-512-byte blocksize of removable media devices
30488 		 */
30489 		un->un_f_non_devbsize_supported = TRUE;
30490 
30491 		/*
30492 		 * Assume that all removable media devices support DOOR_LOCK
30493 		 */
30494 		un->un_f_doorlock_supported = TRUE;
30495 
30496 		/*
30497 		 * For a removable media device, it is possible to be opened
30498 		 * with NDELAY flag when there is no media in drive, in this
30499 		 * case we don't care if device is writable. But if without
30500 		 * NDELAY flag, we need to check if media is write-protected.
30501 		 */
30502 		un->un_f_chk_wp_open = TRUE;
30503 
30504 		/*
30505 		 * need to start a SCSI watch thread to monitor media state,
30506 		 * when media is being inserted or ejected, notify syseventd.
30507 		 */
30508 		un->un_f_monitor_media_state = TRUE;
30509 
30510 		/*
30511 		 * Some devices don't support START_STOP_UNIT command.
30512 		 * Therefore, we'd better check if a device supports it
30513 		 * before sending it.
30514 		 */
30515 		un->un_f_check_start_stop = TRUE;
30516 
30517 		/*
30518 		 * support eject media ioctl:
30519 		 *		FDEJECT, DKIOCEJECT, CDROMEJECT
30520 		 */
30521 		un->un_f_eject_media_supported = TRUE;
30522 
30523 		/*
30524 		 * Because many removable-media devices don't support
30525 		 * LOG_SENSE, we couldn't use this command to check if
30526 		 * a removable media device support power-management.
30527 		 * We assume that they support power-management via
30528 		 * START_STOP_UNIT command and can be spun up and down
30529 		 * without limitations.
30530 		 */
30531 		un->un_f_pm_supported = TRUE;
30532 
30533 		/*
30534 		 * Need to create a zero length (Boolean) property
30535 		 * removable-media for the removable media devices.
30536 		 * Note that the return value of the property is not being
30537 		 * checked, since if unable to create the property
30538 		 * then do not want the attach to fail altogether. Consistent
30539 		 * with other property creation in attach.
30540 		 */
30541 		(void) ddi_prop_create(DDI_DEV_T_NONE, devi,
30542 		    DDI_PROP_CANSLEEP, "removable-media", NULL, 0);
30543 
30544 	} else {
30545 		/*
30546 		 * create device ID for device
30547 		 */
30548 		un->un_f_devid_supported = TRUE;
30549 
30550 		/*
30551 		 * Spin up non-removable-media devices once it is attached
30552 		 */
30553 		un->un_f_attach_spinup = TRUE;
30554 
30555 		/*
30556 		 * According to SCSI specification, Sense data has two kinds of
30557 		 * format: fixed format, and descriptor format. At present, we
30558 		 * don't support descriptor format sense data for removable
30559 		 * media.
30560 		 */
30561 		if (SD_INQUIRY(un)->inq_dtype == DTYPE_DIRECT) {
30562 			un->un_f_descr_format_supported = TRUE;
30563 		}
30564 
30565 		/*
30566 		 * kstats are created only for non-removable media devices.
30567 		 *
30568 		 * Set this in sd.conf to 0 in order to disable kstats.  The
30569 		 * default is 1, so they are enabled by default.
30570 		 */
30571 		un->un_f_pkstats_enabled = (ddi_prop_get_int(DDI_DEV_T_ANY,
30572 		    SD_DEVINFO(un), DDI_PROP_DONTPASS,
30573 		    "enable-partition-kstats", 1));
30574 
30575 		/*
30576 		 * Check if HBA has set the "pm-capable" property.
30577 		 * If "pm-capable" exists and is non-zero then we can
30578 		 * power manage the device without checking the start/stop
30579 		 * cycle count log sense page.
30580 		 *
30581 		 * If "pm-capable" exists and is set to be false (0),
30582 		 * then we should not power manage the device.
30583 		 *
30584 		 * If "pm-capable" doesn't exist then pm_cap will
30585 		 * be set to SD_PM_CAPABLE_UNDEFINED (-1).  In this case,
30586 		 * sd will check the start/stop cycle count log sense page
30587 		 * and power manage the device if the cycle count limit has
30588 		 * not been exceeded.
30589 		 */
30590 		pm_cap = ddi_prop_get_int(DDI_DEV_T_ANY, devi,
30591 		    DDI_PROP_DONTPASS, "pm-capable", SD_PM_CAPABLE_UNDEFINED);
30592 		if (SD_PM_CAPABLE_IS_UNDEFINED(pm_cap)) {
30593 			un->un_f_log_sense_supported = TRUE;
30594 			if (!un->un_f_power_condition_disabled &&
30595 			    SD_INQUIRY(un)->inq_ansi == 6) {
30596 				un->un_f_power_condition_supported = TRUE;
30597 			}
30598 		} else {
30599 			/*
30600 			 * pm-capable property exists.
30601 			 *
30602 			 * Convert "TRUE" values for pm_cap to
30603 			 * SD_PM_CAPABLE_IS_TRUE to make it easier to check
30604 			 * later. "TRUE" values are any values defined in
30605 			 * inquiry.h.
30606 			 */
30607 			if (SD_PM_CAPABLE_IS_FALSE(pm_cap)) {
30608 				un->un_f_log_sense_supported = FALSE;
30609 			} else {
30610 				/* SD_PM_CAPABLE_IS_TRUE case */
30611 				un->un_f_pm_supported = TRUE;
30612 				if (!un->un_f_power_condition_disabled &&
30613 				    SD_PM_CAPABLE_IS_SPC_4(pm_cap)) {
30614 					un->un_f_power_condition_supported =
30615 					    TRUE;
30616 				}
30617 				if (SD_PM_CAP_LOG_SUPPORTED(pm_cap)) {
30618 					un->un_f_log_sense_supported = TRUE;
30619 					un->un_f_pm_log_sense_smart =
30620 					    SD_PM_CAP_SMART_LOG(pm_cap);
30621 				}
30622 			}
30623 
30624 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
30625 			    "sd_unit_attach: un:0x%p pm-capable "
30626 			    "property set to %d.\n", un, un->un_f_pm_supported);
30627 		}
30628 	}
30629 
30630 	if (un->un_f_is_hotpluggable) {
30631 
30632 		/*
30633 		 * Have to watch hotpluggable devices as well, since
30634 		 * that's the only way for userland applications to
30635 		 * detect hot removal while device is busy/mounted.
30636 		 */
30637 		un->un_f_monitor_media_state = TRUE;
30638 
30639 		un->un_f_check_start_stop = TRUE;
30640 
30641 	}
30642 }
30643 
30644 /*
30645  * sd_tg_rdwr:
30646  * Provides rdwr access for cmlb via sd_tgops. The start_block is
30647  * in sys block size, req_length in bytes.
30648  *
30649  */
30650 static int
30651 sd_tg_rdwr(dev_info_t *devi, uchar_t cmd, void *bufaddr,
30652     diskaddr_t start_block, size_t reqlength, void *tg_cookie)
30653 {
30654 	struct sd_lun *un;
30655 	int path_flag = (int)(uintptr_t)tg_cookie;
30656 	char *dkl = NULL;
30657 	diskaddr_t real_addr = start_block;
30658 	diskaddr_t first_byte, end_block;
30659 
30660 	size_t	buffer_size = reqlength;
30661 	int rval = 0;
30662 	diskaddr_t	cap;
30663 	uint32_t	lbasize;
30664 	sd_ssc_t	*ssc;
30665 
30666 	un = ddi_get_soft_state(sd_state, ddi_get_instance(devi));
30667 	if (un == NULL)
30668 		return (ENXIO);
30669 
30670 	if (cmd != TG_READ && cmd != TG_WRITE)
30671 		return (EINVAL);
30672 
30673 	ssc = sd_ssc_init(un);
30674 	mutex_enter(SD_MUTEX(un));
30675 	if (un->un_f_tgt_blocksize_is_valid == FALSE) {
30676 		mutex_exit(SD_MUTEX(un));
30677 		rval = sd_send_scsi_READ_CAPACITY(ssc, (uint64_t *)&cap,
30678 		    &lbasize, path_flag);
30679 		if (rval != 0)
30680 			goto done1;
30681 		mutex_enter(SD_MUTEX(un));
30682 		sd_update_block_info(un, lbasize, cap);
30683 		if ((un->un_f_tgt_blocksize_is_valid == FALSE)) {
30684 			mutex_exit(SD_MUTEX(un));
30685 			rval = EIO;
30686 			goto done;
30687 		}
30688 	}
30689 
30690 	if (NOT_DEVBSIZE(un)) {
30691 		/*
30692 		 * sys_blocksize != tgt_blocksize, need to re-adjust
30693 		 * blkno and save the index to beginning of dk_label
30694 		 */
30695 		first_byte  = SD_SYSBLOCKS2BYTES(start_block);
30696 		real_addr = first_byte / un->un_tgt_blocksize;
30697 
30698 		end_block = (first_byte + reqlength +
30699 		    un->un_tgt_blocksize - 1) / un->un_tgt_blocksize;
30700 
30701 		/* round up buffer size to multiple of target block size */
30702 		buffer_size = (end_block - real_addr) * un->un_tgt_blocksize;
30703 
30704 		SD_TRACE(SD_LOG_IO_PARTITION, un, "sd_tg_rdwr",
30705 		    "label_addr: 0x%x allocation size: 0x%x\n",
30706 		    real_addr, buffer_size);
30707 
30708 		if (((first_byte % un->un_tgt_blocksize) != 0) ||
30709 		    (reqlength % un->un_tgt_blocksize) != 0)
30710 			/* the request is not aligned */
30711 			dkl = kmem_zalloc(buffer_size, KM_SLEEP);
30712 	}
30713 
30714 	/*
30715 	 * The MMC standard allows READ CAPACITY to be
30716 	 * inaccurate by a bounded amount (in the interest of
30717 	 * response latency).  As a result, failed READs are
30718 	 * commonplace (due to the reading of metadata and not
30719 	 * data). Depending on the per-Vendor/drive Sense data,
30720 	 * the failed READ can cause many (unnecessary) retries.
30721 	 */
30722 
30723 	if (ISCD(un) && (cmd == TG_READ) &&
30724 	    (un->un_f_blockcount_is_valid == TRUE) &&
30725 	    ((start_block == (un->un_blockcount - 1))||
30726 	    (start_block == (un->un_blockcount - 2)))) {
30727 			path_flag = SD_PATH_DIRECT_PRIORITY;
30728 	}
30729 
30730 	mutex_exit(SD_MUTEX(un));
30731 	if (cmd == TG_READ) {
30732 		rval = sd_send_scsi_READ(ssc, (dkl != NULL)? dkl: bufaddr,
30733 		    buffer_size, real_addr, path_flag);
30734 		if (dkl != NULL)
30735 			bcopy(dkl + SD_TGTBYTEOFFSET(un, start_block,
30736 			    real_addr), bufaddr, reqlength);
30737 	} else {
30738 		if (dkl) {
30739 			rval = sd_send_scsi_READ(ssc, dkl, buffer_size,
30740 			    real_addr, path_flag);
30741 			if (rval) {
30742 				goto done1;
30743 			}
30744 			bcopy(bufaddr, dkl + SD_TGTBYTEOFFSET(un, start_block,
30745 			    real_addr), reqlength);
30746 		}
30747 		rval = sd_send_scsi_WRITE(ssc, (dkl != NULL)? dkl: bufaddr,
30748 		    buffer_size, real_addr, path_flag);
30749 	}
30750 
30751 done1:
30752 	if (dkl != NULL)
30753 		kmem_free(dkl, buffer_size);
30754 
30755 	if (rval != 0) {
30756 		if (rval == EIO)
30757 			sd_ssc_assessment(ssc, SD_FMT_STATUS_CHECK);
30758 		else
30759 			sd_ssc_assessment(ssc, SD_FMT_IGNORE);
30760 	}
30761 done:
30762 	sd_ssc_fini(ssc);
30763 	return (rval);
30764 }
30765 
30766 
30767 static int
30768 sd_tg_getinfo(dev_info_t *devi, int cmd, void *arg, void *tg_cookie)
30769 {
30770 
30771 	struct sd_lun *un;
30772 	diskaddr_t	cap;
30773 	uint32_t	lbasize;
30774 	int		path_flag = (int)(uintptr_t)tg_cookie;
30775 	int		ret = 0;
30776 
30777 	un = ddi_get_soft_state(sd_state, ddi_get_instance(devi));
30778 	if (un == NULL)
30779 		return (ENXIO);
30780 
30781 	switch (cmd) {
30782 	case TG_GETPHYGEOM:
30783 	case TG_GETVIRTGEOM:
30784 	case TG_GETCAPACITY:
30785 	case TG_GETBLOCKSIZE:
30786 		mutex_enter(SD_MUTEX(un));
30787 
30788 		if ((un->un_f_blockcount_is_valid == TRUE) &&
30789 		    (un->un_f_tgt_blocksize_is_valid == TRUE)) {
30790 			cap = un->un_blockcount;
30791 			lbasize = un->un_tgt_blocksize;
30792 			mutex_exit(SD_MUTEX(un));
30793 		} else {
30794 			sd_ssc_t	*ssc;
30795 			mutex_exit(SD_MUTEX(un));
30796 			ssc = sd_ssc_init(un);
30797 			ret = sd_send_scsi_READ_CAPACITY(ssc, (uint64_t *)&cap,
30798 			    &lbasize, path_flag);
30799 			if (ret != 0) {
30800 				if (ret == EIO)
30801 					sd_ssc_assessment(ssc,
30802 					    SD_FMT_STATUS_CHECK);
30803 				else
30804 					sd_ssc_assessment(ssc,
30805 					    SD_FMT_IGNORE);
30806 				sd_ssc_fini(ssc);
30807 				return (ret);
30808 			}
30809 			sd_ssc_fini(ssc);
30810 			mutex_enter(SD_MUTEX(un));
30811 			sd_update_block_info(un, lbasize, cap);
30812 			if ((un->un_f_blockcount_is_valid == FALSE) ||
30813 			    (un->un_f_tgt_blocksize_is_valid == FALSE)) {
30814 				mutex_exit(SD_MUTEX(un));
30815 				return (EIO);
30816 			}
30817 			mutex_exit(SD_MUTEX(un));
30818 		}
30819 
30820 		if (cmd == TG_GETCAPACITY) {
30821 			*(diskaddr_t *)arg = cap;
30822 			return (0);
30823 		}
30824 
30825 		if (cmd == TG_GETBLOCKSIZE) {
30826 			*(uint32_t *)arg = lbasize;
30827 			return (0);
30828 		}
30829 
30830 		if (cmd == TG_GETPHYGEOM)
30831 			ret = sd_get_physical_geometry(un, (cmlb_geom_t *)arg,
30832 			    cap, lbasize, path_flag);
30833 		else
30834 			/* TG_GETVIRTGEOM */
30835 			ret = sd_get_virtual_geometry(un,
30836 			    (cmlb_geom_t *)arg, cap, lbasize);
30837 
30838 		return (ret);
30839 
30840 	case TG_GETATTR:
30841 		mutex_enter(SD_MUTEX(un));
30842 		((tg_attribute_t *)arg)->media_is_writable =
30843 		    un->un_f_mmc_writable_media;
30844 		((tg_attribute_t *)arg)->media_is_solid_state =
30845 		    un->un_f_is_solid_state;
30846 		mutex_exit(SD_MUTEX(un));
30847 		return (0);
30848 	default:
30849 		return (ENOTTY);
30850 
30851 	}
30852 }
30853 
30854 /*
30855  *    Function: sd_ssc_ereport_post
30856  *
30857  * Description: Will be called when SD driver need to post an ereport.
30858  *
30859  *    Context: Kernel thread or interrupt context.
30860  */
30861 static void
30862 sd_ssc_ereport_post(sd_ssc_t *ssc, enum sd_driver_assessment drv_assess)
30863 {
30864 	int uscsi_path_instance = 0;
30865 	uchar_t	uscsi_pkt_reason;
30866 	uint32_t uscsi_pkt_state;
30867 	uint32_t uscsi_pkt_statistics;
30868 	uint64_t uscsi_ena;
30869 	uchar_t op_code;
30870 	uint8_t *sensep;
30871 	union scsi_cdb *cdbp;
30872 	uint_t cdblen = 0;
30873 	uint_t senlen = 0;
30874 	struct sd_lun *un;
30875 	dev_info_t *dip;
30876 	char *devid;
30877 	int ssc_invalid_flags = SSC_FLAGS_INVALID_PKT_REASON |
30878 	    SSC_FLAGS_INVALID_STATUS |
30879 	    SSC_FLAGS_INVALID_SENSE |
30880 	    SSC_FLAGS_INVALID_DATA;
30881 	char assessment[16];
30882 
30883 	ASSERT(ssc != NULL);
30884 	ASSERT(ssc->ssc_uscsi_cmd != NULL);
30885 	ASSERT(ssc->ssc_uscsi_info != NULL);
30886 
30887 	un = ssc->ssc_un;
30888 	ASSERT(un != NULL);
30889 
30890 	dip = un->un_sd->sd_dev;
30891 
30892 	/*
30893 	 * Get the devid:
30894 	 *	devid will only be passed to non-transport error reports.
30895 	 */
30896 	devid = DEVI(dip)->devi_devid_str;
30897 
30898 	/*
30899 	 * If we are syncing or dumping, the command will not be executed
30900 	 * so we bypass this situation.
30901 	 */
30902 	if (ddi_in_panic() || (un->un_state == SD_STATE_SUSPENDED) ||
30903 	    (un->un_state == SD_STATE_DUMPING))
30904 		return;
30905 
30906 	uscsi_pkt_reason = ssc->ssc_uscsi_info->ui_pkt_reason;
30907 	uscsi_path_instance = ssc->ssc_uscsi_cmd->uscsi_path_instance;
30908 	uscsi_pkt_state = ssc->ssc_uscsi_info->ui_pkt_state;
30909 	uscsi_pkt_statistics = ssc->ssc_uscsi_info->ui_pkt_statistics;
30910 	uscsi_ena = ssc->ssc_uscsi_info->ui_ena;
30911 
30912 	sensep = (uint8_t *)ssc->ssc_uscsi_cmd->uscsi_rqbuf;
30913 	cdbp = (union scsi_cdb *)ssc->ssc_uscsi_cmd->uscsi_cdb;
30914 
30915 	/* In rare cases, EG:DOORLOCK, the cdb could be NULL */
30916 	if (cdbp == NULL) {
30917 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
30918 		    "sd_ssc_ereport_post meet empty cdb\n");
30919 		return;
30920 	}
30921 
30922 	op_code = cdbp->scc_cmd;
30923 
30924 	cdblen = (int)ssc->ssc_uscsi_cmd->uscsi_cdblen;
30925 	senlen = (int)(ssc->ssc_uscsi_cmd->uscsi_rqlen -
30926 	    ssc->ssc_uscsi_cmd->uscsi_rqresid);
30927 
30928 	if (senlen > 0)
30929 		ASSERT(sensep != NULL);
30930 
30931 	/*
30932 	 * Initialize drv_assess to corresponding values.
30933 	 * SD_FM_DRV_FATAL will be mapped to "fail" or "fatal" depending
30934 	 * on the sense-key returned back.
30935 	 */
30936 	switch (drv_assess) {
30937 		case SD_FM_DRV_RECOVERY:
30938 			(void) sprintf(assessment, "%s", "recovered");
30939 			break;
30940 		case SD_FM_DRV_RETRY:
30941 			(void) sprintf(assessment, "%s", "retry");
30942 			break;
30943 		case SD_FM_DRV_NOTICE:
30944 			(void) sprintf(assessment, "%s", "info");
30945 			break;
30946 		case SD_FM_DRV_FATAL:
30947 		default:
30948 			(void) sprintf(assessment, "%s", "unknown");
30949 	}
30950 	/*
30951 	 * If drv_assess == SD_FM_DRV_RECOVERY, this should be a recovered
30952 	 * command, we will post ereport.io.scsi.cmd.disk.recovered.
30953 	 * driver-assessment will always be "recovered" here.
30954 	 */
30955 	if (drv_assess == SD_FM_DRV_RECOVERY) {
30956 		scsi_fm_ereport_post(un->un_sd, uscsi_path_instance,
30957 		    "cmd.disk.recovered", uscsi_ena, devid, DDI_NOSLEEP,
30958 		    FM_VERSION, DATA_TYPE_UINT8, FM_EREPORT_VERS0,
30959 		    "driver-assessment", DATA_TYPE_STRING, assessment,
30960 		    "op-code", DATA_TYPE_UINT8, op_code,
30961 		    "cdb", DATA_TYPE_UINT8_ARRAY,
30962 		    cdblen, ssc->ssc_uscsi_cmd->uscsi_cdb,
30963 		    "pkt-reason", DATA_TYPE_UINT8, uscsi_pkt_reason,
30964 		    "pkt-state", DATA_TYPE_UINT32, uscsi_pkt_state,
30965 		    "pkt-stats", DATA_TYPE_UINT32, uscsi_pkt_statistics,
30966 		    NULL);
30967 		return;
30968 	}
30969 
30970 	/*
30971 	 * If there is un-expected/un-decodable data, we should post
30972 	 * ereport.io.scsi.cmd.disk.dev.uderr.
30973 	 * driver-assessment will be set based on parameter drv_assess.
30974 	 * SSC_FLAGS_INVALID_SENSE - invalid sense data sent back.
30975 	 * SSC_FLAGS_INVALID_PKT_REASON - invalid pkt-reason encountered.
30976 	 * SSC_FLAGS_INVALID_STATUS - invalid stat-code encountered.
30977 	 * SSC_FLAGS_INVALID_DATA - invalid data sent back.
30978 	 */
30979 	if (ssc->ssc_flags & ssc_invalid_flags) {
30980 		if (ssc->ssc_flags & SSC_FLAGS_INVALID_SENSE) {
30981 			scsi_fm_ereport_post(un->un_sd, uscsi_path_instance,
30982 			    "cmd.disk.dev.uderr", uscsi_ena, devid, DDI_NOSLEEP,
30983 			    FM_VERSION, DATA_TYPE_UINT8, FM_EREPORT_VERS0,
30984 			    "driver-assessment", DATA_TYPE_STRING,
30985 			    drv_assess == SD_FM_DRV_FATAL ?
30986 			    "fail" : assessment,
30987 			    "op-code", DATA_TYPE_UINT8, op_code,
30988 			    "cdb", DATA_TYPE_UINT8_ARRAY,
30989 			    cdblen, ssc->ssc_uscsi_cmd->uscsi_cdb,
30990 			    "pkt-reason", DATA_TYPE_UINT8, uscsi_pkt_reason,
30991 			    "pkt-state", DATA_TYPE_UINT32, uscsi_pkt_state,
30992 			    "pkt-stats", DATA_TYPE_UINT32,
30993 			    uscsi_pkt_statistics,
30994 			    "stat-code", DATA_TYPE_UINT8,
30995 			    ssc->ssc_uscsi_cmd->uscsi_status,
30996 			    "un-decode-info", DATA_TYPE_STRING,
30997 			    ssc->ssc_info,
30998 			    "un-decode-value", DATA_TYPE_UINT8_ARRAY,
30999 			    senlen, sensep,
31000 			    NULL);
31001 		} else {
31002 			/*
31003 			 * For other type of invalid data, the
31004 			 * un-decode-value field would be empty because the
31005 			 * un-decodable content could be seen from upper
31006 			 * level payload or inside un-decode-info.
31007 			 */
31008 			scsi_fm_ereport_post(un->un_sd, uscsi_path_instance,
31009 			    "cmd.disk.dev.uderr", uscsi_ena, devid, DDI_NOSLEEP,
31010 			    FM_VERSION, DATA_TYPE_UINT8, FM_EREPORT_VERS0,
31011 			    "driver-assessment", DATA_TYPE_STRING,
31012 			    drv_assess == SD_FM_DRV_FATAL ?
31013 			    "fail" : assessment,
31014 			    "op-code", DATA_TYPE_UINT8, op_code,
31015 			    "cdb", DATA_TYPE_UINT8_ARRAY,
31016 			    cdblen, ssc->ssc_uscsi_cmd->uscsi_cdb,
31017 			    "pkt-reason", DATA_TYPE_UINT8, uscsi_pkt_reason,
31018 			    "pkt-state", DATA_TYPE_UINT32, uscsi_pkt_state,
31019 			    "pkt-stats", DATA_TYPE_UINT32,
31020 			    uscsi_pkt_statistics,
31021 			    "stat-code", DATA_TYPE_UINT8,
31022 			    ssc->ssc_uscsi_cmd->uscsi_status,
31023 			    "un-decode-info", DATA_TYPE_STRING,
31024 			    ssc->ssc_info,
31025 			    "un-decode-value", DATA_TYPE_UINT8_ARRAY,
31026 			    0, NULL,
31027 			    NULL);
31028 		}
31029 		ssc->ssc_flags &= ~ssc_invalid_flags;
31030 		return;
31031 	}
31032 
31033 	if (uscsi_pkt_reason != CMD_CMPLT ||
31034 	    (ssc->ssc_flags & SSC_FLAGS_TRAN_ABORT)) {
31035 		/*
31036 		 * pkt-reason != CMD_CMPLT or SSC_FLAGS_TRAN_ABORT was
31037 		 * set inside sd_start_cmds due to errors(bad packet or
31038 		 * fatal transport error), we should take it as a
31039 		 * transport error, so we post ereport.io.scsi.cmd.disk.tran.
31040 		 * driver-assessment will be set based on drv_assess.
31041 		 * We will set devid to NULL because it is a transport
31042 		 * error.
31043 		 */
31044 		if (ssc->ssc_flags & SSC_FLAGS_TRAN_ABORT)
31045 			ssc->ssc_flags &= ~SSC_FLAGS_TRAN_ABORT;
31046 
31047 		scsi_fm_ereport_post(un->un_sd, uscsi_path_instance,
31048 		    "cmd.disk.tran", uscsi_ena, NULL, DDI_NOSLEEP, FM_VERSION,
31049 		    DATA_TYPE_UINT8, FM_EREPORT_VERS0,
31050 		    "driver-assessment", DATA_TYPE_STRING,
31051 		    drv_assess == SD_FM_DRV_FATAL ? "fail" : assessment,
31052 		    "op-code", DATA_TYPE_UINT8, op_code,
31053 		    "cdb", DATA_TYPE_UINT8_ARRAY,
31054 		    cdblen, ssc->ssc_uscsi_cmd->uscsi_cdb,
31055 		    "pkt-reason", DATA_TYPE_UINT8, uscsi_pkt_reason,
31056 		    "pkt-state", DATA_TYPE_UINT8, uscsi_pkt_state,
31057 		    "pkt-stats", DATA_TYPE_UINT32, uscsi_pkt_statistics,
31058 		    NULL);
31059 	} else {
31060 		/*
31061 		 * If we got here, we have a completed command, and we need
31062 		 * to further investigate the sense data to see what kind
31063 		 * of ereport we should post.
31064 		 * Post ereport.io.scsi.cmd.disk.dev.rqs.merr
31065 		 * if sense-key == 0x3.
31066 		 * Post ereport.io.scsi.cmd.disk.dev.rqs.derr otherwise.
31067 		 * driver-assessment will be set based on the parameter
31068 		 * drv_assess.
31069 		 */
31070 		if (senlen > 0) {
31071 			/*
31072 			 * Here we have sense data available.
31073 			 */
31074 			uint8_t sense_key;
31075 			sense_key = scsi_sense_key(sensep);
31076 			if (sense_key == 0x3) {
31077 				/*
31078 				 * sense-key == 0x3(medium error),
31079 				 * driver-assessment should be "fatal" if
31080 				 * drv_assess is SD_FM_DRV_FATAL.
31081 				 */
31082 				scsi_fm_ereport_post(un->un_sd,
31083 				    uscsi_path_instance,
31084 				    "cmd.disk.dev.rqs.merr",
31085 				    uscsi_ena, devid, DDI_NOSLEEP, FM_VERSION,
31086 				    DATA_TYPE_UINT8, FM_EREPORT_VERS0,
31087 				    "driver-assessment",
31088 				    DATA_TYPE_STRING,
31089 				    drv_assess == SD_FM_DRV_FATAL ?
31090 				    "fatal" : assessment,
31091 				    "op-code",
31092 				    DATA_TYPE_UINT8, op_code,
31093 				    "cdb",
31094 				    DATA_TYPE_UINT8_ARRAY, cdblen,
31095 				    ssc->ssc_uscsi_cmd->uscsi_cdb,
31096 				    "pkt-reason",
31097 				    DATA_TYPE_UINT8, uscsi_pkt_reason,
31098 				    "pkt-state",
31099 				    DATA_TYPE_UINT8, uscsi_pkt_state,
31100 				    "pkt-stats",
31101 				    DATA_TYPE_UINT32,
31102 				    uscsi_pkt_statistics,
31103 				    "stat-code",
31104 				    DATA_TYPE_UINT8,
31105 				    ssc->ssc_uscsi_cmd->uscsi_status,
31106 				    "key",
31107 				    DATA_TYPE_UINT8,
31108 				    scsi_sense_key(sensep),
31109 				    "asc",
31110 				    DATA_TYPE_UINT8,
31111 				    scsi_sense_asc(sensep),
31112 				    "ascq",
31113 				    DATA_TYPE_UINT8,
31114 				    scsi_sense_ascq(sensep),
31115 				    "sense-data",
31116 				    DATA_TYPE_UINT8_ARRAY,
31117 				    senlen, sensep,
31118 				    "lba",
31119 				    DATA_TYPE_UINT64,
31120 				    ssc->ssc_uscsi_info->ui_lba,
31121 				    NULL);
31122 				} else {
31123 					/*
31124 					 * if sense-key == 0x4(hardware
31125 					 * error), driver-assessment should
31126 					 * be "fatal" if drv_assess is
31127 					 * SD_FM_DRV_FATAL.
31128 					 */
31129 					scsi_fm_ereport_post(un->un_sd,
31130 					    uscsi_path_instance,
31131 					    "cmd.disk.dev.rqs.derr",
31132 					    uscsi_ena, devid, DDI_NOSLEEP,
31133 					    FM_VERSION,
31134 					    DATA_TYPE_UINT8, FM_EREPORT_VERS0,
31135 					    "driver-assessment",
31136 					    DATA_TYPE_STRING,
31137 					    drv_assess == SD_FM_DRV_FATAL ?
31138 					    (sense_key == 0x4 ?
31139 					    "fatal" : "fail") : assessment,
31140 					    "op-code",
31141 					    DATA_TYPE_UINT8, op_code,
31142 					    "cdb",
31143 					    DATA_TYPE_UINT8_ARRAY, cdblen,
31144 					    ssc->ssc_uscsi_cmd->uscsi_cdb,
31145 					    "pkt-reason",
31146 					    DATA_TYPE_UINT8, uscsi_pkt_reason,
31147 					    "pkt-state",
31148 					    DATA_TYPE_UINT8, uscsi_pkt_state,
31149 					    "pkt-stats",
31150 					    DATA_TYPE_UINT32,
31151 					    uscsi_pkt_statistics,
31152 					    "stat-code",
31153 					    DATA_TYPE_UINT8,
31154 					    ssc->ssc_uscsi_cmd->uscsi_status,
31155 					    "key",
31156 					    DATA_TYPE_UINT8,
31157 					    scsi_sense_key(sensep),
31158 					    "asc",
31159 					    DATA_TYPE_UINT8,
31160 					    scsi_sense_asc(sensep),
31161 					    "ascq",
31162 					    DATA_TYPE_UINT8,
31163 					    scsi_sense_ascq(sensep),
31164 					    "sense-data",
31165 					    DATA_TYPE_UINT8_ARRAY,
31166 					    senlen, sensep,
31167 					    NULL);
31168 				}
31169 		} else {
31170 			/*
31171 			 * For stat_code == STATUS_GOOD, this is not a
31172 			 * hardware error.
31173 			 */
31174 			if (ssc->ssc_uscsi_cmd->uscsi_status == STATUS_GOOD)
31175 				return;
31176 
31177 			/*
31178 			 * Post ereport.io.scsi.cmd.disk.dev.serr if we got the
31179 			 * stat-code but with sense data unavailable.
31180 			 * driver-assessment will be set based on parameter
31181 			 * drv_assess.
31182 			 */
31183 			scsi_fm_ereport_post(un->un_sd,
31184 			    uscsi_path_instance, "cmd.disk.dev.serr", uscsi_ena,
31185 			    devid, DDI_NOSLEEP, FM_VERSION, DATA_TYPE_UINT8,
31186 			    FM_EREPORT_VERS0,
31187 			    "driver-assessment", DATA_TYPE_STRING,
31188 			    drv_assess == SD_FM_DRV_FATAL ? "fail" : assessment,
31189 			    "op-code", DATA_TYPE_UINT8, op_code,
31190 			    "cdb",
31191 			    DATA_TYPE_UINT8_ARRAY,
31192 			    cdblen, ssc->ssc_uscsi_cmd->uscsi_cdb,
31193 			    "pkt-reason",
31194 			    DATA_TYPE_UINT8, uscsi_pkt_reason,
31195 			    "pkt-state",
31196 			    DATA_TYPE_UINT8, uscsi_pkt_state,
31197 			    "pkt-stats",
31198 			    DATA_TYPE_UINT32, uscsi_pkt_statistics,
31199 			    "stat-code",
31200 			    DATA_TYPE_UINT8,
31201 			    ssc->ssc_uscsi_cmd->uscsi_status,
31202 			    NULL);
31203 		}
31204 	}
31205 }
31206 
31207 /*
31208  *     Function: sd_ssc_extract_info
31209  *
31210  * Description: Extract information available to help generate ereport.
31211  *
31212  *     Context: Kernel thread or interrupt context.
31213  */
31214 static void
31215 sd_ssc_extract_info(sd_ssc_t *ssc, struct sd_lun *un, struct scsi_pkt *pktp,
31216     struct buf *bp, struct sd_xbuf *xp)
31217 {
31218 	size_t senlen = 0;
31219 	union scsi_cdb *cdbp;
31220 	int path_instance;
31221 	/*
31222 	 * Need scsi_cdb_size array to determine the cdb length.
31223 	 */
31224 	extern uchar_t	scsi_cdb_size[];
31225 
31226 	ASSERT(un != NULL);
31227 	ASSERT(pktp != NULL);
31228 	ASSERT(bp != NULL);
31229 	ASSERT(xp != NULL);
31230 	ASSERT(ssc != NULL);
31231 	ASSERT(mutex_owned(SD_MUTEX(un)));
31232 
31233 	/*
31234 	 * Transfer the cdb buffer pointer here.
31235 	 */
31236 	cdbp = (union scsi_cdb *)pktp->pkt_cdbp;
31237 
31238 	ssc->ssc_uscsi_cmd->uscsi_cdblen = scsi_cdb_size[GETGROUP(cdbp)];
31239 	ssc->ssc_uscsi_cmd->uscsi_cdb = (caddr_t)cdbp;
31240 
31241 	/*
31242 	 * Transfer the sense data buffer pointer if sense data is available,
31243 	 * calculate the sense data length first.
31244 	 */
31245 	if ((xp->xb_sense_state & STATE_XARQ_DONE) ||
31246 	    (xp->xb_sense_state & STATE_ARQ_DONE)) {
31247 		/*
31248 		 * For arq case, we will enter here.
31249 		 */
31250 		if (xp->xb_sense_state & STATE_XARQ_DONE) {
31251 			senlen = MAX_SENSE_LENGTH - xp->xb_sense_resid;
31252 		} else {
31253 			senlen = SENSE_LENGTH;
31254 		}
31255 	} else {
31256 		/*
31257 		 * For non-arq case, we will enter this branch.
31258 		 */
31259 		if (SD_GET_PKT_STATUS(pktp) == STATUS_CHECK &&
31260 		    (xp->xb_sense_state & STATE_XFERRED_DATA)) {
31261 			senlen = SENSE_LENGTH - xp->xb_sense_resid;
31262 		}
31263 
31264 	}
31265 
31266 	ssc->ssc_uscsi_cmd->uscsi_rqlen = (senlen & 0xff);
31267 	ssc->ssc_uscsi_cmd->uscsi_rqresid = 0;
31268 	ssc->ssc_uscsi_cmd->uscsi_rqbuf = (caddr_t)xp->xb_sense_data;
31269 
31270 	ssc->ssc_uscsi_cmd->uscsi_status = ((*(pktp)->pkt_scbp) & STATUS_MASK);
31271 
31272 	/*
31273 	 * Only transfer path_instance when scsi_pkt was properly allocated.
31274 	 */
31275 	path_instance = pktp->pkt_path_instance;
31276 	if (scsi_pkt_allocated_correctly(pktp) && path_instance)
31277 		ssc->ssc_uscsi_cmd->uscsi_path_instance = path_instance;
31278 	else
31279 		ssc->ssc_uscsi_cmd->uscsi_path_instance = 0;
31280 
31281 	/*
31282 	 * Copy in the other fields we may need when posting ereport.
31283 	 */
31284 	ssc->ssc_uscsi_info->ui_pkt_reason = pktp->pkt_reason;
31285 	ssc->ssc_uscsi_info->ui_pkt_state = pktp->pkt_state;
31286 	ssc->ssc_uscsi_info->ui_pkt_statistics = pktp->pkt_statistics;
31287 	ssc->ssc_uscsi_info->ui_lba = (uint64_t)SD_GET_BLKNO(bp);
31288 
31289 	/*
31290 	 * For partially read/write command, we will not create ena
31291 	 * in case of a successful command be reconized as recovered.
31292 	 */
31293 	if ((pktp->pkt_reason == CMD_CMPLT) &&
31294 	    (ssc->ssc_uscsi_cmd->uscsi_status == STATUS_GOOD) &&
31295 	    (senlen == 0)) {
31296 		return;
31297 	}
31298 
31299 	/*
31300 	 * To associate ereports of a single command execution flow, we
31301 	 * need a shared ena for a specific command.
31302 	 */
31303 	if (xp->xb_ena == 0)
31304 		xp->xb_ena = fm_ena_generate(0, FM_ENA_FMT1);
31305 	ssc->ssc_uscsi_info->ui_ena = xp->xb_ena;
31306 }
31307 
31308 
31309 /*
31310  *     Function: sd_check_solid_state
31311  *
31312  * Description: Query the optional INQUIRY VPD page 0xb1. If the device
31313  *              supports VPD page 0xb1, sd examines the MEDIUM ROTATION
31314  *              RATE. If the MEDIUM ROTATION RATE is 1, sd assumes the
31315  *              device is a solid state drive.
31316  *
31317  *     Context: Kernel thread or interrupt context.
31318  */
31319 
31320 static void
31321 sd_check_solid_state(sd_ssc_t *ssc)
31322 {
31323 	int		rval		= 0;
31324 	uchar_t		*inqb1		= NULL;
31325 	size_t		inqb1_len	= MAX_INQUIRY_SIZE;
31326 	size_t		inqb1_resid	= 0;
31327 	struct sd_lun	*un;
31328 
31329 	ASSERT(ssc != NULL);
31330 	un = ssc->ssc_un;
31331 	ASSERT(un != NULL);
31332 	ASSERT(!mutex_owned(SD_MUTEX(un)));
31333 
31334 	mutex_enter(SD_MUTEX(un));
31335 	un->un_f_is_solid_state = FALSE;
31336 
31337 	if (ISCD(un)) {
31338 		mutex_exit(SD_MUTEX(un));
31339 		return;
31340 	}
31341 
31342 	if (sd_check_vpd_page_support(ssc) == 0 &&
31343 	    un->un_vpd_page_mask & SD_VPD_DEV_CHARACTER_PG) {
31344 		mutex_exit(SD_MUTEX(un));
31345 		/* collect page b1 data */
31346 		inqb1 = kmem_zalloc(inqb1_len, KM_SLEEP);
31347 
31348 		rval = sd_send_scsi_INQUIRY(ssc, inqb1, inqb1_len,
31349 		    0x01, 0xB1, &inqb1_resid);
31350 
31351 		if (rval == 0 && (inqb1_len - inqb1_resid > 5)) {
31352 			SD_TRACE(SD_LOG_COMMON, un,
31353 			    "sd_check_solid_state: \
31354 			    successfully get VPD page: %x \
31355 			    PAGE LENGTH: %x BYTE 4: %x \
31356 			    BYTE 5: %x", inqb1[1], inqb1[3], inqb1[4],
31357 			    inqb1[5]);
31358 
31359 			mutex_enter(SD_MUTEX(un));
31360 			/*
31361 			 * Check the MEDIUM ROTATION RATE. If it is set
31362 			 * to 1, the device is a solid state drive.
31363 			 */
31364 			if (inqb1[4] == 0 && inqb1[5] == 1) {
31365 				un->un_f_is_solid_state = TRUE;
31366 			}
31367 			mutex_exit(SD_MUTEX(un));
31368 		} else if (rval != 0) {
31369 			sd_ssc_assessment(ssc, SD_FMT_IGNORE);
31370 		}
31371 
31372 		kmem_free(inqb1, inqb1_len);
31373 	} else {
31374 		mutex_exit(SD_MUTEX(un));
31375 	}
31376 }
31377